Agregar archivos de proyecto.

This commit is contained in:
2026-05-27 17:09:59 +02:00
parent 73b30b7de7
commit 03813aff5a
9144 changed files with 4026729 additions and 0 deletions

View File

@@ -0,0 +1,24 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("TSpdf.StyledXmlParser.tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("TSpdf")]
[assembly: AssemblyProduct("TSpdf")]
[assembly: AssemblyCopyright("Copyright (c) 1987-2023 TSpdf")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("409b5131-4d0c-4e4b-9c7b-2407a8356ca4")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0.0")]
#if !NETSTANDARD2_0
[assembly: NUnit.Framework.Timeout(300000)]
#endif

Binary file not shown.

View File

@@ -0,0 +1,62 @@
<Project Sdk="Microsoft.NET.Sdk" ToolsVersion="15.0">
<PropertyGroup Label="Globals">
<SccProjectName>SAK</SccProjectName>
<SccProvider>SAK</SccProvider>
<SccAuxPath>SAK</SccAuxPath>
<SccLocalPath>SAK</SccLocalPath>
</PropertyGroup>
<PropertyGroup Label="Configuration">
<SignAssembly>True</SignAssembly>
<DelaySign>False</DelaySign>
<RootNamespace />
</PropertyGroup>
<PropertyGroup>
<TargetFrameworks>netcoreapp3.1;net461;net48</TargetFrameworks>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'net461' ">
<OutputType>library</OutputType>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'netcoreapp3.1' ">
<OutputType>Library</OutputType>
<DefineConstants>NETSTANDARD2_0</DefineConstants>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>TSpdf.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<PropertyGroup>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<ApplicationIcon />
<OutputTypeEx>library</OutputTypeEx>
<StartupObject />
<AssemblyName>TSpdf.styledxmlparser.tests</AssemblyName>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="TeamCity.VSTest.TestAdapter" Version="1.0.0" />
<PackageReference Include="NUnit" Version="3.7.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.10.0" />
</ItemGroup>
<ItemGroup>
<None Include="TSpdf.snk" />
<None Include="packages.config" />
</ItemGroup>
<PropertyGroup>
<NoWarn>1701;1702;1591;1570;1572;1573;1574;1580;1584;1658</NoWarn>
</PropertyGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net461' ">
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\TSpdf\TSpdf.io\TSpdf.io.csproj" />
<ProjectReference Include="..\..\TSpdf\TSpdf.layout\TSpdf.layout.csproj" />
<ProjectReference Include="..\..\TSpdf\TSpdf.styledxmlparser\TSpdf.styledxmlparser.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1'">
<PackageReference Include="Microsoft.NET.Test.Sdk">
<Version>15.0.0</Version>
</PackageReference>
<PackageReference Include="System.Runtime.InteropServices.RuntimeInformation">
<Version>4.3.0</Version>
</PackageReference>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,54 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.Layout.Font;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css {
[NUnit.Framework.Category("UnitTest")]
public class CssFontFaceRuleTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void VerifyThatToStringProducesValidCss() {
CssFontFaceRule fontFaceRule = new CssFontFaceRule();
IList<CssDeclaration> declarations = new List<CssDeclaration>();
declarations.Add(new CssDeclaration(CommonCssConstants.FONT_FAMILY, "test-font-family"));
declarations.Add(new CssDeclaration(CommonCssConstants.FONT_WEIGHT, CommonCssConstants.BOLD));
fontFaceRule.AddBodyCssDeclarations(declarations);
String expectedCss = "@font-face {\n" + " font-family: test-font-family;\n" + " font-weight: bold;\n"
+ "}";
NUnit.Framework.Assert.AreEqual(expectedCss, fontFaceRule.ToString());
}
[NUnit.Framework.Test]
public virtual void ResolveUnicodeRangeTest() {
CssFontFaceRule fontFaceRule = new CssFontFaceRule();
IList<CssDeclaration> declarations = new List<CssDeclaration>();
declarations.Add(new CssDeclaration("unicode-range", "U+75"));
fontFaceRule.AddBodyCssDeclarations(declarations);
TSpdf.Layout.Font.Range range = fontFaceRule.ResolveUnicodeRange();
NUnit.Framework.Assert.IsNotNull(range);
NUnit.Framework.Assert.IsTrue(range.Contains(117));
}
}
}

View File

@@ -0,0 +1,120 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.IO;
using TSpdf.Commons.Utils;
using TSpdf.StyledXmlParser.Css.Font;
using TSpdf.StyledXmlParser.Css.Parse;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.StyledXmlParser.Css {
[NUnit.Framework.Category("UnitTest")]
public class CssFontFaceSrcTest : ExtendedTSpdfTest {
private static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/styledxmlparser/css/CssFontFaceSrcTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
}
[NUnit.Framework.Test]
public virtual void SrcPropertyTest() {
String fontSrc = "web-fonts/droid-serif-invalid.";
CssStyleSheet styleSheet = CssStyleSheetParser.Parse(new FileStream(sourceFolder + "srcs.css", FileMode.Open
, FileAccess.Read));
CssFontFaceRule fontFaceRule = (CssFontFaceRule)styleSheet.GetStatements()[0];
CssDeclaration src = fontFaceRule.GetProperties()[0];
NUnit.Framework.Assert.AreEqual("src", src.GetProperty(), "src expected");
String[] sources = TSpdf.Commons.Utils.StringUtil.Split(src.GetExpression(), ",");
NUnit.Framework.Assert.AreEqual(27, sources.Length, "27 sources expected");
for (int i = 0; i < sources.Length; i++) {
Matcher m = TSpdf.Commons.Utils.Matcher.Match(CssFontFace.CssFontFaceSrc.UrlPattern, sources[i]);
NUnit.Framework.Assert.IsTrue(m.Matches(), "Expression doesn't match pattern: " + sources[i]);
String format = m.Group(CssFontFace.CssFontFaceSrc.FormatGroup);
String source2 = MessageFormatUtil.Format("{0}({1}){2}", m.Group(CssFontFace.CssFontFaceSrc.TypeGroup), m.
Group(CssFontFace.CssFontFaceSrc.UrlGroup), format != null ? MessageFormatUtil.Format(" format({0})",
format) : "");
String url = CssFontFace.CssFontFaceSrc.Unquote(m.Group(CssFontFace.CssFontFaceSrc.UrlGroup));
NUnit.Framework.Assert.IsTrue(url.StartsWith(fontSrc), "Invalid url: " + url);
NUnit.Framework.Assert.IsTrue(format == null || CssFontFace.CssFontFaceSrc.ParseFormat(format) != CssFontFace.FontFormat
.None, "Invalid format: " + format);
NUnit.Framework.Assert.AreEqual(sources[i], source2, "Group check fails: ");
CssFontFace.CssFontFaceSrc fontFaceSrc = CssFontFace.CssFontFaceSrc.Create(sources[i]);
NUnit.Framework.Assert.IsTrue(fontFaceSrc.GetSrc().StartsWith(fontSrc), "Invalid url: " + fontSrc);
String type = "url";
if (fontFaceSrc.IsLocal()) {
type = "local";
}
NUnit.Framework.Assert.IsTrue(sources[i].StartsWith(type), "Type '" + type + "' expected: " + sources[i]);
switch (fontFaceSrc.GetFormat()) {
case CssFontFace.FontFormat.OpenType: {
NUnit.Framework.Assert.IsTrue(sources[i].Contains("opentype"), "Format " + fontFaceSrc.GetFormat() + " expected: "
+ sources[i]);
break;
}
case CssFontFace.FontFormat.TrueType: {
NUnit.Framework.Assert.IsTrue(sources[i].Contains("truetype"), "Format " + fontFaceSrc.GetFormat() + " expected: "
+ sources[i]);
break;
}
case CssFontFace.FontFormat.SVG: {
NUnit.Framework.Assert.IsTrue(sources[i].Contains("svg"), "Format " + fontFaceSrc.GetFormat() + " expected: "
+ sources[i]);
break;
}
case CssFontFace.FontFormat.None: {
NUnit.Framework.Assert.IsFalse(sources[i].Contains("format("), "Format " + fontFaceSrc.GetFormat() + " expected: "
+ sources[i]);
break;
}
}
}
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.QUOTE_IS_NOT_CLOSED_IN_CSS_EXPRESSION
)]
public virtual void ParseBase64SrcTest() {
CssStyleSheet styleSheet = CssStyleSheetParser.Parse(new FileStream(sourceFolder + "srcs2.css", FileMode.Open
, FileAccess.Read));
CssFontFaceRule fontFaceRule = (CssFontFaceRule)styleSheet.GetStatements()[0];
CssDeclaration src = fontFaceRule.GetProperties()[0];
NUnit.Framework.Assert.AreEqual("src", src.GetProperty(), "src expected");
String[] sources = CssFontFace.SplitSourcesSequence(src.GetExpression());
NUnit.Framework.Assert.AreEqual(8, sources.Length, "8 sources expected");
for (int i = 0; i < 6; i++) {
Matcher m = TSpdf.Commons.Utils.Matcher.Match(CssFontFace.CssFontFaceSrc.UrlPattern, sources[i]);
NUnit.Framework.Assert.IsTrue(m.Matches(), "Expression doesn't match pattern: " + sources[i]);
}
for (int i = 6; i < sources.Length; i++) {
Matcher m = TSpdf.Commons.Utils.Matcher.Match(CssFontFace.CssFontFaceSrc.UrlPattern, sources[i]);
NUnit.Framework.Assert.IsFalse(m.Matches(), "Expression matches pattern (though it shouldn't!): " + sources
[i]);
}
}
}
}

View File

@@ -0,0 +1,62 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System.Collections.Generic;
using TSpdf.StyledXmlParser.Css.Font;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css {
[NUnit.Framework.Category("UnitTest")]
public class CssFontFaceTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void CreateCssFontFaceTest() {
IList<CssDeclaration> properties = new List<CssDeclaration>();
properties.Add(new CssDeclaration("font-family", "Droid Italic"));
properties.Add(new CssDeclaration("src", "url(\"web-fonts/droid-serif-italic.ttf\")"));
CssFontFace fontFace = CssFontFace.Create(properties);
NUnit.Framework.Assert.IsNotNull(fontFace);
NUnit.Framework.Assert.AreEqual("droid italic", fontFace.GetFontFamily());
IList<CssFontFace.CssFontFaceSrc> sources = fontFace.GetSources();
NUnit.Framework.Assert.IsNotNull(sources);
NUnit.Framework.Assert.AreEqual(1, sources.Count);
NUnit.Framework.Assert.AreEqual("web-fonts/droid-serif-italic.ttf", sources[0].GetSrc());
}
[NUnit.Framework.Test]
public virtual void CreateCssFontFaceNullSrcTest() {
IList<CssDeclaration> properties = new List<CssDeclaration>();
properties.Add(new CssDeclaration("font-family", "Droid Italic"));
properties.Add(new CssDeclaration("src", null));
CssFontFace fontFace = CssFontFace.Create(properties);
NUnit.Framework.Assert.IsNull(fontFace);
}
[NUnit.Framework.Test]
public virtual void CreateCssFontFaceNullFontFamilyTest() {
IList<CssDeclaration> properties = new List<CssDeclaration>();
properties.Add(new CssDeclaration("font-family", ""));
properties.Add(new CssDeclaration("src", "some_directory/droid-serif-italic.ttf"));
CssFontFace fontFace = CssFontFace.Create(properties);
NUnit.Framework.Assert.IsNull(fontFace);
}
}
}

View File

@@ -0,0 +1,162 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using System.IO;
using TSpdf.StyledXmlParser;
using TSpdf.StyledXmlParser.Css.Media;
using TSpdf.StyledXmlParser.Css.Parse;
using TSpdf.StyledXmlParser.Node;
using TSpdf.StyledXmlParser.Node.Impl.Jsoup;
using TSpdf.StyledXmlParser.Node.Impl.Jsoup.Node;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css {
[NUnit.Framework.Category("UnitTest")]
public class CssMatchingTest : ExtendedTSpdfTest {
private static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/styledxmlparser/css/CssMatchingTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
}
[NUnit.Framework.Test]
public virtual void Test01() {
String htmlFileName = sourceFolder + "html01.html";
String cssFileName = sourceFolder + "css01.css";
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode document = htmlParser.Parse(new FileStream(htmlFileName, FileMode.Open, FileAccess.Read), "UTF-8"
);
CssStyleSheet css = CssStyleSheetParser.Parse(new FileStream(cssFileName, FileMode.Open, FileAccess.Read));
MediaDeviceDescription deviceDescription = new MediaDeviceDescription("all");
IElementNode element = new JsoupElementNode(((JsoupDocumentNode)document).GetDocument().GetElementsByTag("p"
).First());
IList<CssDeclaration> declarations = css.GetCssDeclarations(element, deviceDescription);
NUnit.Framework.Assert.AreEqual(1, declarations.Count);
NUnit.Framework.Assert.AreEqual("font-weight: bold", declarations[0].ToString());
}
[NUnit.Framework.Test]
public virtual void Test02() {
String htmlFileName = sourceFolder + "html02.html";
String cssFileName = sourceFolder + "css02.css";
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode document = htmlParser.Parse(new FileStream(htmlFileName, FileMode.Open, FileAccess.Read), "UTF-8"
);
CssStyleSheet css = CssStyleSheetParser.Parse(new FileStream(cssFileName, FileMode.Open, FileAccess.Read));
MediaDeviceDescription deviceDescription = new MediaDeviceDescription("all");
IElementNode element = new JsoupElementNode(((JsoupDocumentNode)document).GetDocument().GetElementsByTag("p"
).First());
IList<CssDeclaration> declarations = css.GetCssDeclarations(element, deviceDescription);
NUnit.Framework.Assert.AreEqual(2, declarations.Count);
NUnit.Framework.Assert.AreEqual("font-weight: bold", declarations[1].ToString());
NUnit.Framework.Assert.AreEqual("color: red", declarations[0].ToString());
}
[NUnit.Framework.Test]
public virtual void Test03() {
String htmlFileName = sourceFolder + "html03.html";
String cssFileName = sourceFolder + "css03.css";
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode document = htmlParser.Parse(new FileStream(htmlFileName, FileMode.Open, FileAccess.Read), "UTF-8"
);
CssStyleSheet css = CssStyleSheetParser.Parse(new FileStream(cssFileName, FileMode.Open, FileAccess.Read));
MediaDeviceDescription deviceDescription = new MediaDeviceDescription("all");
IElementNode element = new JsoupElementNode(((JsoupDocumentNode)document).GetDocument().GetElementsByTag("p"
).First());
IList<CssDeclaration> declarations = css.GetCssDeclarations(element, deviceDescription);
NUnit.Framework.Assert.AreEqual(2, declarations.Count);
NUnit.Framework.Assert.AreEqual("font-weight: bold", declarations[0].ToString());
NUnit.Framework.Assert.AreEqual("color: black", declarations[1].ToString());
}
[NUnit.Framework.Test]
public virtual void Test04() {
String htmlFileName = sourceFolder + "html04.html";
String cssFileName = sourceFolder + "css04.css";
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode document = htmlParser.Parse(new FileStream(htmlFileName, FileMode.Open, FileAccess.Read), "UTF-8"
);
CssStyleSheet css = CssStyleSheetParser.Parse(new FileStream(cssFileName, FileMode.Open, FileAccess.Read));
MediaDeviceDescription deviceDescription = new MediaDeviceDescription("all");
IElementNode element = new JsoupElementNode(((JsoupDocumentNode)document).GetDocument().GetElementsByTag("p"
).First());
IList<CssDeclaration> declarations = css.GetCssDeclarations(element, deviceDescription);
NUnit.Framework.Assert.AreEqual(1, declarations.Count);
NUnit.Framework.Assert.AreEqual("font-size: 100px", declarations[0].ToString());
}
[NUnit.Framework.Test]
public virtual void Test05() {
String htmlFileName = sourceFolder + "html05.html";
String cssFileName = sourceFolder + "css05.css";
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode document = htmlParser.Parse(new FileStream(htmlFileName, FileMode.Open, FileAccess.Read), "UTF-8"
);
CssStyleSheet css = CssStyleSheetParser.Parse(new FileStream(cssFileName, FileMode.Open, FileAccess.Read));
MediaDeviceDescription deviceDescription = new MediaDeviceDescription("all");
IElementNode element = new JsoupElementNode(((JsoupDocumentNode)document).GetDocument().GetElementsByTag("p"
).First());
IList<CssDeclaration> declarations = css.GetCssDeclarations(element, deviceDescription);
NUnit.Framework.Assert.AreEqual(1, declarations.Count);
NUnit.Framework.Assert.AreEqual("color: red", declarations[0].ToString());
}
[NUnit.Framework.Test]
public virtual void Test06() {
String htmlFileName = sourceFolder + "html06.html";
String cssFileName = sourceFolder + "css06.css";
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode document = htmlParser.Parse(new FileStream(htmlFileName, FileMode.Open, FileAccess.Read), "UTF-8"
);
CssStyleSheet css = CssStyleSheetParser.Parse(new FileStream(cssFileName, FileMode.Open, FileAccess.Read));
MediaDeviceDescription deviceDescription = new MediaDeviceDescription("all");
IElementNode element = new JsoupElementNode(((JsoupDocumentNode)document).GetDocument().GetElementsByTag("p"
).First());
IList<CssDeclaration> declarations = css.GetCssDeclarations(element, deviceDescription);
NUnit.Framework.Assert.AreEqual(1, declarations.Count);
NUnit.Framework.Assert.AreEqual("color: blue", declarations[0].ToString());
}
}
}

View File

@@ -0,0 +1,43 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using TSpdf.StyledXmlParser.Css.Page;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css {
[NUnit.Framework.Category("UnitTest")]
public class CssNestedAtRuleFactoryTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void TestCreatingNestedRule() {
CssNestedAtRule pageRule = CssNestedAtRuleFactory.CreateNestedRule("page:first");
NUnit.Framework.Assert.IsTrue(pageRule is CssPageRule);
NUnit.Framework.Assert.AreEqual(CssRuleName.PAGE, pageRule.GetRuleName());
NUnit.Framework.Assert.AreEqual(":first", pageRule.GetRuleParameters());
CssNestedAtRule rightBottomMarginRule = CssNestedAtRuleFactory.CreateNestedRule("bottom-right");
NUnit.Framework.Assert.IsTrue(rightBottomMarginRule is CssMarginRule);
NUnit.Framework.Assert.AreEqual(CssRuleName.BOTTOM_RIGHT, rightBottomMarginRule.GetRuleName());
CssNestedAtRule fontFaceRule = CssNestedAtRuleFactory.CreateNestedRule("font-face");
NUnit.Framework.Assert.IsTrue(fontFaceRule is CssFontFaceRule);
NUnit.Framework.Assert.AreEqual(CssRuleName.FONT_FACE, fontFaceRule.GetRuleName());
}
}
}

View File

@@ -0,0 +1,54 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.StyledXmlParser.Css.Parse;
using TSpdf.StyledXmlParser.Css.Selector;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css {
[NUnit.Framework.Category("UnitTest")]
public class CssRuleSetTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void AddCssRuleSetWithNormalImportantDeclarationsTest() {
String src = "float:right; clear:right !important;width:22.0em!important; margin:0 0 1.0em 1.0em; " + "background:#f9f9f9; "
+ "border:1px solid #aaa;padding:0.2em ! important;border-spacing:0.4em 0; text-align:center " + "!important; "
+ "line-height:1.4em; font-size:88%! important;";
String[] expectedNormal = new String[] { "float: right", "margin: 0 0 1.0em 1.0em", "background: #f9f9f9",
"border: 1px solid #aaa", "border-spacing: 0.4em 0", "line-height: 1.4em" };
String[] expectedImportant = new String[] { "clear: right", "width: 22.0em", "padding: 0.2em", "text-align: center"
, "font-size: 88%" };
IList<CssDeclaration> declarations = CssRuleSetParser.ParsePropertyDeclarations(src);
CssSelector selector = new CssSelector("h1");
CssRuleSet cssRuleSet = new CssRuleSet(selector, declarations);
IList<CssDeclaration> normalDeclarations = cssRuleSet.GetNormalDeclarations();
for (int i = 0; i < expectedNormal.Length; i++) {
NUnit.Framework.Assert.AreEqual(expectedNormal[i], normalDeclarations[i].ToString());
}
IList<CssDeclaration> importantDeclarations = cssRuleSet.GetImportantDeclarations();
for (int i = 0; i < expectedImportant.Length; i++) {
NUnit.Framework.Assert.AreEqual(expectedImportant[i], importantDeclarations[i].ToString());
}
}
}
}

View File

@@ -0,0 +1,203 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using TSpdf.StyledXmlParser;
using TSpdf.StyledXmlParser.Css;
using TSpdf.StyledXmlParser.Css.Parse;
using TSpdf.StyledXmlParser.Node;
using TSpdf.StyledXmlParser.Node.Impl.Jsoup;
using TSpdf.StyledXmlParser.Node.Impl.Jsoup.Node;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Media {
[NUnit.Framework.Category("UnitTest")]
public class CssMediaRuleTest : ExtendedTSpdfTest {
private static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/styledxmlparser/css/media/MediaRuleTest/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
}
[NUnit.Framework.Test]
public virtual void Test01() {
String htmlFileName = sourceFolder + "html01.html";
String cssFileName = sourceFolder + "css01.css";
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode document = htmlParser.Parse(new FileStream(htmlFileName, FileMode.Open, FileAccess.Read), "UTF-8"
);
CssStyleSheet css = CssStyleSheetParser.Parse(new FileStream(cssFileName, FileMode.Open, FileAccess.Read));
MediaDeviceDescription deviceDescription = new MediaDeviceDescription(MediaType.PRINT);
IElementNode element = new JsoupElementNode(((JsoupDocumentNode)document).GetDocument().GetElementsByTag("p"
).First());
IList<CssDeclaration> declarations = css.GetCssDeclarations(element, deviceDescription);
NUnit.Framework.Assert.AreEqual(3, declarations.Count);
NUnit.Framework.Assert.AreEqual("font-weight: bold", declarations[0].ToString());
NUnit.Framework.Assert.AreEqual("color: red", declarations[1].ToString());
NUnit.Framework.Assert.AreEqual("font-size: 20pt", declarations[2].ToString());
}
[NUnit.Framework.Test]
public virtual void Test02() {
String htmlFileName = sourceFolder + "html02.html";
String cssFileName = sourceFolder + "css02.css";
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode document = htmlParser.Parse(new FileStream(htmlFileName, FileMode.Open, FileAccess.Read), "UTF-8"
);
CssStyleSheet css = CssStyleSheetParser.Parse(new FileStream(cssFileName, FileMode.Open, FileAccess.Read));
IElementNode element = new JsoupElementNode(((JsoupDocumentNode)document).GetDocument().GetElementsByTag("p"
).First());
MediaDeviceDescription deviceDescription1 = new MediaDeviceDescription(MediaType.PRINT);
deviceDescription1.SetWidth(525);
MediaDeviceDescription deviceDescription2 = new MediaDeviceDescription(MediaType.HANDHELD);
deviceDescription2.SetOrientation("landscape");
IList<CssDeclaration> declarations1 = css.GetCssDeclarations(element, deviceDescription1);
IList<CssDeclaration> declarations2 = css.GetCssDeclarations(element, deviceDescription2);
NUnit.Framework.Assert.IsTrue(Enumerable.SequenceEqual(declarations1, declarations2));
NUnit.Framework.Assert.AreEqual(1, declarations1.Count);
NUnit.Framework.Assert.AreEqual("font-weight: bold", declarations1[0].ToString());
}
[NUnit.Framework.Test]
public virtual void Test03() {
String htmlFileName = sourceFolder + "html03.html";
String cssFileName = sourceFolder + "css03.css";
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode document = htmlParser.Parse(new FileStream(htmlFileName, FileMode.Open, FileAccess.Read), "UTF-8"
);
CssStyleSheet css = CssStyleSheetParser.Parse(new FileStream(cssFileName, FileMode.Open, FileAccess.Read));
MediaDeviceDescription deviceDescription = new MediaDeviceDescription(MediaType.PRINT);
deviceDescription.SetResolution(300);
IElementNode element = new JsoupElementNode(((JsoupDocumentNode)document).GetDocument().GetElementsByTag("p"
).First());
IList<CssDeclaration> declarations = css.GetCssDeclarations(element, deviceDescription);
NUnit.Framework.Assert.AreEqual(1, declarations.Count);
NUnit.Framework.Assert.AreEqual("color: black", declarations[0].ToString());
}
[NUnit.Framework.Test]
public virtual void Test04() {
String htmlFileName = sourceFolder + "html04.html";
String cssFileName = sourceFolder + "css04.css";
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode document = htmlParser.Parse(new FileStream(htmlFileName, FileMode.Open, FileAccess.Read), "UTF-8"
);
CssStyleSheet css = CssStyleSheetParser.Parse(new FileStream(cssFileName, FileMode.Open, FileAccess.Read));
MediaDeviceDescription deviceDescription = new MediaDeviceDescription(MediaType.PRINT).SetColorIndex(256);
IElementNode element = new JsoupElementNode(((JsoupDocumentNode)document).GetDocument().GetElementsByTag("p"
).First());
IList<CssDeclaration> declarations = css.GetCssDeclarations(element, deviceDescription);
NUnit.Framework.Assert.AreEqual(2, declarations.Count);
NUnit.Framework.Assert.AreEqual("color: red", declarations[0].ToString());
NUnit.Framework.Assert.AreEqual("font-size: 20em", declarations[1].ToString());
}
[NUnit.Framework.Test]
public virtual void Test05() {
String htmlFileName = sourceFolder + "html05.html";
String cssFileName = sourceFolder + "css05.css";
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode document = htmlParser.Parse(new FileStream(htmlFileName, FileMode.Open, FileAccess.Read), "UTF-8"
);
CssStyleSheet css = CssStyleSheetParser.Parse(new FileStream(cssFileName, FileMode.Open, FileAccess.Read));
IElementNode element = new JsoupElementNode(((JsoupDocumentNode)document).GetDocument().GetElementsByTag("p"
).First());
MediaDeviceDescription deviceDescription1 = new MediaDeviceDescription(MediaType.PRINT).SetWidth(300).SetHeight
(301);
MediaDeviceDescription deviceDescription2 = new MediaDeviceDescription(MediaType.SCREEN).SetWidth(400).SetHeight
(400);
IList<CssDeclaration> declarations1 = css.GetCssDeclarations(element, deviceDescription1);
IList<CssDeclaration> declarations2 = css.GetCssDeclarations(element, deviceDescription2);
NUnit.Framework.Assert.AreEqual(0, declarations1.Count);
NUnit.Framework.Assert.AreEqual(1, declarations2.Count);
NUnit.Framework.Assert.AreEqual("color: red", declarations2[0].ToString());
}
[NUnit.Framework.Test]
public virtual void Test06() {
String htmlFileName = sourceFolder + "html06.html";
String cssFileName = sourceFolder + "css06.css";
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode document = htmlParser.Parse(new FileStream(htmlFileName, FileMode.Open, FileAccess.Read), "UTF-8"
);
CssStyleSheet css = CssStyleSheetParser.Parse(new FileStream(cssFileName, FileMode.Open, FileAccess.Read));
IElementNode element = new JsoupElementNode(((JsoupDocumentNode)document).GetDocument().GetElementsByTag("p"
).First());
MediaDeviceDescription deviceDescription1 = new MediaDeviceDescription(MediaType.PRINT).SetBitsPerComponent
(2);
MediaDeviceDescription deviceDescription2 = new MediaDeviceDescription(MediaType.HANDHELD).SetBitsPerComponent
(2);
MediaDeviceDescription deviceDescription3 = new MediaDeviceDescription(MediaType.SCREEN).SetBitsPerComponent
(1);
IList<CssDeclaration> declarations1 = css.GetCssDeclarations(element, deviceDescription1);
IList<CssDeclaration> declarations2 = css.GetCssDeclarations(element, deviceDescription2);
IList<CssDeclaration> declarations3 = css.GetCssDeclarations(element, deviceDescription3);
NUnit.Framework.Assert.IsTrue(Enumerable.SequenceEqual(declarations1, declarations2));
NUnit.Framework.Assert.AreEqual(0, declarations3.Count);
NUnit.Framework.Assert.AreEqual(1, declarations1.Count);
NUnit.Framework.Assert.AreEqual("color: red", declarations1[0].ToString());
}
[NUnit.Framework.Test]
public virtual void MatchMediaDeviceTest() {
MediaDeviceDescription deviceDescription = new MediaDeviceDescription("all");
deviceDescription.SetHeight(450);
deviceDescription.SetWidth(600);
CssMediaRule rule = new CssMediaRule("@media all and (min-width: 600px) and (min-height: 600px)");
NUnit.Framework.Assert.IsTrue(rule.MatchMediaDevice(deviceDescription));
}
[NUnit.Framework.Test]
public virtual void GetCssRuleSetsTest() {
MediaDeviceDescription deviceDescription = new MediaDeviceDescription("all");
String html = "<a id=\"123\" class=\"baz = 'bar'\" style = media= all and (min-width: 600px) />";
IDocumentNode node = new JsoupHtmlParser().Parse(html);
IList<CssRuleSet> ruleSets = new CssMediaRule("only all and (min-width: 600px) and (min-height: 600px)").GetCssRuleSets
(node, deviceDescription);
NUnit.Framework.Assert.IsNotNull(ruleSets);
}
}
}

View File

@@ -0,0 +1,166 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Media {
[NUnit.Framework.Category("UnitTest")]
public class MediaExpressionTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void MediaExpressionTestTest01() {
MediaExpression minWidth = new MediaExpression("min-width", "600px");
MediaExpression minHeight = new MediaExpression("min-height", "600px");
MediaDeviceDescription deviceDescription = new MediaDeviceDescription("all");
deviceDescription.SetWidth(600);
deviceDescription.SetHeight(600);
NUnit.Framework.Assert.IsTrue(minHeight.Matches(deviceDescription));
NUnit.Framework.Assert.IsTrue(minWidth.Matches(deviceDescription));
}
[NUnit.Framework.Test]
public virtual void MediaExpressionTestTest02() {
MediaExpression maxWidth = new MediaExpression("max-width", "600px");
MediaExpression maxHeight = new MediaExpression("max-height", "600px");
MediaDeviceDescription deviceDescription = new MediaDeviceDescription("all");
deviceDescription.SetWidth(450);
deviceDescription.SetHeight(450);
NUnit.Framework.Assert.IsTrue(maxHeight.Matches(deviceDescription));
NUnit.Framework.Assert.IsTrue(maxWidth.Matches(deviceDescription));
}
[NUnit.Framework.Test]
public virtual void MediaExpressionTestTest03() {
MediaExpression orientation = new MediaExpression("orientation", "landscape");
MediaExpression resolution = new MediaExpression("resolution", "150dpi");
MediaExpression grid = new MediaExpression("grid", "0");
MediaExpression colorIndex = new MediaExpression("max-color-index", "15000");
MediaExpression monochrome = new MediaExpression("monochrome", "0");
MediaExpression scan = new MediaExpression("scan", "interlace");
MediaExpression color = new MediaExpression("color", "15000");
MediaExpression minAspectRatio = new MediaExpression("max-aspect-ratio", "8/5");
MediaDeviceDescription deviceDescription = new MediaDeviceDescription("all");
deviceDescription.SetOrientation("landscape");
deviceDescription.SetResolution(150);
deviceDescription.SetGrid(false);
deviceDescription.SetColorIndex(15000);
deviceDescription.SetMonochrome(0);
deviceDescription.SetScan("interlace");
deviceDescription.SetBitsPerComponent(15000);
deviceDescription.SetWidth(32);
deviceDescription.SetHeight(20);
NUnit.Framework.Assert.IsTrue(resolution.Matches(deviceDescription));
NUnit.Framework.Assert.IsTrue(orientation.Matches(deviceDescription));
NUnit.Framework.Assert.IsTrue(grid.Matches(deviceDescription));
NUnit.Framework.Assert.IsTrue(colorIndex.Matches(deviceDescription));
NUnit.Framework.Assert.IsTrue(monochrome.Matches(deviceDescription));
NUnit.Framework.Assert.IsTrue(scan.Matches(deviceDescription));
NUnit.Framework.Assert.IsTrue(color.Matches(deviceDescription));
NUnit.Framework.Assert.IsTrue(minAspectRatio.Matches(deviceDescription));
}
[NUnit.Framework.Test]
public virtual void MediaExpressionTestTest04() {
MediaExpression minColorIndex = new MediaExpression("min-color-index", "15000");
MediaExpression minResolution = new MediaExpression("min-resolution", "150dpi");
MediaExpression minColor = new MediaExpression("min-color", "8");
MediaExpression minAspectRatio = new MediaExpression("min-aspect-ratio", "8/5");
MediaDeviceDescription deviceDescription = new MediaDeviceDescription("all");
deviceDescription.SetColorIndex(15000);
deviceDescription.SetBitsPerComponent(8);
deviceDescription.SetResolution(150);
deviceDescription.SetWidth(32);
deviceDescription.SetHeight(20);
NUnit.Framework.Assert.IsTrue(minAspectRatio.Matches(deviceDescription));
NUnit.Framework.Assert.IsTrue(minColorIndex.Matches(deviceDescription));
NUnit.Framework.Assert.IsTrue(minColor.Matches(deviceDescription));
NUnit.Framework.Assert.IsTrue(minResolution.Matches(deviceDescription));
}
[NUnit.Framework.Test]
public virtual void MediaExpressionTestTest05() {
MediaExpression maxColorIndex = new MediaExpression("max-color-index", null);
MediaExpression maxColor = new MediaExpression("max-color", null);
MediaExpression maxWidth = new MediaExpression("width", "600ex");
MediaExpression maxHeight = new MediaExpression("height", "600ex");
MediaExpression maxMonochrome = new MediaExpression("max-monochrome", "0");
MediaExpression maxResolution = new MediaExpression("max-resolution", "150dpi");
MediaDeviceDescription deviceDescription = new MediaDeviceDescription("all");
deviceDescription.SetHeight(450);
deviceDescription.SetWidth(450);
deviceDescription.SetColorIndex(15000);
deviceDescription.SetBitsPerComponent(8);
deviceDescription.SetMonochrome(0);
deviceDescription.SetResolution(150);
NUnit.Framework.Assert.IsTrue(maxMonochrome.Matches(deviceDescription));
NUnit.Framework.Assert.IsTrue(maxHeight.Matches(deviceDescription));
NUnit.Framework.Assert.IsTrue(maxWidth.Matches(deviceDescription));
NUnit.Framework.Assert.IsFalse(maxColorIndex.Matches(deviceDescription));
NUnit.Framework.Assert.IsFalse(maxColor.Matches(deviceDescription));
NUnit.Framework.Assert.IsTrue(maxResolution.Matches(deviceDescription));
}
[NUnit.Framework.Test]
public virtual void MediaExpressionTestTest06() {
MediaExpression minColorIndex = new MediaExpression("min-color-index", null);
MediaExpression minColor = new MediaExpression("min-color", null);
MediaExpression colorIndex = new MediaExpression("color-index", "1500");
MediaExpression minMonochrome = new MediaExpression("min-monochrome", "0");
MediaExpression resolution = new MediaExpression("resolution", "150dpi");
MediaExpression defaultExpression = new MediaExpression("none", "none");
MediaExpression aspectRatio = new MediaExpression("aspect-ratio", "8/8");
MediaDeviceDescription deviceDescription = new MediaDeviceDescription("all");
deviceDescription.SetColorIndex(15000);
deviceDescription.SetBitsPerComponent(8);
deviceDescription.SetMonochrome(0);
deviceDescription.SetWidth(1.99999999f);
deviceDescription.SetHeight(2.00000000f);
deviceDescription.SetColorIndex(15000);
NUnit.Framework.Assert.IsTrue(aspectRatio.Matches(deviceDescription));
NUnit.Framework.Assert.IsTrue(minMonochrome.Matches(deviceDescription));
NUnit.Framework.Assert.IsFalse(minColorIndex.Matches(deviceDescription));
NUnit.Framework.Assert.IsFalse(minColor.Matches(deviceDescription));
NUnit.Framework.Assert.IsFalse(resolution.Matches(deviceDescription));
NUnit.Framework.Assert.IsFalse(defaultExpression.Matches(deviceDescription));
NUnit.Framework.Assert.IsFalse(colorIndex.Matches(deviceDescription));
}
}
}

View File

@@ -0,0 +1,60 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System.Collections.Generic;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Media {
[NUnit.Framework.Category("UnitTest")]
public class MediaQueryTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void MatchTest() {
MediaDeviceDescription deviceDescription = new MediaDeviceDescription("all");
MediaQuery query = MediaQueryParser.ParseMediaQuery("not all and (min-width: 600px)");
IList<MediaQuery> queries = MediaQueryParser.ParseMediaQueries("not all and (min-width: 600px), not all and (min-width: 500px)"
);
NUnit.Framework.Assert.IsTrue(query.Matches(deviceDescription));
NUnit.Framework.Assert.IsTrue(queries[0].Matches(deviceDescription));
NUnit.Framework.Assert.IsTrue(queries[1].Matches(deviceDescription));
}
}
}

View File

@@ -0,0 +1,76 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.Kernel.Geom;
using TSpdf.StyledXmlParser.Css.Pseudo;
using TSpdf.StyledXmlParser.Node;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Page {
[NUnit.Framework.Category("UnitTest")]
public class PageMarginBoxContextNodeTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void DefaultBehaviourTest() {
String marginBoxName = "someName";
PageMarginBoxContextNode pageMarginBoxContextNode = new PageMarginBoxContextNode(new PageContextNode(), marginBoxName
);
NUnit.Framework.Assert.AreEqual(marginBoxName, pageMarginBoxContextNode.GetMarginBoxName());
NUnit.Framework.Assert.AreEqual(PageMarginBoxContextNode.PAGE_MARGIN_BOX_TAG, pageMarginBoxContextNode.Name
());
NUnit.Framework.Assert.Catch(typeof(NotSupportedException), () => pageMarginBoxContextNode.GetLang());
NUnit.Framework.Assert.IsNull(pageMarginBoxContextNode.GetAdditionalHtmlStyles());
NUnit.Framework.Assert.Catch(typeof(NotSupportedException), () => pageMarginBoxContextNode.AddAdditionalHtmlStyles
(new Dictionary<String, String>()));
IAttributes attributes = pageMarginBoxContextNode.GetAttributes();
NUnit.Framework.Assert.IsNotNull(attributes);
NUnit.Framework.Assert.AreEqual(0, attributes.Size());
String someKey = "someKey";
String someValue = "someValue";
NUnit.Framework.Assert.Catch(typeof(NotSupportedException), () => attributes.SetAttribute(someKey, someValue
));
NUnit.Framework.Assert.IsNull(attributes.GetAttribute(someKey));
NUnit.Framework.Assert.IsNull(pageMarginBoxContextNode.GetAttribute(someKey));
NUnit.Framework.Assert.IsNull(pageMarginBoxContextNode.GetContainingBlockForMarginBox());
Rectangle someRectangle = new Rectangle(100, 100);
pageMarginBoxContextNode.SetContainingBlockForMarginBox(someRectangle);
NUnit.Framework.Assert.AreEqual(someRectangle, pageMarginBoxContextNode.GetContainingBlockForMarginBox());
NUnit.Framework.Assert.IsNull(pageMarginBoxContextNode.GetPageMarginBoxRectangle());
Rectangle someRectangle2 = new Rectangle(200, 200);
pageMarginBoxContextNode.SetPageMarginBoxRectangle(someRectangle2);
NUnit.Framework.Assert.AreEqual(someRectangle2, pageMarginBoxContextNode.GetPageMarginBoxRectangle());
}
[NUnit.Framework.Test]
public virtual void ParentNotPageTest() {
// Create some invalid node
PageContextNode pageContextNode = new PageContextNode();
CssPseudoElementNode pseudoElementNode = new CssPseudoElementNode(pageContextNode, "test");
// Pass this mode to the constructor
Exception e = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => new PageMarginBoxContextNode(pseudoElementNode
, "test"));
NUnit.Framework.Assert.AreEqual("Page-margin-box context node shall have a page context node as parent.",
e.Message);
}
}
}

View File

@@ -0,0 +1,45 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.StyledXmlParser.Css;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Parse {
[NUnit.Framework.Category("UnitTest")]
public class CssRuleSetParserTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void ParsePropertyDeclarationsTest() {
String src = "float:right; clear:right;width:22.0em; margin:0 0 1.0em 1.0em; background:#f9f9f9; " + "border:1px solid #aaa;padding:0.2em;border-spacing:0.4em 0; text-align:center; "
+ "line-height:1.4em; font-size:88%;";
String[] expected = new String[] { "float: right", "clear: right", "width: 22.0em", "margin: 0 0 1.0em 1.0em"
, "background: #f9f9f9", "border: 1px solid #aaa", "padding: 0.2em", "border-spacing: 0.4em 0", "text-align: center"
, "line-height: 1.4em", "font-size: 88%" };
IList<CssDeclaration> declarations = CssRuleSetParser.ParsePropertyDeclarations(src);
NUnit.Framework.Assert.AreEqual(expected.Length, declarations.Count);
for (int i = 0; i < expected.Length; i++) {
NUnit.Framework.Assert.AreEqual(expected[i], declarations[i].ToString());
}
}
}
}

View File

@@ -0,0 +1,41 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Commons.Utils;
using TSpdf.StyledXmlParser.Exceptions;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Parse {
[NUnit.Framework.Category("UnitTest")]
public class CssSelectorParserTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void SelectorBeginsWithSpaceTest() {
String space = " ";
String selectorWithSpaceAtTheBeginning = space + ".spaceBefore";
Exception expectedException = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => CssSelectorParser
.ParseSelectorItems(selectorWithSpaceAtTheBeginning));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(StyledXmlParserExceptionMessage.INVALID_TOKEN_AT_THE_BEGINNING_OF_SELECTOR
, space), expectedException.Message);
}
}
}

View File

@@ -0,0 +1,78 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.IO;
using TSpdf.StyledXmlParser;
using TSpdf.StyledXmlParser.Node;
using TSpdf.StyledXmlParser.Node.Impl.Jsoup;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Parse {
[NUnit.Framework.Category("IntegrationTest")]
public class CssStyleAttributeParseTest : ExtendedTSpdfTest {
private static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/styledxmlparser/css/parse/CssStyleAttributeParseTest/";
[NUnit.Framework.Test]
public virtual void StyleAttributeParseTest() {
String fileName = SOURCE_FOLDER + "cssStyleAttributeParse.html";
IXmlParser parser = new JsoupHtmlParser();
IDocumentNode document = parser.Parse(new FileStream(fileName, FileMode.Open, FileAccess.Read), "UTF-8");
IList<String> styleDeclarations = new List<String>();
IList<String> expectStyleDeclarations = new List<String>();
expectStyleDeclarations.Add("display:none;");
expectStyleDeclarations.Add("position:relative;");
expectStyleDeclarations.Add("display:none");
expectStyleDeclarations.Add("text-align:center;");
expectStyleDeclarations.Add("white-space:nowrap;");
expectStyleDeclarations.Add("float:right; clear:right; width:22.0em; margin:0 0 1.0em 1.0em; background:#f9f9f9;"
+ " border:1px solid #aaa; padding:0.2em; border-spacing:0.4em 0; text-align:center;" + " line-height:1.4em; font-size:88%;"
);
expectStyleDeclarations.Add("padding:0.2em 0.4em 0.2em; font-size:145%; line-height:1.15em; font-weight:bold;"
+ " display:block; margin-bottom:0.25em;");
ParseStyleAttrForSubtree(document, styleDeclarations);
NUnit.Framework.Assert.AreEqual(styleDeclarations.Count, expectStyleDeclarations.Count);
for (int i = 0; i < expectStyleDeclarations.Count; i++) {
NUnit.Framework.Assert.AreEqual(expectStyleDeclarations[i], styleDeclarations[i]);
}
}
private void ParseOwnStyleAttr(IElementNode element, IList<String> styleDeclarations) {
IAttributes attributes = element.GetAttributes();
String styleAttr = attributes.GetAttribute("style");
if (styleAttr != null && styleAttr.Length > 0) {
styleDeclarations.Add(styleAttr);
}
}
private void ParseStyleAttrForSubtree(INode node, IList<String> styleDeclarations) {
if (node is IElementNode) {
ParseOwnStyleAttr((IElementNode)node, styleDeclarations);
}
foreach (INode child in node.ChildNodes()) {
ParseStyleAttrForSubtree(child, styleDeclarations);
}
}
}
}

View File

@@ -0,0 +1,168 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.IO;
using TSpdf.IO.Util;
using TSpdf.StyledXmlParser.Css;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Parse {
[NUnit.Framework.Category("UnitTest")]
public class CssStyleSheetParserTest : ExtendedTSpdfTest {
private static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/styledxmlparser/css/parse/CssStyleSheetParserTest/";
[NUnit.Framework.Test]
public virtual void Test01() {
String cssFile = sourceFolder + "css01.css";
CssStyleSheet styleSheet = CssStyleSheetParser.Parse(new FileStream(cssFile, FileMode.Open, FileAccess.Read
));
NUnit.Framework.Assert.AreEqual(GetCssFileContents(cssFile), styleSheet.ToString());
}
[NUnit.Framework.Test]
public virtual void Test02() {
String cssFile = sourceFolder + "css02.css";
String cmpFile = sourceFolder + "cmp_css02.css";
CssStyleSheet styleSheet = CssStyleSheetParser.Parse(new FileStream(cssFile, FileMode.Open, FileAccess.Read
));
NUnit.Framework.Assert.AreEqual(GetCssFileContents(cmpFile), styleSheet.ToString());
}
[NUnit.Framework.Test]
public virtual void Test03() {
String cssFile = sourceFolder + "css03.css";
String cmpFile = sourceFolder + "cmp_css03.css";
CssStyleSheet styleSheet = CssStyleSheetParser.Parse(new FileStream(cssFile, FileMode.Open, FileAccess.Read
));
NUnit.Framework.Assert.AreEqual(GetCssFileContents(cmpFile), styleSheet.ToString());
}
[NUnit.Framework.Test]
public virtual void Test04() {
String cssFile = sourceFolder + "css04.css";
CssStyleSheet styleSheet = CssStyleSheetParser.Parse(new FileStream(cssFile, FileMode.Open, FileAccess.Read
));
NUnit.Framework.Assert.AreEqual("", styleSheet.ToString());
}
[NUnit.Framework.Test]
public virtual void Test05() {
String cssFile = sourceFolder + "css05.css";
String cmpFile = sourceFolder + "cmp_css05.css";
CssStyleSheet styleSheet = CssStyleSheetParser.Parse(new FileStream(cssFile, FileMode.Open, FileAccess.Read
));
NUnit.Framework.Assert.AreEqual(GetCssFileContents(cmpFile), styleSheet.ToString());
}
[NUnit.Framework.Test]
public virtual void Test06() {
String cssFile = sourceFolder + "css06.css";
String cmpFile = sourceFolder + "cmp_css06.css";
CssStyleSheet styleSheet = CssStyleSheetParser.Parse(new FileStream(cssFile, FileMode.Open, FileAccess.Read
));
NUnit.Framework.Assert.AreEqual(GetCssFileContents(cmpFile), styleSheet.ToString());
}
[NUnit.Framework.Test]
public virtual void Test07() {
String cssFile = sourceFolder + "css07.css";
CssStyleSheet styleSheet = CssStyleSheetParser.Parse(new FileStream(cssFile, FileMode.Open, FileAccess.Read
));
NUnit.Framework.Assert.AreEqual(GetCssFileContents(cssFile), styleSheet.ToString());
}
[NUnit.Framework.Test]
public virtual void Test08() {
String cssFile = sourceFolder + "css08.css";
String cmpFile = sourceFolder + "cmp_css08.css";
CssStyleSheet styleSheet = CssStyleSheetParser.Parse(new FileStream(cssFile, FileMode.Open, FileAccess.Read
));
NUnit.Framework.Assert.AreEqual(GetCssFileContents(cmpFile), styleSheet.ToString());
}
[NUnit.Framework.Test]
public virtual void Test09() {
String cssFile = sourceFolder + "css09.css";
CssStyleSheet styleSheet = CssStyleSheetParser.Parse(new FileStream(cssFile, FileMode.Open, FileAccess.Read
));
NUnit.Framework.Assert.AreEqual(GetCssFileContents(cssFile), styleSheet.ToString());
}
[NUnit.Framework.Test]
public virtual void Test10() {
String cssFile = sourceFolder + "css10.css";
String cmpFile = sourceFolder + "cmp_css10.css";
CssStyleSheet styleSheet = CssStyleSheetParser.Parse(new FileStream(cssFile, FileMode.Open, FileAccess.Read
));
NUnit.Framework.Assert.AreEqual(GetCssFileContents(cmpFile), styleSheet.ToString());
}
[NUnit.Framework.Test]
public virtual void Test11() {
// TODO DEVSIX-6364 Fix the body declarations duplication for each pageSelector part
String cssFile = sourceFolder + "css11.css";
String cmpFile = sourceFolder + "cmp_css11.css";
CssStyleSheet styleSheet = CssStyleSheetParser.Parse(new FileStream(cssFile, FileMode.Open, FileAccess.Read
));
NUnit.Framework.Assert.AreEqual(GetCssFileContents(cmpFile), styleSheet.ToString());
}
[NUnit.Framework.Test]
public virtual void Test12() {
String cssFile = sourceFolder + "css12.css";
String cmpFile = sourceFolder + "cmp_css12.css";
CssStyleSheet styleSheet = CssStyleSheetParser.Parse(new FileStream(cssFile, FileMode.Open, FileAccess.Read
));
NUnit.Framework.Assert.AreEqual(GetCssFileContents(cmpFile), styleSheet.ToString());
}
private String GetCssFileContents(String filePath) {
byte[] bytes = StreamUtil.InputStreamToArray(new FileStream(filePath, FileMode.Open, FileAccess.Read));
String content = TSpdf.Commons.Utils.JavaUtil.GetStringForBytes(bytes);
content = content.Trim();
content = content.Replace("\r\n", "\n");
return content;
}
}
}

View File

@@ -0,0 +1,106 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.StyledXmlParser.Node;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Pseudo {
[NUnit.Framework.Category("UnitTest")]
public class CssPseudoElementNodeTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void GetPseudoElementNameTest() {
CssPseudoElementNode pseudoElementNode = new CssPseudoElementNode(null, "after");
NUnit.Framework.Assert.AreEqual("after", pseudoElementNode.GetPseudoElementName());
}
[NUnit.Framework.Test]
public virtual void GetPseudoElementTagNameTest() {
CssPseudoElementNode pseudoElementNode = new CssPseudoElementNode(null, "after");
NUnit.Framework.Assert.AreEqual("pseudo-element::after", pseudoElementNode.Name());
}
[NUnit.Framework.Test]
public virtual void GetAttributeStringTest() {
CssPseudoElementNode pseudoElementNode = new CssPseudoElementNode(null, "after");
NUnit.Framework.Assert.IsNull(pseudoElementNode.GetAttribute("after"));
}
[NUnit.Framework.Test]
public virtual void GetAttributesTest() {
CssPseudoElementNode pseudoElementNode = new CssPseudoElementNode(null, "after");
NUnit.Framework.Assert.IsTrue(pseudoElementNode.GetAttributes() is IAttributes);
NUnit.Framework.Assert.IsFalse(pseudoElementNode.GetAttributes() == pseudoElementNode.GetAttributes());
}
[NUnit.Framework.Test]
public virtual void GetAdditionalHtmlStylesTest() {
CssPseudoElementNode pseudoElementNode = new CssPseudoElementNode(null, "after");
NUnit.Framework.Assert.IsNull(pseudoElementNode.GetAdditionalHtmlStyles());
}
[NUnit.Framework.Test]
public virtual void AddAdditionalHtmlStylesTest() {
CssPseudoElementNode pseudoElementNode = new CssPseudoElementNode(null, "after");
IDictionary<String, String> styles = new Dictionary<String, String>();
styles.Put("font-size", "12px");
styles.Put("color", "red");
NUnit.Framework.Assert.Catch(typeof(NotSupportedException), () => pseudoElementNode.AddAdditionalHtmlStyles
(styles));
}
[NUnit.Framework.Test]
public virtual void GetLangTest() {
CssPseudoElementNode pseudoElementNode = new CssPseudoElementNode(null, "after");
NUnit.Framework.Assert.IsNull(pseudoElementNode.GetLang());
}
[NUnit.Framework.Test]
public virtual void AttributesStubSetAttributeTest() {
CssPseudoElementNode pseudoElementNode = new CssPseudoElementNode(null, "after");
IAttributes attributes = pseudoElementNode.GetAttributes();
NUnit.Framework.Assert.Catch(typeof(NotSupportedException), () => attributes.SetAttribute("content", "TSpdf"
));
}
[NUnit.Framework.Test]
public virtual void AttributesStubGetSizeTest() {
CssPseudoElementNode pseudoElementNode = new CssPseudoElementNode(null, "after");
NUnit.Framework.Assert.AreEqual(0, pseudoElementNode.GetAttributes().Size());
}
[NUnit.Framework.Test]
public virtual void AttributesStubGetAttributeTest() {
CssPseudoElementNode pseudoElementNode = new CssPseudoElementNode(null, "after");
NUnit.Framework.Assert.IsNull(pseudoElementNode.GetAttributes().GetAttribute("after"));
}
[NUnit.Framework.Test]
public virtual void AttributesStubIteratorTest() {
CssPseudoElementNode pseudoElementNode = new CssPseudoElementNode(null, "after");
foreach (IAttribute attr in pseudoElementNode.GetAttributes()) {
NUnit.Framework.Assert.Fail("AttributesStub must return an empty iterator");
}
}
}
}

View File

@@ -0,0 +1,73 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.StyledXmlParser.Node;
using TSpdf.StyledXmlParser.Node.Impl.Jsoup.Node;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Pseudo {
[NUnit.Framework.Category("UnitTest")]
public class CssPseudoElementUtilTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void CreatePseudoElementTagNameTest() {
String beforePseudoElemName = CssPseudoElementUtil.CreatePseudoElementTagName("before");
String expected = "pseudo-element::before";
NUnit.Framework.Assert.AreEqual(expected, beforePseudoElemName);
}
[NUnit.Framework.Test]
public virtual void HasBeforeAfterElementsNullScenarioTest() {
NUnit.Framework.Assert.IsFalse(CssPseudoElementUtil.HasBeforeAfterElements(null));
}
[NUnit.Framework.Test]
public virtual void HasBeforeAfterElementsInstanceOfTest() {
NUnit.Framework.Assert.IsFalse(CssPseudoElementUtil.HasBeforeAfterElements(new CssPseudoElementNode(null,
"")));
}
[NUnit.Framework.Test]
public virtual void HasBeforeAfterElementsNodeNameTest() {
TSpdf.StyledXmlParser.Jsoup.Nodes.Element element = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element(TSpdf.StyledXmlParser.Jsoup.Parser.Tag
.ValueOf("pseudo-element::"), "");
IElementNode node = new JsoupElementNode(element);
NUnit.Framework.Assert.IsFalse(CssPseudoElementUtil.HasBeforeAfterElements(node));
}
[NUnit.Framework.Test]
public virtual void HasAfterElementTest() {
TSpdf.StyledXmlParser.Jsoup.Nodes.Element element = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element(TSpdf.StyledXmlParser.Jsoup.Parser.Tag
.ValueOf("after"), "");
IElementNode node = new JsoupElementNode(element);
NUnit.Framework.Assert.IsTrue(CssPseudoElementUtil.HasBeforeAfterElements(node));
}
[NUnit.Framework.Test]
public virtual void HasBeforeElementTest() {
TSpdf.StyledXmlParser.Jsoup.Nodes.Element element = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element(TSpdf.StyledXmlParser.Jsoup.Parser.Tag
.ValueOf("before"), "");
IElementNode node = new JsoupElementNode(element);
NUnit.Framework.Assert.IsTrue(CssPseudoElementUtil.HasBeforeAfterElements(node));
}
}
}

View File

@@ -0,0 +1,105 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using TSpdf.Commons.Utils;
using TSpdf.StyledXmlParser.Css.Parse;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Resolve {
[NUnit.Framework.Category("UnitTest")]
public class CssDeclarationValueTokenizerTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void FunctionTest01() {
RunTest("func(param)", JavaUtil.ArraysAsList("func(param)"), JavaUtil.ArraysAsList(CssDeclarationValueTokenizer.TokenType
.FUNCTION));
}
[NUnit.Framework.Test]
public virtual void FunctionTest02() {
RunTest("func(param1, param2)", JavaUtil.ArraysAsList("func(param1, param2)"), JavaUtil.ArraysAsList(CssDeclarationValueTokenizer.TokenType
.FUNCTION));
}
[NUnit.Framework.Test]
public virtual void FunctionTest03() {
RunTest("func(param,'param)',\"param))\")", JavaUtil.ArraysAsList("func(param,'param)',\"param))\")"), JavaUtil.ArraysAsList
(CssDeclarationValueTokenizer.TokenType.FUNCTION));
}
[NUnit.Framework.Test]
public virtual void FunctionTest04() {
RunTest("func(param, innerFunc())", JavaUtil.ArraysAsList("func(param, innerFunc())"), JavaUtil.ArraysAsList
(CssDeclarationValueTokenizer.TokenType.FUNCTION));
}
[NUnit.Framework.Test]
public virtual void FunctionTest05() {
RunTest(") )) function()", JavaUtil.ArraysAsList(")", "))", "function()"), JavaUtil.ArraysAsList(CssDeclarationValueTokenizer.TokenType
.UNKNOWN, CssDeclarationValueTokenizer.TokenType.UNKNOWN, CssDeclarationValueTokenizer.TokenType.FUNCTION
));
}
[NUnit.Framework.Test]
public virtual void FunctionTest06() {
RunTest("a('x'), b('x')", JavaUtil.ArraysAsList("a('x')", ",", "b('x')"), JavaUtil.ArraysAsList(CssDeclarationValueTokenizer.TokenType
.FUNCTION, CssDeclarationValueTokenizer.TokenType.COMMA, CssDeclarationValueTokenizer.TokenType.FUNCTION
));
}
private void RunTest(String src, IList<String> tokenValues, IList<CssDeclarationValueTokenizer.TokenType>
tokenTypes) {
CssDeclarationValueTokenizer tokenizer = new CssDeclarationValueTokenizer(src);
CssDeclarationValueTokenizer.Token token = null;
NUnit.Framework.Assert.IsTrue(tokenValues.Count == tokenTypes.Count, "Value and type arrays size should be equal"
);
int index = 0;
while ((token = tokenizer.GetNextValidToken()) != null) {
NUnit.Framework.Assert.AreEqual(tokenValues[index], token.GetValue());
NUnit.Framework.Assert.AreEqual(tokenTypes[index], token.GetType());
++index;
}
NUnit.Framework.Assert.IsTrue(index == tokenValues.Count);
}
}
}

View File

@@ -0,0 +1,61 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using TSpdf.StyledXmlParser.Css;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Resolve {
[NUnit.Framework.Category("UnitTest")]
public class CssInheritanceUnitTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void IsInheritablePositiveTest() {
IStyleInheritance cssInheritance = new CssInheritance();
NUnit.Framework.Assert.IsTrue(cssInheritance.IsInheritable(CommonCssConstants.FONT_SIZE));
}
[NUnit.Framework.Test]
public virtual void IsInheritableNegativeTest() {
IStyleInheritance cssInheritance = new CssInheritance();
NUnit.Framework.Assert.IsFalse(cssInheritance.IsInheritable(CommonCssConstants.FOCUS));
}
}
}

View File

@@ -0,0 +1,139 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Resolve {
[NUnit.Framework.Category("UnitTest")]
public class CssPropertyMergerUnitTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void MergeTextDecorationSimpleTest() {
String firstValue = "underline";
String secondValue = "strikethrough bold";
String expected = "underline strikethrough bold";
String actual = CssPropertyMerger.MergeTextDecoration(firstValue, secondValue);
NUnit.Framework.Assert.AreEqual(expected, actual);
}
[NUnit.Framework.Test]
public virtual void MergeTextDecorationNormalizeFirstTest() {
String firstValue = " underline ";
String secondValue = "strikethrough bold";
String expected = "underline strikethrough bold";
String actual = CssPropertyMerger.MergeTextDecoration(firstValue, secondValue);
NUnit.Framework.Assert.AreEqual(expected, actual);
}
[NUnit.Framework.Test]
public virtual void MergeTextDecorationNormalizeSecondTest() {
String firstValue = "underline";
String secondValue = "strikethrough bold ";
String expected = "underline strikethrough bold";
String actual = CssPropertyMerger.MergeTextDecoration(firstValue, secondValue);
NUnit.Framework.Assert.AreEqual(expected, actual);
}
[NUnit.Framework.Test]
public virtual void MergeTextDecorationFirstNullTest() {
String firstValue = null;
String secondValue = "strikethrough bold";
String expected = "strikethrough bold";
String actual = CssPropertyMerger.MergeTextDecoration(firstValue, secondValue);
NUnit.Framework.Assert.AreEqual(expected, actual);
}
[NUnit.Framework.Test]
public virtual void MergeTextDecorationSecondNullTest() {
String firstValue = "underline";
String secondValue = null;
String expected = "underline";
String actual = CssPropertyMerger.MergeTextDecoration(firstValue, secondValue);
NUnit.Framework.Assert.AreEqual(expected, actual);
}
[NUnit.Framework.Test]
public virtual void MergeTextDecorationBothNullTest() {
String firstValue = null;
String secondValue = null;
String expected = null;
String actual = CssPropertyMerger.MergeTextDecoration(firstValue, secondValue);
NUnit.Framework.Assert.AreEqual(expected, actual);
}
[NUnit.Framework.Test]
public virtual void MergeTextDecorationEmpyInputsTest() {
String firstValue = "";
String secondValue = "";
String expected = "none";
String actual = CssPropertyMerger.MergeTextDecoration(firstValue, secondValue);
NUnit.Framework.Assert.AreEqual(expected, actual);
}
[NUnit.Framework.Test]
public virtual void MergeTextDecorationSecondInputContainsNoneTest() {
String firstValue = "underline";
String secondValue = "none strikethrough";
String expected = "underline";
String actual = CssPropertyMerger.MergeTextDecoration(firstValue, secondValue);
NUnit.Framework.Assert.AreEqual(expected, actual);
}
[NUnit.Framework.Test]
public virtual void MergeTextDecorationFirstInputNoneTest() {
String firstValue = "underline none";
String secondValue = "strikethrough";
String expected = "strikethrough";
String actual = CssPropertyMerger.MergeTextDecoration(firstValue, secondValue);
NUnit.Framework.Assert.AreEqual(expected, actual);
}
[NUnit.Framework.Test]
public virtual void MergeTextDecorationBothInputsNoneTest() {
String firstValue = "underline none";
String secondValue = "strikethrough none";
String expected = "none";
String actual = CssPropertyMerger.MergeTextDecoration(firstValue, secondValue);
NUnit.Framework.Assert.AreEqual(expected, actual);
}
}
}

View File

@@ -0,0 +1,287 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.Commons.Utils;
using TSpdf.StyledXmlParser.Css;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.StyledXmlParser.Css.Resolve.Shorthand {
[NUnit.Framework.Category("UnitTest")]
public class BackgroundPositionShorthandResolverTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void InitialValueTest() {
String shorthandExpression = "initial";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-position-x: initial"
, "background-position-y: initial"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.SHORTHAND_PROPERTY_CANNOT_BE_EMPTY
)]
public virtual void FullEmptyValueTest() {
String shorthandExpression = " ";
ICollection<String> expectedResolvedProperties = new HashSet<String>();
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.SHORTHAND_PROPERTY_CANNOT_BE_EMPTY
)]
public virtual void EmptyValueTest() {
String shorthandExpression = "50pt, , 20pt";
ICollection<String> expectedResolvedProperties = new HashSet<String>();
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void InvalidXValueTest() {
String shorthandExpression = "left right";
ICollection<String> expectedResolvedProperties = new HashSet<String>();
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void NotExistingXValueTest() {
String shorthandExpression = "30jacoco 50pt";
ICollection<String> expectedResolvedProperties = new HashSet<String>();
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void InvalidYValueTest() {
String shorthandExpression = "top bottom";
ICollection<String> expectedResolvedProperties = new HashSet<String>();
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void NotExistingYValueTest() {
String shorthandExpression = "50pt 30jacoco";
ICollection<String> expectedResolvedProperties = new HashSet<String>();
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void InvalidNumericValueTest() {
String shorthandExpression = "50px left top";
ICollection<String> expectedResolvedProperties = new HashSet<String>();
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void InvalidNotShortNumericValueTest() {
String shorthandExpression = "50pt 30px 10pt";
ICollection<String> expectedResolvedProperties = new HashSet<String>();
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void InvalidTopPxShortNumericValueTest() {
String shorthandExpression = "top 50px";
ICollection<String> expectedResolvedProperties = new HashSet<String>();
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void PxCenterShortNumericValueTest() {
String shorthandExpression = "50px center";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-position-x: 50px"
, "background-position-y: center"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void InvalidPxLeftShortNumericValueTest() {
String shorthandExpression = "50px left";
ICollection<String> expectedResolvedProperties = new HashSet<String>();
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void TopPxLeftLargeNumericValueTest() {
String shorthandExpression = "top 50px left";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-position-x: left"
, "background-position-y: top 50px"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void TopLeftPxLargeNumericValueTest() {
String shorthandExpression = "top left 50px";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-position-x: left 50px"
, "background-position-y: top"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void TopPxLeftPxLargeNumericValueTest() {
String shorthandExpression = "top 10px left 50px";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-position-x: left 50px"
, "background-position-y: top 10px"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void InvalidCenterPxTopLargeNumericValueTest() {
String shorthandExpression = "center 50px top";
ICollection<String> expectedResolvedProperties = new HashSet<String>();
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void DoubleHorizontalWithCenterValueTest() {
String shorthandExpression = "center left";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-position-x: left"
, "background-position-y: center"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void InvalidDoubleHorizontalWithCenterAndVerticalValueTest() {
String shorthandExpression = "center top left";
ICollection<String> expectedResolvedProperties = new HashSet<String>();
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void LeftCenterValueTest() {
String shorthandExpression = "left center";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-position-x: left"
, "background-position-y: center"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void InvalidLeftTopCenterValueTest() {
String shorthandExpression = "left bottom center";
ICollection<String> expectedResolvedProperties = new HashSet<String>();
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void MultiValueMissedValueTest() {
String shorthandExpression = "left,top";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-position-x: left,center"
, "background-position-y: center,top"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND_POSITION
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
}
}

View File

@@ -0,0 +1,692 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.Commons.Utils;
using TSpdf.StyledXmlParser.Css;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.StyledXmlParser.Css.Resolve.Shorthand {
[NUnit.Framework.Category("UnitTest")]
public class BackgroundShorthandResolverTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void BackgroundTest01() {
String shorthandExpression = "red url('img.gif') 25%/50px 150px repeat-y border-box content-box fixed";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-color: red"
, "background-image: url('img.gif')", "background-position: 25%", "background-size: 50px 150px", "background-repeat: repeat-y"
, "background-origin: border-box", "background-clip: content-box", "background-attachment: fixed"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BackgroundTest02() {
String shorthandExpression = "url('img.gif') red 25%/50px 150px repeat-y fixed border-box content-box";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-color: red"
, "background-image: url('img.gif')", "background-position: 25%", "background-size: 50px 150px", "background-repeat: repeat-y"
, "background-origin: border-box", "background-clip: content-box", "background-attachment: fixed"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BackgroundTest03() {
String shorthandExpression = "url('img.gif') 25%/50px 150px fixed border-box";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-color: transparent"
, "background-image: url('img.gif')", "background-position: 25%", "background-size: 50px 150px", "background-repeat: repeat"
, "background-origin: padding-box", "background-clip: border-box", "background-attachment: fixed"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage("Was not able to define one of the background CSS shorthand properties: rgdbq(150,90,60)")]
public virtual void BackgroundTest05() {
String shorthandExpression = "rgdbq(150,90,60) url'smiley.gif') repeat-x scroll 20 60%";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BackgroundTest06() {
String shorthandExpression = "DarkOliveGreen fixed center";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-color: darkolivegreen"
, "background-image: none", "background-position: center", "background-size: auto", "background-repeat: repeat"
, "background-origin: padding-box", "background-clip: border-box", "background-attachment: fixed"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.UNKNOWN_PROPERTY)]
public virtual void BackgroundWithSlashInvalidSizeTest1() {
String shorthandExpression = "50px/50";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.UNKNOWN_PROPERTY)]
public virtual void BackgroundWithSlashInvalidSizeTest2() {
String shorthandExpression = "50px/repeat";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.UNKNOWN_PROPERTY)]
public virtual void BackgroundWithSlashInvalidSizeTest3() {
String shorthandExpression = "50px/left";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.WAS_NOT_ABLE_TO_DEFINE_BACKGROUND_CSS_SHORTHAND_PROPERTIES
)]
public virtual void BackgroundWithSlashInvalidSizeTest4() {
String shorthandExpression = "50px/url(img.jpg)";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.WAS_NOT_ABLE_TO_DEFINE_BACKGROUND_CSS_SHORTHAND_PROPERTIES
)]
public virtual void BackgroundWithSlashInvalidSizeTest5() {
String shorthandExpression = "50px/";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void BackgroundWithAnotherShorthandFailedTest() {
String shorthandExpression = "no-repeat left right";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.UNKNOWN_PROPERTY)]
public virtual void BackgroundWithSlashInvalidPositionTest1() {
String shorthandExpression = "50/50px";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.UNKNOWN_PROPERTY)]
public virtual void BackgroundWithSlashInvalidPositionTest2() {
String shorthandExpression = "cover/50px";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.UNKNOWN_PROPERTY)]
public virtual void BackgroundWithSlashInvalidPositionTest3() {
String shorthandExpression = "repeat/50px";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.WAS_NOT_ABLE_TO_DEFINE_BACKGROUND_CSS_SHORTHAND_PROPERTIES
)]
public virtual void BackgroundWithSlashInvalidPositionTest4() {
String shorthandExpression = "url(img.jpg)/50px";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.WAS_NOT_ABLE_TO_DEFINE_BACKGROUND_CSS_SHORTHAND_PROPERTIES
)]
public virtual void BackgroundWithSlashInvalidPositionTest5() {
String shorthandExpression = "/50px";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.WAS_NOT_ABLE_TO_DEFINE_BACKGROUND_CSS_SHORTHAND_PROPERTIES
, Count = 3)]
public virtual void BackgroundIncorrectPositionTest() {
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
String[] incorrectPositions = new String[] { "cover", "auto", "contain" };
foreach (String incorrectPosition in incorrectPositions) {
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(incorrectPosition);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
}
[NUnit.Framework.Test]
public virtual void BackgroundWithMultiSlashTest() {
String shorthandExpression = "50px 5px/25px 5%";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-color: transparent"
, "background-image: none", "background-position: 50px 5px", "background-size: 25px 5%", "background-repeat: repeat"
, "background-origin: padding-box", "background-clip: border-box", "background-attachment: scroll"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.WAS_NOT_ABLE_TO_DEFINE_BACKGROUND_CSS_SHORTHAND_PROPERTIES
)]
public virtual void BackgroundWithMultiSlashFailedOnSizeTest1() {
String shorthandExpression = "50px 5px/25px 5";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.WAS_NOT_ABLE_TO_DEFINE_BACKGROUND_CSS_SHORTHAND_PROPERTIES
)]
public virtual void BackgroundWithMultiSlashFailedOnSizeTest2() {
String shorthandExpression = "50px 5px/25px left";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.WAS_NOT_ABLE_TO_DEFINE_BACKGROUND_CSS_SHORTHAND_PROPERTIES
)]
public virtual void BackgroundWithMultiSlashFailedOnPositionTest1() {
String shorthandExpression = "50 5px/25px 5%";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.WAS_NOT_ABLE_TO_DEFINE_BACKGROUND_CSS_SHORTHAND_PROPERTIES
)]
public virtual void BackgroundWithMultiSlashFailedOnPositionTest2() {
String shorthandExpression = "cover 5px/25px 5%";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.WAS_NOT_ABLE_TO_DEFINE_BACKGROUND_CSS_SHORTHAND_PROPERTIES
)]
public virtual void BackgroundWithTwoSlashesTest1() {
String shorthandExpression = "5px/25px 5%/20px";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.UNKNOWN_PROPERTY)]
public virtual void BackgroundWithTwoSlashesTest2() {
String shorthandExpression = "5px/25px/5%";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BackgroundWithSlashAndSpaceTest1() {
String shorthandExpression = "5px / 25px";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-color: transparent"
, "background-image: none", "background-position: 5px", "background-size: 25px", "background-repeat: repeat"
, "background-origin: padding-box", "background-clip: border-box", "background-attachment: scroll"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BackgroundWithSlashAndSpaceTest2() {
String shorthandExpression = "5px/ 25px";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-color: transparent"
, "background-image: none", "background-position: 5px", "background-size: 25px", "background-repeat: repeat"
, "background-origin: padding-box", "background-clip: border-box", "background-attachment: scroll"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BackgroundWithSlashAndSpaceTest3() {
String shorthandExpression = "5px /25px";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-color: transparent"
, "background-image: none", "background-position: 5px", "background-size: 25px", "background-repeat: repeat"
, "background-origin: padding-box", "background-clip: border-box", "background-attachment: scroll"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.UNKNOWN_PROPERTY)]
public virtual void BackgroundWithSlashAndSpaceIncorrectTest1() {
String shorthandExpression = "repeat / 25px";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.UNKNOWN_PROPERTY)]
public virtual void BackgroundWithSlashAndSpaceIncorrectTest2() {
String shorthandExpression = "5px / repeat";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.UNKNOWN_PROPERTY)]
public virtual void BackgroundWithSlashAndSpaceIncorrectTest3() {
String shorthandExpression = "5px /repeat";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.UNKNOWN_PROPERTY)]
public virtual void BackgroundWithSlashAndSpaceIncorrectTest4() {
String shorthandExpression = "5px/ repeat-y";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.UNKNOWN_PROPERTY)]
public virtual void BackgroundWithSlashAndSpaceIncorrectTest5() {
String shorthandExpression = "repeat-x/ 20px";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.UNKNOWN_PROPERTY)]
public virtual void BackgroundWithSlashAndSpaceIncorrectTest6() {
String shorthandExpression = "no-repeat /20px";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.WAS_NOT_ABLE_TO_DEFINE_BACKGROUND_CSS_SHORTHAND_PROPERTIES
)]
public virtual void BackgroundWithSlashAndSpaceIncorrectTest7() {
String shorthandExpression = "20px /";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.WAS_NOT_ABLE_TO_DEFINE_BACKGROUND_CSS_SHORTHAND_PROPERTIES
)]
public virtual void BackgroundWithSlashAndSpaceIncorrectTest8() {
String shorthandExpression = "/ 20px";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BackgroundInitialInheritUnsetTest() {
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
String[] globalExpressions = new String[] { "initial", "inherit", "unset" };
foreach (String globalExpression in globalExpressions) {
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-color: "
+ globalExpression, "background-image: " + globalExpression, "background-position: " + globalExpression
, "background-size: " + globalExpression, "background-repeat: " + globalExpression, "background-origin: "
+ globalExpression, "background-clip: " + globalExpression, "background-attachment: " + globalExpression
));
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(globalExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.SHORTHAND_PROPERTY_CANNOT_BE_EMPTY
)]
public virtual void BackgroundEmptyShorthandTest() {
String shorthandExpression = "";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.SHORTHAND_PROPERTY_CANNOT_BE_EMPTY
)]
public virtual void BackgroundEmptyShorthandWithSpaceTest() {
String shorthandExpression = " ";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.SHORTHAND_PROPERTY_CANNOT_BE_EMPTY
)]
public virtual void MultiBackgroundEmptyShorthandTest1() {
String shorthandExpression = "none,,none";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.SHORTHAND_PROPERTY_CANNOT_BE_EMPTY
)]
public virtual void MultiBackgroundEmptyShorthandTest2() {
String shorthandExpression = "none,none,";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.SHORTHAND_PROPERTY_CANNOT_BE_EMPTY
)]
public virtual void MultiBackgroundEmptyShorthandTest3() {
String shorthandExpression = ",none,none";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.SHORTHAND_PROPERTY_CANNOT_BE_EMPTY
)]
public virtual void MultiBackgroundEmptyShorthandWithSpaceTest() {
String shorthandExpression = "none, ,none";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BackgroundDefaultValuesShorthandTest() {
String shorthandExpression = "none";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-color: transparent"
, "background-image: none", "background-position: 0% 0%", "background-size: auto", "background-repeat: repeat"
, "background-origin: padding-box", "background-clip: border-box", "background-attachment: scroll"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.ONLY_THE_LAST_BACKGROUND_CAN_INCLUDE_BACKGROUND_COLOR
)]
public virtual void BackgroundColorNotLastTest() {
String shorthandExpression = "url('img.gif') red, url('img2.gif')";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BackgroundColorInImageTest() {
String shorthandExpression = "url('img.gif'), url('img2.gif') blue";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-color: blue"
, "background-image: url('img.gif'),url('img2.gif')", "background-position: 0% 0%,0% 0%", "background-size: auto,auto"
, "background-repeat: repeat,repeat", "background-origin: padding-box,padding-box", "background-clip: border-box,border-box"
, "background-attachment: scroll,scroll"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BackgroundColorNotInImageTest() {
String shorthandExpression = "url('img.gif'), url('img2.gif'), blue";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-color: blue"
, "background-image: url('img.gif'),url('img2.gif'),none", "background-position: 0% 0%,0% 0%,0% 0%", "background-size: auto,auto,auto"
, "background-repeat: repeat,repeat,repeat", "background-origin: padding-box,padding-box,padding-box",
"background-clip: border-box,border-box,border-box", "background-attachment: scroll,scroll,scroll"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void BackgroundDoubleColorTest() {
String shorthandExpression = "url('img.gif'), url('img2.gif') red blue";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BackgroundMultiImageTest() {
String shorthandExpression = "url('img.gif'), url('img2.gif'), url('img3.gif')";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-color: transparent"
, "background-image: url('img.gif'),url('img2.gif'),url('img3.gif')", "background-position: 0% 0%,0% 0%,0% 0%"
, "background-size: auto,auto,auto", "background-repeat: repeat,repeat,repeat", "background-origin: padding-box,padding-box,padding-box"
, "background-clip: border-box,border-box,border-box", "background-attachment: scroll,scroll,scroll"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void BackgroundDoubleImageTest() {
String shorthandExpression = "url('img.gif'), url('img2.gif') url('img3.gif')";
ICollection<String> expectedResolvedProperties = new HashSet<String>(new List<String>());
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BackgroundMultiImageWithOtherPropsTest() {
String shorthandExpression = "url('img.gif') 5px/5% repeat-x border-box padding-box fixed," + " url('img2.gif') left/50px repeat-y border-box border-box local,"
+ "url('img3.gif') center/cover no-repeat padding-box padding-box scroll red";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-color: red"
, "background-image: url('img.gif'),url('img2.gif'),url('img3.gif')", "background-position: 5px,left,center"
, "background-size: 5%,50px,cover", "background-repeat: repeat-x,repeat-y,no-repeat", "background-origin: border-box,border-box,padding-box"
, "background-clip: padding-box,border-box,padding-box", "background-attachment: fixed,local,scroll"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BackgroundMultiImageWithOtherPropsMissedTest() {
String shorthandExpression = "url('img.gif') 5px/5% repeat-x fixed," + " repeat-y border-box border-box local,"
+ "url('img3.gif') center/cover padding-box padding-box red";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("background-color: red"
, "background-image: url('img.gif'),none,url('img3.gif')", "background-position: 5px,0% 0%,center", "background-size: 5%,auto,cover"
, "background-repeat: repeat-x,repeat-y,repeat", "background-origin: padding-box,border-box,padding-box"
, "background-clip: border-box,border-box,padding-box", "background-attachment: fixed,local,scroll"));
IShorthandResolver backgroundResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BACKGROUND
);
NUnit.Framework.Assert.IsNotNull(backgroundResolver);
IList<CssDeclaration> resolvedShorthandProps = backgroundResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
}
}

View File

@@ -0,0 +1,58 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.Commons.Utils;
using TSpdf.StyledXmlParser.Css;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Resolve.Shorthand {
[NUnit.Framework.Category("UnitTest")]
public class BorderRadiusShorthandResolverTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void BorderRadiusSlashTest() {
String shorthandExpression = "20px 40px 40px / 20px 40px 40px";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-bottom-left-radius: 40px 40px"
, "border-bottom-right-radius: 40px 40px", "border-top-left-radius: 20px 20px", "border-top-right-radius: 40px 40px"
));
IShorthandResolver borderRadiusResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants
.BORDER_RADIUS);
NUnit.Framework.Assert.IsNotNull(borderRadiusResolver);
IList<CssDeclaration> resolvedShorthandProps = borderRadiusResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BorderRadiusSingleTest() {
String shorthandExpression = " 20px ";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-bottom-left-radius: 20px"
, "border-bottom-right-radius: 20px", "border-top-left-radius: 20px", "border-top-right-radius: 20px")
);
IShorthandResolver borderRadiusResolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants
.BORDER_RADIUS);
NUnit.Framework.Assert.IsNotNull(borderRadiusResolver);
IList<CssDeclaration> resolvedShorthandProps = borderRadiusResolver.ResolveShorthand(shorthandExpression);
CssShorthandResolverTest.CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
}
}

View File

@@ -0,0 +1,547 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using System.Text;
using TSpdf.Commons.Utils;
using TSpdf.StyledXmlParser.Css;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Resolve.Shorthand {
[NUnit.Framework.Category("UnitTest")]
public class CssShorthandResolverTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void BorderBottomTest01() {
String shorthandExpression = "15px dotted blue";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-bottom-width: 15px"
, "border-bottom-style: dotted", "border-bottom-color: blue"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BORDER_BOTTOM
);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BorderLeftTest01() {
String shorthandExpression = "10px solid #ff0000";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-left-width: 10px"
, "border-left-style: solid", "border-left-color: #ff0000"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BORDER_LEFT
);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BorderRightTest01() {
String shorthandExpression = "10px double rgb(12,220,100)";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-right-width: 10px"
, "border-right-style: double", "border-right-color: rgb(12,220,100)"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BORDER_RIGHT
);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BorderTopTest01() {
String shorthandExpression = "10px hidden rgba(12,225,100,0.7)";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-top-width: 10px"
, "border-top-style: hidden", "border-top-color: rgba(12,225,100,0.7)"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BORDER_TOP);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BorderTest01() {
String shorthandExpression = "thick groove black";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-top-width: thick"
, "border-right-width: thick", "border-bottom-width: thick", "border-left-width: thick", "border-top-style: groove"
, "border-right-style: groove", "border-bottom-style: groove", "border-left-style: groove", "border-top-color: black"
, "border-right-color: black", "border-bottom-color: black", "border-left-color: black"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BORDER);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BorderTest02() {
String shorthandExpression = "groove";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-top-width: initial"
, "border-right-width: initial", "border-bottom-width: initial", "border-left-width: initial", "border-top-style: groove"
, "border-right-style: groove", "border-bottom-style: groove", "border-left-style: groove", "border-bottom-color: initial"
, "border-left-color: initial", "border-right-color: initial", "border-top-color: initial"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BORDER);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BorderTest03() {
String shorthandExpression = "inherit";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-top-width: inherit"
, "border-right-width: inherit", "border-bottom-width: inherit", "border-left-width: inherit", "border-top-style: inherit"
, "border-right-style: inherit", "border-bottom-style: inherit", "border-left-style: inherit", "border-top-color: inherit"
, "border-right-color: inherit", "border-bottom-color: inherit", "border-left-color: inherit"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BORDER);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BorderTest04() {
String shorthandExpression = "dashed";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-top-width: initial"
, "border-right-width: initial", "border-bottom-width: initial", "border-left-width: initial", "border-top-style: dashed"
, "border-right-style: dashed", "border-bottom-style: dashed", "border-left-style: dashed", "border-bottom-color: initial"
, "border-left-color: initial", "border-right-color: initial", "border-top-color: initial"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BORDER);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BorderTest05() {
String shorthandExpression = "dashed green";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-top-width: initial"
, "border-right-width: initial", "border-bottom-width: initial", "border-left-width: initial", "border-top-style: dashed"
, "border-right-style: dashed", "border-bottom-style: dashed", "border-left-style: dashed", "border-top-color: green"
, "border-right-color: green", "border-bottom-color: green", "border-left-color: green"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BORDER);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BorderTest06() {
String shorthandExpression = "1px dashed";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-top-width: 1px"
, "border-right-width: 1px", "border-bottom-width: 1px", "border-left-width: 1px", "border-top-style: dashed"
, "border-right-style: dashed", "border-bottom-style: dashed", "border-left-style: dashed", "border-bottom-color: initial"
, "border-left-color: initial", "border-right-color: initial", "border-top-color: initial"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BORDER);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BorderTest07() {
String shorthandExpression = "1px dashed green";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-top-width: 1px"
, "border-right-width: 1px", "border-bottom-width: 1px", "border-left-width: 1px", "border-top-style: dashed"
, "border-right-style: dashed", "border-bottom-style: dashed", "border-left-style: dashed", "border-top-color: green"
, "border-right-color: green", "border-bottom-color: green", "border-left-color: green"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BORDER);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BorderWidthTest01() {
String shorthandExpression = "thin medium thick 10px";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-top-width: thin"
, "border-right-width: medium", "border-bottom-width: thick", "border-left-width: 10px"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BORDER_WIDTH
);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BorderWidthTest02() {
String shorthandExpression = "thin 20% thick";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-top-width: thin"
, "border-right-width: 20%", "border-bottom-width: thick", "border-left-width: 20%"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BORDER_WIDTH
);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BorderWidthTest03() {
String shorthandExpression = "inherit";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-top-width: inherit"
, "border-right-width: inherit", "border-bottom-width: inherit", "border-left-width: inherit"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BORDER_WIDTH
);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BorderStyleTest01() {
String shorthandExpression = "dotted solid double dashed";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-top-style: dotted"
, "border-right-style: solid", "border-bottom-style: double", "border-left-style: dashed"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BORDER_STYLE
);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BorderStyleTest02() {
String shorthandExpression = "dotted solid";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-top-style: dotted"
, "border-right-style: solid", "border-bottom-style: dotted", "border-left-style: solid"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BORDER_STYLE
);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BorderColorTest01() {
String shorthandExpression = "red rgba(125,0,50,0.4) rgb(12,255,0) #0000ff";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-top-color: red"
, "border-right-color: rgba(125,0,50,0.4)", "border-bottom-color: rgb(12,255,0)", "border-left-color: #0000ff"
));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BORDER_COLOR
);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void BorderColorTest02() {
String shorthandExpression = "red";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("border-top-color: red"
, "border-right-color: red", "border-bottom-color: red", "border-left-color: red"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.BORDER_COLOR
);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void ListStyleTest01() {
String shorthandExpression = "square inside url('sqpurple.gif')";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("list-style-type: square"
, "list-style-position: inside", "list-style-image: url('sqpurple.gif')"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.LIST_STYLE);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void ListStyleTest02() {
String shorthandExpression = "inside url('sqpurple.gif')";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("list-style-type: initial"
, "list-style-position: inside", "list-style-image: url('sqpurple.gif')"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.LIST_STYLE);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void ListStyleTest03() {
String shorthandExpression = "inherit";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("list-style-type: inherit"
, "list-style-position: inherit", "list-style-image: inherit"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.LIST_STYLE);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void MarginTest01() {
String shorthandExpression = "2cm -4cm 3cm 4cm";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("margin-top: 2cm"
, "margin-right: -4cm", "margin-bottom: 3cm", "margin-left: 4cm"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.MARGIN);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void MarginTest02() {
String shorthandExpression = "2cm auto 4cm";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("margin-top: 2cm"
, "margin-right: auto", "margin-bottom: 4cm", "margin-left: auto"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.MARGIN);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void OutlineTest01() {
String shorthandExpression = "#00ff00 dashed medium";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("outline-color: #00ff00"
, "outline-style: dashed", "outline-width: medium"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.OUTLINE);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void PaddingTest01() {
String shorthandExpression = "10px 5px 15px 20px";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("padding-top: 10px"
, "padding-right: 5px", "padding-bottom: 15px", "padding-left: 20px"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.PADDING);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void PaddingTest02() {
String shorthandExpression = "10px 5px";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("padding-top: 10px"
, "padding-right: 5px", "padding-bottom: 10px", "padding-left: 5px"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.PADDING);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void PaddingTest03() {
String shorthandExpression = "inherit";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("padding-top: inherit"
, "padding-right: inherit", "padding-bottom: inherit", "padding-left: inherit"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.PADDING);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void LinearGradientInlistStyleImageTest() {
String shorthandExpression = "inside linear-gradient(red, green, blue)";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("list-style-type: initial"
, "list-style-position: inside", "list-style-image: linear-gradient(red,green,blue)"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.LIST_STYLE);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void RepeatingLinearGradientInlistStyleImageTest() {
String shorthandExpression = "square inside repeating-linear-gradient(45deg, blue 7%, red 10%)";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("list-style-type: square"
, "list-style-position: inside", "list-style-image: repeating-linear-gradient(45deg,blue 7%,red 10%)")
);
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.LIST_STYLE);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void NoneInlistStyleImageTest() {
String shorthandExpression = "circle none inside";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("list-style-type: circle"
, "list-style-position: inside", "list-style-image: none"));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.LIST_STYLE);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void FontTest01() {
String shorthandExpression = "italic normal bold 12px/30px Georgia, serif";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("font-style: italic"
, "font-variant: initial", "font-weight: bold", "font-size: 12px", "line-height: 30px", "font-family: georgia,serif"
));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.FONT);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void FontTest02() {
String shorthandExpression = "bold Georgia, serif";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("font-style: initial"
, "font-variant: initial", "font-weight: bold", "font-size: initial", "line-height: initial", "font-family: georgia,serif"
));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.FONT);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void FontTest03() {
String shorthandExpression = "inherit";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("font-style: inherit"
, "font-variant: inherit", "font-weight: inherit", "font-size: inherit", "line-height: inherit", "font-family: inherit"
));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.FONT);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void FontTest04() {
String shorthandExpression = "bold Georgia, serif, \"Times New Roman\"";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("font-style: initial"
, "font-variant: initial", "font-weight: bold", "font-size: initial", "line-height: initial", "font-family: georgia,serif,\"Times New Roman\""
));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.FONT);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void FontTest05() {
String shorthandExpression = "italic normal bold 12px/30px Georgia, \"Times New Roman\", serif";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("font-style: italic"
, "font-variant: initial", "font-weight: bold", "font-size: 12px", "line-height: 30px", "font-family: georgia,\"Times New Roman\",serif"
));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.FONT);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void FontTest06() {
String shorthandExpression = "italic normal bold 12px/30px Georgia , \"Times New Roman\" , serif";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("font-style: italic"
, "font-variant: initial", "font-weight: bold", "font-size: 12px", "line-height: 30px", "font-family: georgia,\"Times New Roman\",serif"
));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.FONT);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void FontTest07() {
String shorthandExpression = "italic normal bold 12px/30px Georgia , \"Times New Roman\" ";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("font-style: italic"
, "font-variant: initial", "font-weight: bold", "font-size: 12px", "line-height: 30px", "font-family: georgia,\"Times New Roman\""
));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.FONT);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void FontTest08() {
String shorthandExpression = "Georgia,'Times New Roman'";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("font-style: initial"
, "font-variant: initial", "font-weight: initial", "font-size: initial", "line-height: initial", "font-family: georgia,'Times New Roman'"
));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.FONT);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
[NUnit.Framework.Test]
public virtual void FontTest09() {
String shorthandExpression = "Georgia , 'Times New Roman', serif";
ICollection<String> expectedResolvedProperties = new HashSet<String>(JavaUtil.ArraysAsList("font-style: initial"
, "font-variant: initial", "font-weight: initial", "font-size: initial", "line-height: initial", "font-family: georgia,'Times New Roman',serif"
));
IShorthandResolver resolver = ShorthandResolverFactory.GetShorthandResolver(CommonCssConstants.FONT);
NUnit.Framework.Assert.IsNotNull(resolver);
IList<CssDeclaration> resolvedShorthandProps = resolver.ResolveShorthand(shorthandExpression);
CompareResolvedProps(resolvedShorthandProps, expectedResolvedProperties);
}
internal static void CompareResolvedProps(IList<CssDeclaration> actual, ICollection<String> expected) {
ICollection<String> actualSet = new HashSet<String>();
foreach (CssDeclaration cssDecl in actual) {
actualSet.Add(cssDecl.ToString());
}
bool areDifferent = false;
StringBuilder sb = new StringBuilder("Resolved styles are different from expected!");
ICollection<String> expCopy = new SortedSet<String>(expected);
ICollection<String> actCopy = new SortedSet<String>(actualSet);
expCopy.RemoveAll(actualSet);
actCopy.RemoveAll(expected);
if (!expCopy.IsEmpty()) {
areDifferent = true;
sb.Append("\nExpected but not found properties:\n");
foreach (String expProp in expCopy) {
sb.Append(expProp).Append('\n');
}
}
if (!actCopy.IsEmpty()) {
areDifferent = true;
sb.Append("\nNot expected but found properties:\n");
foreach (String actProp in actCopy) {
sb.Append(actProp).Append('\n');
}
}
if (areDifferent) {
NUnit.Framework.Assert.Fail(sb.ToString());
}
}
}
}

View File

@@ -0,0 +1,184 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.Commons.Utils;
using TSpdf.StyledXmlParser.Css;
using TSpdf.StyledXmlParser.Css.Resolve.Shorthand.Impl;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.StyledXmlParser.Css.Resolve.Shorthand {
[NUnit.Framework.Category("UnitTest")]
public class FlexFlowShorthandResolverTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void InitialOrInheritOrUnsetValuesTest() {
IShorthandResolver resolver = new FlexFlowShorthandResolver();
String initialShorthand = CommonCssConstants.INITIAL;
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(initialShorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_DIRECTION, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INITIAL, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_WRAP, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INITIAL, resolvedShorthand[1].GetExpression());
String inheritShorthand = CommonCssConstants.INHERIT;
resolvedShorthand = resolver.ResolveShorthand(inheritShorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_DIRECTION, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INHERIT, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_WRAP, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INHERIT, resolvedShorthand[1].GetExpression());
String unsetShorthand = CommonCssConstants.UNSET;
resolvedShorthand = resolver.ResolveShorthand(unsetShorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_DIRECTION, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.UNSET, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_WRAP, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.UNSET, resolvedShorthand[1].GetExpression());
}
[NUnit.Framework.Test]
public virtual void InitialWithSpacesTest() {
IShorthandResolver resolver = new FlexFlowShorthandResolver();
String initialWithSpacesShorthand = " initial ";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(initialWithSpacesShorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_DIRECTION, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INITIAL, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_WRAP, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INITIAL, resolvedShorthand[1].GetExpression());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION,
Count = 3)]
public virtual void ContainsInitialOrInheritOrUnsetShorthandTest() {
IShorthandResolver resolver = new FlexFlowShorthandResolver();
String containsInitialShorthand = "row initial ";
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(containsInitialShorthand));
String containsInheritShorthand = "inherit wrap";
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(containsInheritShorthand));
String containsUnsetShorthand = "wrap unset";
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(containsUnsetShorthand));
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.SHORTHAND_PROPERTY_CANNOT_BE_EMPTY
, Count = 2)]
public virtual void EmptyShorthandTest() {
IShorthandResolver resolver = new FlexFlowShorthandResolver();
String emptyShorthand = "";
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(emptyShorthand));
String shorthandWithSpaces = " ";
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(shorthandWithSpaces));
}
[NUnit.Framework.Test]
public virtual void ShorthandWithOneDirectionValueTest() {
IShorthandResolver resolver = new FlexFlowShorthandResolver();
String shorthand = "column";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_DIRECTION, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual("column", resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_WRAP, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual("nowrap", resolvedShorthand[1].GetExpression());
}
[NUnit.Framework.Test]
public virtual void ShorthandWithOneWrapValueTest() {
IShorthandResolver resolver = new FlexFlowShorthandResolver();
String shorthand = CommonCssConstants.WRAP_REVERSE;
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_WRAP, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.WRAP_REVERSE, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_DIRECTION, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.ROW, resolvedShorthand[1].GetExpression());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION,
Count = 1)]
public virtual void ShorthandWithOneInvalidValueTest() {
IShorthandResolver resolver = new FlexFlowShorthandResolver();
String shorthand = "invalid";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
public virtual void ShorthandWithDirectionAndWrapValuesTest() {
IShorthandResolver resolver = new FlexFlowShorthandResolver();
String shorthand = CommonCssConstants.ROW_REVERSE + " " + CommonCssConstants.WRAP;
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_DIRECTION, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.ROW_REVERSE, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_WRAP, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.WRAP, resolvedShorthand[1].GetExpression());
}
[NUnit.Framework.Test]
public virtual void ShorthandWithWrapAndDirectionValuesTest() {
IShorthandResolver resolver = new FlexFlowShorthandResolver();
String shorthand = "wrap-reverse column";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_DIRECTION, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.COLUMN, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_WRAP, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.WRAP_REVERSE, resolvedShorthand[1].GetExpression());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithTwoDirectionValuesTest() {
IShorthandResolver resolver = new FlexFlowShorthandResolver();
String shorthand = "column-reverse row";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolvedShorthand);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithTwoWrapValuesTest() {
IShorthandResolver resolver = new FlexFlowShorthandResolver();
String shorthand = "nowrap wrap-reverse";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolvedShorthand);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithTwoValuesAndSecondIsInvalidTest() {
IShorthandResolver resolver = new FlexFlowShorthandResolver();
String shorthand = "column-reverse invalid";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolvedShorthand);
}
}
}

View File

@@ -0,0 +1,325 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.Commons.Utils;
using TSpdf.StyledXmlParser.Css;
using TSpdf.StyledXmlParser.Css.Resolve.Shorthand.Impl;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.StyledXmlParser.Css.Resolve.Shorthand {
[NUnit.Framework.Category("UnitTest")]
public class FlexShorthandResolverTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.SHORTHAND_PROPERTY_CANNOT_BE_EMPTY
, Count = 2)]
public virtual void EmptyShorthandTest() {
String emptyShorthand = "";
IShorthandResolver resolver = new FlexShorthandResolver();
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(emptyShorthand));
String shorthandWithSpaces = " ";
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(shorthandWithSpaces));
}
[NUnit.Framework.Test]
public virtual void InitialOrInheritOrUnsetShorthandTest() {
String initialShorthand = CommonCssConstants.INITIAL;
IShorthandResolver resolver = new FlexShorthandResolver();
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(initialShorthand);
NUnit.Framework.Assert.AreEqual(3, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_GROW, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INITIAL, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_SHRINK, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INITIAL, resolvedShorthand[1].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_BASIS, resolvedShorthand[2].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INITIAL, resolvedShorthand[2].GetExpression());
String inheritShorthand = CommonCssConstants.INHERIT;
resolvedShorthand = resolver.ResolveShorthand(inheritShorthand);
NUnit.Framework.Assert.AreEqual(3, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_GROW, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INHERIT, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_SHRINK, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INHERIT, resolvedShorthand[1].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_BASIS, resolvedShorthand[2].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INHERIT, resolvedShorthand[2].GetExpression());
String unsetShorthand = CommonCssConstants.UNSET;
resolvedShorthand = resolver.ResolveShorthand(unsetShorthand);
NUnit.Framework.Assert.AreEqual(3, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_GROW, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.UNSET, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_SHRINK, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.UNSET, resolvedShorthand[1].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_BASIS, resolvedShorthand[2].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.UNSET, resolvedShorthand[2].GetExpression());
}
[NUnit.Framework.Test]
public virtual void InitialWithSpacesTest() {
IShorthandResolver resolver = new FlexShorthandResolver();
String initialWithSpacesShorthand = " initial ";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(initialWithSpacesShorthand);
NUnit.Framework.Assert.AreEqual(3, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_GROW, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INITIAL, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_SHRINK, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INITIAL, resolvedShorthand[1].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_BASIS, resolvedShorthand[2].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INITIAL, resolvedShorthand[2].GetExpression());
}
[NUnit.Framework.Test]
public virtual void AutoShorthandTest() {
String initialShorthand = CommonCssConstants.AUTO;
IShorthandResolver resolver = new FlexShorthandResolver();
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(initialShorthand);
NUnit.Framework.Assert.AreEqual(3, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_GROW, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual("1", resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_SHRINK, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual("1", resolvedShorthand[1].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_BASIS, resolvedShorthand[2].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.AUTO, resolvedShorthand[2].GetExpression());
}
[NUnit.Framework.Test]
public virtual void NoneShorthandTest() {
String initialShorthand = CommonCssConstants.NONE;
IShorthandResolver resolver = new FlexShorthandResolver();
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(initialShorthand);
NUnit.Framework.Assert.AreEqual(3, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_GROW, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual("0", resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_SHRINK, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual("0", resolvedShorthand[1].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_BASIS, resolvedShorthand[2].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.AUTO, resolvedShorthand[2].GetExpression());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION,
Count = 3)]
public virtual void ContainsInitialOrInheritOrUnsetShorthandTest() {
IShorthandResolver resolver = new FlexShorthandResolver();
String containsInitialShorthand = "1 initial 50px";
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(containsInitialShorthand));
String containsInheritShorthand = "inherit 2 50px";
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(containsInheritShorthand));
String containsUnsetShorthand = "0 2 unset";
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(containsUnsetShorthand));
}
[NUnit.Framework.Test]
public virtual void ShorthandWithOneUnitlessNumberValueTest() {
IShorthandResolver resolver = new FlexShorthandResolver();
String shorthand = "5";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(3, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_GROW, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual("5", resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_SHRINK, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual("1", resolvedShorthand[1].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_BASIS, resolvedShorthand[2].GetProperty());
NUnit.Framework.Assert.AreEqual("0", resolvedShorthand[2].GetExpression());
}
[NUnit.Framework.Test]
public virtual void ShorthandWithOneUnitNumberValueTest() {
IShorthandResolver resolver = new FlexShorthandResolver();
String shorthand = "5px";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(3, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_BASIS, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual("5px", resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_GROW, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual("0", resolvedShorthand[1].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_SHRINK, resolvedShorthand[2].GetProperty());
NUnit.Framework.Assert.AreEqual("1", resolvedShorthand[2].GetExpression());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithOneInvalidValueTest() {
IShorthandResolver resolver = new FlexShorthandResolver();
String shorthand = "5pixels";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
public virtual void ShorthandWithTwoUnitlessNumberValuesTest() {
IShorthandResolver resolver = new FlexShorthandResolver();
String shorthand = "5 7";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(3, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_GROW, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual("5", resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_SHRINK, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual("7", resolvedShorthand[1].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_BASIS, resolvedShorthand[2].GetProperty());
NUnit.Framework.Assert.AreEqual("0", resolvedShorthand[2].GetExpression());
}
[NUnit.Framework.Test]
public virtual void ShorthandWithUnitlessAndUnitNumberValuesTest() {
IShorthandResolver resolver = new FlexShorthandResolver();
String shorthand = "5 7px";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(3, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_GROW, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual("5", resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_BASIS, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual("7px", resolvedShorthand[1].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_SHRINK, resolvedShorthand[2].GetProperty());
NUnit.Framework.Assert.AreEqual("1", resolvedShorthand[2].GetExpression());
}
[NUnit.Framework.Test]
public virtual void ShorthandWithUnitAndUnitlessNumberValuesTest() {
IShorthandResolver resolver = new FlexShorthandResolver();
String shorthand = "5px 7";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(3, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_BASIS, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual("5px", resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_GROW, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual("7", resolvedShorthand[1].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_SHRINK, resolvedShorthand[2].GetProperty());
NUnit.Framework.Assert.AreEqual("1", resolvedShorthand[2].GetExpression());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithTwoUnitValuesTest() {
IShorthandResolver resolver = new FlexShorthandResolver();
String shorthand = "5px 7px";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithOneUnitlessAndOneInvalidValuesTest() {
IShorthandResolver resolver = new FlexShorthandResolver();
String shorthand = "5 invalid";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithTwoValuesAndFirstIsInvalidTest() {
IShorthandResolver resolver = new FlexShorthandResolver();
String shorthand = "invalid 5px";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
public virtual void ShorthandWithTwoUnitlessAndOneUnitValuesTest() {
IShorthandResolver resolver = new FlexShorthandResolver();
String shorthand = "5 7 10px";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(3, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_GROW, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual("5", resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_SHRINK, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual("7", resolvedShorthand[1].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_BASIS, resolvedShorthand[2].GetProperty());
NUnit.Framework.Assert.AreEqual("10px", resolvedShorthand[2].GetExpression());
}
[NUnit.Framework.Test]
public virtual void ShorthandWithOneUnitAndTwoUnitlessValuesTest() {
IShorthandResolver resolver = new FlexShorthandResolver();
String shorthand = "5px 7 10";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(3, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_GROW, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual("7", resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_SHRINK, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual("10", resolvedShorthand[1].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.FLEX_BASIS, resolvedShorthand[2].GetProperty());
NUnit.Framework.Assert.AreEqual("5px", resolvedShorthand[2].GetExpression());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithThreeUnitlessValuesTest() {
IShorthandResolver resolver = new FlexShorthandResolver();
String shorthand = "5 7 10";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithOneUnitlessOneUnitAndOneUnitlessValuesTest() {
IShorthandResolver resolver = new FlexShorthandResolver();
String shorthand = "5 7px 10";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithThreeUnitValuesTest() {
IShorthandResolver resolver = new FlexShorthandResolver();
String shorthand = "5px 7px 10px";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithOneUnitOneUnitlessAndOneUnitValuesTest() {
IShorthandResolver resolver = new FlexShorthandResolver();
String shorthand = "5px 7 10px";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithThreeValuesAndFirstIsInvalidTest() {
IShorthandResolver resolver = new FlexShorthandResolver();
String shorthand = "invalid 7 10";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithFourValuesTest() {
IShorthandResolver resolver = new FlexShorthandResolver();
String shorthand = "5 7 10 13";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolvedShorthand);
}
}
}

View File

@@ -0,0 +1,173 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.Commons.Utils;
using TSpdf.StyledXmlParser.Css;
using TSpdf.StyledXmlParser.Css.Resolve.Shorthand.Impl;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.StyledXmlParser.Css.Resolve.Shorthand {
[NUnit.Framework.Category("UnitTest")]
public class GapShorthandResolverTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void InitialOrInheritOrUnsetValuesTest() {
IShorthandResolver resolver = new GapShorthandResolver();
String initialShorthand = CommonCssConstants.INITIAL;
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(initialShorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.ROW_GAP, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INITIAL, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.COLUMN_GAP, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INITIAL, resolvedShorthand[1].GetExpression());
String inheritShorthand = CommonCssConstants.INHERIT;
resolvedShorthand = resolver.ResolveShorthand(inheritShorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.ROW_GAP, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INHERIT, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.COLUMN_GAP, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INHERIT, resolvedShorthand[1].GetExpression());
String unsetShorthand = CommonCssConstants.UNSET;
resolvedShorthand = resolver.ResolveShorthand(unsetShorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.ROW_GAP, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.UNSET, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.COLUMN_GAP, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.UNSET, resolvedShorthand[1].GetExpression());
}
[NUnit.Framework.Test]
public virtual void InitialWithSpacesTest() {
IShorthandResolver resolver = new GapShorthandResolver();
String initialWithSpacesShorthand = " initial ";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(initialWithSpacesShorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.ROW_GAP, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INITIAL, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.COLUMN_GAP, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INITIAL, resolvedShorthand[1].GetExpression());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION,
Count = 3)]
public virtual void ContainsInitialOrInheritOrUnsetShorthandTest() {
IShorthandResolver resolver = new GapShorthandResolver();
String containsInitialShorthand = "10px initial ";
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(containsInitialShorthand));
String containsInheritShorthand = "inherit 10%";
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(containsInheritShorthand));
String containsUnsetShorthand = "0 unset";
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(containsUnsetShorthand));
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.SHORTHAND_PROPERTY_CANNOT_BE_EMPTY
, Count = 2)]
public virtual void EmptyShorthandTest() {
IShorthandResolver resolver = new GapShorthandResolver();
String emptyShorthand = "";
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(emptyShorthand));
String shorthandWithSpaces = " ";
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(shorthandWithSpaces));
}
[NUnit.Framework.Test]
public virtual void GapWithOneValidValueTest() {
IShorthandResolver resolver = new GapShorthandResolver();
String shorthand = "10px";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.ROW_GAP, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual("10px", resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.COLUMN_GAP, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual("10px", resolvedShorthand[1].GetExpression());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void GapWithOneInvalidValueTest() {
IShorthandResolver resolver = new GapShorthandResolver();
String shorthand = "10";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
public virtual void GapWithTwoValidValuesTest() {
IShorthandResolver resolver = new GapShorthandResolver();
String shorthand = "10px 15px";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.ROW_GAP, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual("10px", resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.COLUMN_GAP, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual("15px", resolvedShorthand[1].GetExpression());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void GapWithValidAndInvalidValuesTest() {
IShorthandResolver resolver = new GapShorthandResolver();
String shorthand = "10px 15";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void GapWithInvalidAndValidValuesTest() {
IShorthandResolver resolver = new GapShorthandResolver();
String shorthand = "10 15px";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
public virtual void GapWithZeroNumberTest() {
IShorthandResolver resolver = new GapShorthandResolver();
String shorthand = "0 10px";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.ROW_GAP, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual("0", resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.COLUMN_GAP, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual("10px", resolvedShorthand[1].GetExpression());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void GapWithThreeValuesTest() {
IShorthandResolver resolver = new GapShorthandResolver();
String shorthand = "10px 15px 20px";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolvedShorthand);
}
}
}

View File

@@ -0,0 +1,265 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.Commons.Utils;
using TSpdf.StyledXmlParser.Css;
using TSpdf.StyledXmlParser.Css.Resolve.Shorthand.Impl;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.StyledXmlParser.Css.Resolve.Shorthand {
[NUnit.Framework.Category("UnitTest")]
public class PlaceItemsShorthandResolverTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void InitialOrInheritOrUnsetValuesTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String initialShorthand = CommonCssConstants.INITIAL;
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(initialShorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.ALIGN_ITEMS, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INITIAL, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.JUSTIFY_ITEMS, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INITIAL, resolvedShorthand[1].GetExpression());
String inheritShorthand = CommonCssConstants.INHERIT;
resolvedShorthand = resolver.ResolveShorthand(inheritShorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.ALIGN_ITEMS, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INHERIT, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.JUSTIFY_ITEMS, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INHERIT, resolvedShorthand[1].GetExpression());
String unsetShorthand = CommonCssConstants.UNSET;
resolvedShorthand = resolver.ResolveShorthand(unsetShorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.ALIGN_ITEMS, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.UNSET, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.JUSTIFY_ITEMS, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.UNSET, resolvedShorthand[1].GetExpression());
}
[NUnit.Framework.Test]
public virtual void InitialWithSpacesTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String initialWithSpacesShorthand = " initial ";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(initialWithSpacesShorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.ALIGN_ITEMS, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INITIAL, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.JUSTIFY_ITEMS, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.INITIAL, resolvedShorthand[1].GetExpression());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION,
Count = 3)]
public virtual void ContainsInitialOrInheritOrUnsetShorthandTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String containsInitialShorthand = "start initial ";
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(containsInitialShorthand));
String containsInheritShorthand = "inherit safe end";
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(containsInheritShorthand));
String containsUnsetShorthand = "baseline unset";
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(containsUnsetShorthand));
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.SHORTHAND_PROPERTY_CANNOT_BE_EMPTY
, Count = 2)]
public virtual void EmptyShorthandTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String emptyShorthand = "";
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(emptyShorthand));
String shorthandWithSpaces = " ";
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolver.ResolveShorthand
(shorthandWithSpaces));
}
[NUnit.Framework.Test]
public virtual void ShorthandWithOneValidWordTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String shorthand = "baseline";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.ALIGN_ITEMS, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual("baseline", resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.JUSTIFY_ITEMS, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual("baseline", resolvedShorthand[1].GetExpression());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithOneInvalidAlignItemsWordTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String shorthand = "legacy";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithOneInvalidWordTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String shorthand = "invalid";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
public virtual void ShorthandWithTwoWordsAlignItemsTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String shorthand = "unsafe start";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.ALIGN_ITEMS, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual("unsafe start", resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.JUSTIFY_ITEMS, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual("unsafe start", resolvedShorthand[1].GetExpression());
}
[NUnit.Framework.Test]
public virtual void ShorthandWithOneWordAlignItemsAndOneWordJustifyItemsTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String shorthand = CommonCssConstants.CENTER + " " + CommonCssConstants.LEGACY + " " + CommonCssConstants.
RIGHT;
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.ALIGN_ITEMS, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.CENTER, resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.JUSTIFY_ITEMS, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.LEGACY + " " + CommonCssConstants.RIGHT, resolvedShorthand
[1].GetExpression());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithTwoWordsAndFirstWordIsInvalidTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String shorthand = "invalid self-end";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithTwoWordsAndSecondWordIsInvalidTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String shorthand = "flex-start invalid";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
public virtual void ShorthandWithOneWordAlignItemsAndTwoWordsJustifyItemsTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String shorthand = "flex-start legacy right";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.ALIGN_ITEMS, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual("flex-start", resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.JUSTIFY_ITEMS, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual("legacy right", resolvedShorthand[1].GetExpression());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithOneWordAlignItemsAndInvalidTwoWordsJustifyItemsTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String shorthand = "flex-start legacy invalid";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
public virtual void ShorthandWithTwoWordsAlignItemsAndOneWordJustifyItemsTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String shorthand = "unsafe flex-start normal";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.ALIGN_ITEMS, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual("unsafe flex-start", resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.JUSTIFY_ITEMS, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual("normal", resolvedShorthand[1].GetExpression());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithTwoWordsAlignItemsAndInvalidOneWordJustifyItemsTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String shorthand = "unsafe flex-start invalid";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithThreeWordsAndInvalidAlignItemsTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String shorthand = "invalid safe self-end";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
public virtual void ShorthandWithTwoWordsAlignItemsAndTwoWordsJustifyItemsTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String shorthand = "first baseline legacy center";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(2, resolvedShorthand.Count);
NUnit.Framework.Assert.AreEqual(CommonCssConstants.ALIGN_ITEMS, resolvedShorthand[0].GetProperty());
NUnit.Framework.Assert.AreEqual("first baseline", resolvedShorthand[0].GetExpression());
NUnit.Framework.Assert.AreEqual(CommonCssConstants.JUSTIFY_ITEMS, resolvedShorthand[1].GetProperty());
NUnit.Framework.Assert.AreEqual("legacy center", resolvedShorthand[1].GetExpression());
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithTwoWordsAlignItemsAndInvalidTwoWordsJustifyItemsTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String shorthand = "first baseline invalid center";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithInvalidTwoWordsAlignItemsAndTwoWordsJustifyItemsTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String shorthand = "invalid baseline legacy left";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(0, resolvedShorthand.Count);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INVALID_CSS_PROPERTY_DECLARATION)]
public virtual void ShorthandWithFiveWordsTest() {
IShorthandResolver resolver = new PlaceItemsShorthandResolver();
String shorthand = "last baseline unsafe safe center";
IList<CssDeclaration> resolvedShorthand = resolver.ResolveShorthand(shorthand);
NUnit.Framework.Assert.AreEqual(JavaCollectionsUtil.EmptyList<CssDeclaration>(), resolvedShorthand);
}
}
}

View File

@@ -0,0 +1,174 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.StyledXmlParser.Css;
using TSpdf.StyledXmlParser.Css.Resolve.Shorthand.Impl;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Resolve.Shorthand {
[NUnit.Framework.Category("UnitTest")]
public class TextDecorationUnitTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void ResolveShorthandLineEmptyTest() {
TextDecorationShorthandResolver resolver = new TextDecorationShorthandResolver();
IList<CssDeclaration> result = resolver.ResolveShorthand("");
IDictionary<String, String> resultMap = ConvertCssDeclarationsToMap(result);
NUnit.Framework.Assert.AreEqual(3, resultMap.Count);
NUnit.Framework.Assert.AreEqual("initial", resultMap.Get("text-decoration-line"));
NUnit.Framework.Assert.AreEqual("initial", resultMap.Get("text-decoration-style"));
NUnit.Framework.Assert.AreEqual("initial", resultMap.Get("text-decoration-color"));
}
[NUnit.Framework.Test]
public virtual void ResolveShorthandLineNoneTest() {
TextDecorationShorthandResolver resolver = new TextDecorationShorthandResolver();
IList<CssDeclaration> result = resolver.ResolveShorthand("none");
IDictionary<String, String> resultMap = ConvertCssDeclarationsToMap(result);
NUnit.Framework.Assert.AreEqual(3, resultMap.Count);
NUnit.Framework.Assert.AreEqual("none", resultMap.Get("text-decoration-line"));
NUnit.Framework.Assert.AreEqual("initial", resultMap.Get("text-decoration-style"));
NUnit.Framework.Assert.AreEqual("initial", resultMap.Get("text-decoration-color"));
}
[NUnit.Framework.Test]
public virtual void ResolveShorthandLineNoneAndUnderlineTogetherTest() {
TextDecorationShorthandResolver resolver = new TextDecorationShorthandResolver();
IList<CssDeclaration> result = resolver.ResolveShorthand("none underline");
IDictionary<String, String> resultMap = ConvertCssDeclarationsToMap(result);
NUnit.Framework.Assert.AreEqual(3, resultMap.Count);
String line = resultMap.Get("text-decoration-line");
NUnit.Framework.Assert.IsTrue(line != null && line.Contains("underline") && line.Contains("none"));
NUnit.Framework.Assert.AreEqual("initial", resultMap.Get("text-decoration-style"));
NUnit.Framework.Assert.AreEqual("initial", resultMap.Get("text-decoration-color"));
}
[NUnit.Framework.Test]
public virtual void ResolveShorthandLineOnePropertyTest() {
TextDecorationShorthandResolver resolver = new TextDecorationShorthandResolver();
IList<CssDeclaration> result = resolver.ResolveShorthand("underline");
IDictionary<String, String> resultMap = ConvertCssDeclarationsToMap(result);
NUnit.Framework.Assert.AreEqual(3, resultMap.Count);
NUnit.Framework.Assert.AreEqual("underline", resultMap.Get("text-decoration-line"));
NUnit.Framework.Assert.AreEqual("initial", resultMap.Get("text-decoration-style"));
NUnit.Framework.Assert.AreEqual("initial", resultMap.Get("text-decoration-color"));
}
[NUnit.Framework.Test]
public virtual void ResolveShorthandLineTwoPropertiesTest() {
TextDecorationShorthandResolver resolver = new TextDecorationShorthandResolver();
IList<CssDeclaration> result = resolver.ResolveShorthand("underline overline");
IDictionary<String, String> resultMap = ConvertCssDeclarationsToMap(result);
NUnit.Framework.Assert.AreEqual(3, resultMap.Count);
String line = resultMap.Get("text-decoration-line");
NUnit.Framework.Assert.IsTrue(line != null && line.Contains("underline") && line.Contains("overline"));
NUnit.Framework.Assert.AreEqual("initial", resultMap.Get("text-decoration-style"));
NUnit.Framework.Assert.AreEqual("initial", resultMap.Get("text-decoration-color"));
}
[NUnit.Framework.Test]
public virtual void ResolveShorthandColorNamedTest() {
TextDecorationShorthandResolver resolver = new TextDecorationShorthandResolver();
IList<CssDeclaration> result = resolver.ResolveShorthand("underline red");
IDictionary<String, String> resultMap = ConvertCssDeclarationsToMap(result);
NUnit.Framework.Assert.AreEqual(3, resultMap.Count);
NUnit.Framework.Assert.AreEqual("underline", resultMap.Get("text-decoration-line"));
NUnit.Framework.Assert.AreEqual("initial", resultMap.Get("text-decoration-style"));
NUnit.Framework.Assert.AreEqual("red", resultMap.Get("text-decoration-color"));
}
[NUnit.Framework.Test]
public virtual void ResolveShorthandColorRgbTest() {
TextDecorationShorthandResolver resolver = new TextDecorationShorthandResolver();
IList<CssDeclaration> result = resolver.ResolveShorthand("underline rgb(255, 255, 0)");
IDictionary<String, String> resultMap = ConvertCssDeclarationsToMap(result);
NUnit.Framework.Assert.AreEqual(3, resultMap.Count);
NUnit.Framework.Assert.AreEqual("underline", resultMap.Get("text-decoration-line"));
NUnit.Framework.Assert.AreEqual("initial", resultMap.Get("text-decoration-style"));
NUnit.Framework.Assert.AreEqual("rgb(255,255,0)", resultMap.Get("text-decoration-color"));
}
[NUnit.Framework.Test]
public virtual void ResolveShorthandColorRgbWithOpacityTest() {
TextDecorationShorthandResolver resolver = new TextDecorationShorthandResolver();
IList<CssDeclaration> result = resolver.ResolveShorthand("underline rgb(255, 255, 0, 0.5)");
IDictionary<String, String> resultMap = ConvertCssDeclarationsToMap(result);
NUnit.Framework.Assert.AreEqual(3, resultMap.Count);
NUnit.Framework.Assert.AreEqual("underline", resultMap.Get("text-decoration-line"));
NUnit.Framework.Assert.AreEqual("initial", resultMap.Get("text-decoration-style"));
NUnit.Framework.Assert.AreEqual("rgb(255,255,0,0.5)", resultMap.Get("text-decoration-color"));
}
[NUnit.Framework.Test]
public virtual void ResolveShorthandColorHslTest() {
TextDecorationShorthandResolver resolver = new TextDecorationShorthandResolver();
IList<CssDeclaration> result = resolver.ResolveShorthand("underline hsl(300, 76%, 72%)");
IDictionary<String, String> resultMap = ConvertCssDeclarationsToMap(result);
NUnit.Framework.Assert.AreEqual(3, resultMap.Count);
NUnit.Framework.Assert.AreEqual("underline", resultMap.Get("text-decoration-line"));
NUnit.Framework.Assert.AreEqual("initial", resultMap.Get("text-decoration-style"));
NUnit.Framework.Assert.AreEqual("hsl(300,76%,72%)", resultMap.Get("text-decoration-color"));
}
[NUnit.Framework.Test]
public virtual void ResolveShorthandColorHexTest() {
TextDecorationShorthandResolver resolver = new TextDecorationShorthandResolver();
IList<CssDeclaration> result = resolver.ResolveShorthand("underline #DDAA55");
IDictionary<String, String> resultMap = ConvertCssDeclarationsToMap(result);
NUnit.Framework.Assert.AreEqual(3, resultMap.Count);
NUnit.Framework.Assert.AreEqual("underline", resultMap.Get("text-decoration-line"));
NUnit.Framework.Assert.AreEqual("initial", resultMap.Get("text-decoration-style"));
NUnit.Framework.Assert.AreEqual("#ddaa55", resultMap.Get("text-decoration-color"));
}
[NUnit.Framework.Test]
public virtual void ResolveShorthandStyleOnePropertyTest() {
TextDecorationShorthandResolver resolver = new TextDecorationShorthandResolver();
IList<CssDeclaration> result = resolver.ResolveShorthand("underline wavy");
IDictionary<String, String> resultMap = ConvertCssDeclarationsToMap(result);
NUnit.Framework.Assert.AreEqual(3, resultMap.Count);
NUnit.Framework.Assert.AreEqual("underline", resultMap.Get("text-decoration-line"));
NUnit.Framework.Assert.AreEqual("wavy", resultMap.Get("text-decoration-style"));
NUnit.Framework.Assert.AreEqual("initial", resultMap.Get("text-decoration-color"));
}
[NUnit.Framework.Test]
public virtual void ResolveShorthandStyleTwoPropertiesTest() {
TextDecorationShorthandResolver resolver = new TextDecorationShorthandResolver();
IList<CssDeclaration> result = resolver.ResolveShorthand("underline wavy dotted");
IDictionary<String, String> resultMap = ConvertCssDeclarationsToMap(result);
NUnit.Framework.Assert.AreEqual(3, resultMap.Count);
NUnit.Framework.Assert.AreEqual("underline", resultMap.Get("text-decoration-line"));
NUnit.Framework.Assert.AreEqual("dotted", resultMap.Get("text-decoration-style"));
NUnit.Framework.Assert.AreEqual("initial", resultMap.Get("text-decoration-color"));
}
private IDictionary<String, String> ConvertCssDeclarationsToMap(IList<CssDeclaration> declarations) {
IDictionary<String, String> result = new Dictionary<String, String>();
foreach (CssDeclaration decl in declarations) {
result.Put(decl.GetProperty(), decl.GetExpression());
}
return result;
}
}
}

View File

@@ -0,0 +1,190 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using TSpdf.StyledXmlParser;
using TSpdf.StyledXmlParser.Node;
using TSpdf.StyledXmlParser.Node.Impl.Jsoup;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Selector.Item {
[NUnit.Framework.Category("UnitTest")]
public class CssMatchesTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void MatchesEmptySelectorItemTest() {
CssPseudoClassEmptySelectorItem item = CssPseudoClassEmptySelectorItem.GetInstance();
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode documentNode = htmlParser.Parse("<div><input value=\"Alexander\"></div>");
INode bodyNode = documentNode.ChildNodes()[0].ChildNodes()[1];
INode divNode = bodyNode.ChildNodes()[0].ChildNodes()[0];
NUnit.Framework.Assert.IsTrue(item.Matches(divNode));
}
[NUnit.Framework.Test]
public virtual void MatchesEmptySelectorItemNotTaggedTextTest() {
CssPseudoClassEmptySelectorItem item = CssPseudoClassEmptySelectorItem.GetInstance();
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode documentNode = htmlParser.Parse("Some text!");
INode bodyNode = documentNode.ChildNodes()[0].ChildNodes()[1];
INode divNode = bodyNode.ChildNodes()[0];
NUnit.Framework.Assert.IsFalse(item.Matches(divNode));
}
[NUnit.Framework.Test]
public virtual void MatchesEmptySelectorItemSpaceTest() {
CssPseudoClassEmptySelectorItem item = CssPseudoClassEmptySelectorItem.GetInstance();
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode documentNode = htmlParser.Parse("<div> </div>");
INode bodyNode = documentNode.ChildNodes()[0].ChildNodes()[1];
INode divNode = bodyNode.ChildNodes()[0];
NUnit.Framework.Assert.IsFalse(item.Matches(divNode));
}
[NUnit.Framework.Test]
public virtual void MatchesFirstOfTypeSelectorItemTest() {
CssPseudoClassFirstOfTypeSelectorItem item = CssPseudoClassFirstOfTypeSelectorItem.GetInstance();
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode documentNode = htmlParser.Parse("<div><p>Alexander</p><p>Alexander</p></div>");
INode bodyNode = documentNode.ChildNodes()[0].ChildNodes()[1];
INode divNode = bodyNode.ChildNodes()[0].ChildNodes()[0];
NUnit.Framework.Assert.IsTrue(item.Matches(divNode));
}
[NUnit.Framework.Test]
public virtual void MatchesFirstOfTypeSelectorItemTestNotTaggedText() {
CssPseudoClassFirstOfTypeSelectorItem item = CssPseudoClassFirstOfTypeSelectorItem.GetInstance();
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode documentNode = htmlParser.Parse("Some text!");
INode bodyNode = documentNode.ChildNodes()[0].ChildNodes()[1];
INode divNode = bodyNode.ChildNodes()[0];
NUnit.Framework.Assert.IsFalse(item.Matches(divNode));
}
[NUnit.Framework.Test]
public virtual void MatchesLastOfTypeSelectorItemTest() {
CssPseudoClassLastOfTypeSelectorItem item = CssPseudoClassLastOfTypeSelectorItem.GetInstance();
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode documentNode = htmlParser.Parse("<div><p>Alexander</p><p>Alexander</p></div>");
INode bodyNode = documentNode.ChildNodes()[0].ChildNodes()[1];
INode divNode = bodyNode.ChildNodes()[0].ChildNodes()[1];
NUnit.Framework.Assert.IsTrue(item.Matches(divNode));
}
[NUnit.Framework.Test]
public virtual void MatchesLastOfTypeSelectorItemTestNotTaggedText() {
CssPseudoClassLastOfTypeSelectorItem item = CssPseudoClassLastOfTypeSelectorItem.GetInstance();
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode documentNode = htmlParser.Parse("SomeText!");
INode bodyNode = documentNode.ChildNodes()[0].ChildNodes()[1];
INode divNode = bodyNode.ChildNodes()[0];
NUnit.Framework.Assert.IsFalse(item.Matches(divNode));
}
[NUnit.Framework.Test]
public virtual void MatchesLastChildSelectorItemTest() {
CssPseudoClassLastChildSelectorItem item = CssPseudoClassLastChildSelectorItem.GetInstance();
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode documentNode = htmlParser.Parse("<div><p>Alexander</p><p>Alexander</p></div>");
INode bodyNode = documentNode.ChildNodes()[0].ChildNodes()[1];
INode divNode = bodyNode.ChildNodes()[0].ChildNodes()[1];
NUnit.Framework.Assert.IsTrue(item.Matches(divNode));
}
[NUnit.Framework.Test]
public virtual void MatchesLastChildSelectorItemTestNotTaggedText() {
CssPseudoClassLastChildSelectorItem item = CssPseudoClassLastChildSelectorItem.GetInstance();
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode documentNode = htmlParser.Parse("SomeText!");
INode bodyNode = documentNode.ChildNodes()[0].ChildNodes()[1];
INode divNode = bodyNode.ChildNodes()[0];
NUnit.Framework.Assert.IsFalse(item.Matches(divNode));
}
[NUnit.Framework.Test]
public virtual void MatchesNthOfTypeSelectorItemTest() {
CssPseudoClassNthOfTypeSelectorItem item = new CssPseudoClassNthOfTypeSelectorItem("1n");
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode documentNode = htmlParser.Parse("<div><p>Alexander</p><p>Alexander</p></div>");
INode bodyNode = documentNode.ChildNodes()[0].ChildNodes()[1];
INode divNode = bodyNode.ChildNodes()[0].ChildNodes()[0];
NUnit.Framework.Assert.IsTrue(item.Matches(divNode));
}
[NUnit.Framework.Test]
public virtual void MatchesNthOfTypeSelectorItemTestNotTaggedText() {
CssPseudoClassNthOfTypeSelectorItem item = new CssPseudoClassNthOfTypeSelectorItem("1n");
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode documentNode = htmlParser.Parse("SomeText!");
INode bodyNode = documentNode.ChildNodes()[0].ChildNodes()[1];
INode divNode = bodyNode.ChildNodes()[0];
NUnit.Framework.Assert.IsFalse(item.Matches(divNode));
}
[NUnit.Framework.Test]
public virtual void MatchesNthOfTypeSelectorItemTestBadNodeArgument() {
CssPseudoClassNthOfTypeSelectorItem item = new CssPseudoClassNthOfTypeSelectorItem("text");
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode documentNode = htmlParser.Parse("<div><p>Alexander</p><p>Alexander</p></div>");
INode bodyNode = documentNode.ChildNodes()[0].ChildNodes()[1];
INode divNode = bodyNode.ChildNodes()[0].ChildNodes()[0];
NUnit.Framework.Assert.IsFalse(item.Matches(divNode));
}
[NUnit.Framework.Test]
public virtual void MatchesRootSelectorItemTest() {
CssPseudoClassRootSelectorItem item = CssPseudoClassRootSelectorItem.GetInstance();
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode documentNode = htmlParser.Parse("<div><p>Alexander</p><p>Alexander</p></div>");
INode headNode = documentNode.ChildNodes()[0];
NUnit.Framework.Assert.IsTrue(item.Matches(headNode));
}
[NUnit.Framework.Test]
public virtual void MatchesRootSelectorItemTestNotTaggedText() {
CssPseudoClassRootSelectorItem item = CssPseudoClassRootSelectorItem.GetInstance();
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode documentNode = htmlParser.Parse("SomeText!");
INode bodyNode = documentNode.ChildNodes()[0].ChildNodes()[1];
INode divNode = bodyNode.ChildNodes()[0];
NUnit.Framework.Assert.IsFalse(item.Matches(divNode));
}
}
}

View File

@@ -0,0 +1,74 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.IO;
using TSpdf.StyledXmlParser;
using TSpdf.StyledXmlParser.Node;
using TSpdf.StyledXmlParser.Node.Impl.Jsoup;
using TSpdf.StyledXmlParser.Node.Impl.Jsoup.Node;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Selector.Item {
[NUnit.Framework.Category("UnitTest")]
public class CssPseudoClassDisabledSelectorItemTest : ExtendedTSpdfTest {
private static readonly String sourceFolder = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/styledxmlparser/css/selector/item/CssPseudoClassDisabledSelectorItemTest/";
[NUnit.Framework.Test]
public virtual void TestDisabledSelector() {
String filename = sourceFolder + "disabled.html";
CssPseudoClassDisabledSelectorItem item = CssPseudoClassDisabledSelectorItem.GetInstance();
IXmlParser htmlParser = new JsoupHtmlParser();
IDocumentNode documentNode = htmlParser.Parse(new FileStream(filename, FileMode.Open, FileAccess.Read), "UTF-8"
);
IElementNode disabledInput = new JsoupElementNode(((JsoupDocumentNode)documentNode).GetDocument().GetElementsByTag
("input").First());
IElementNode enabledInput = new JsoupElementNode(((JsoupDocumentNode)documentNode).GetDocument().GetElementsByTag
("input")[1]);
NUnit.Framework.Assert.IsFalse(item.Matches(documentNode));
NUnit.Framework.Assert.IsTrue(item.Matches(disabledInput));
NUnit.Framework.Assert.IsFalse(item.Matches(enabledInput));
NUnit.Framework.Assert.IsFalse(item.Matches(null));
}
}
}

View File

@@ -0,0 +1,218 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using TSpdf.StyledXmlParser.Css.Selector;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Selector.Item {
[NUnit.Framework.Category("UnitTest")]
public class SpecificityCalculationTest : ExtendedTSpdfTest {
// https://www.smashingmagazine.com/2007/07/css-specificity-things-you-should-know/
// https://specificity.keegan.st/
[NUnit.Framework.Test]
public virtual void Test01() {
NUnit.Framework.Assert.AreEqual(0, GetSpecificity("*"));
}
[NUnit.Framework.Test]
public virtual void Test02() {
NUnit.Framework.Assert.AreEqual(1, GetSpecificity("li"));
}
[NUnit.Framework.Test]
public virtual void Test03() {
NUnit.Framework.Assert.AreEqual(2, GetSpecificity("li:first-line"));
}
[NUnit.Framework.Test]
public virtual void Test04() {
NUnit.Framework.Assert.AreEqual(2, GetSpecificity("ul li"));
}
[NUnit.Framework.Test]
public virtual void Test05() {
NUnit.Framework.Assert.AreEqual(3, GetSpecificity("ul ol+li"));
}
[NUnit.Framework.Test]
public virtual void Test06() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.CLASS_SPECIFICITY + CssSpecificityConstants.ELEMENT_SPECIFICITY
, GetSpecificity("h1 + *[rel=up]"));
}
[NUnit.Framework.Test]
public virtual void Test07() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.CLASS_SPECIFICITY + CssSpecificityConstants.ELEMENT_SPECIFICITY
* 3, GetSpecificity("ul ol li.red"));
}
[NUnit.Framework.Test]
public virtual void Test08() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.CLASS_SPECIFICITY * 2 + CssSpecificityConstants.ELEMENT_SPECIFICITY
, GetSpecificity("li.red.level"));
}
[NUnit.Framework.Test]
public virtual void Test09() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.CLASS_SPECIFICITY, GetSpecificity(".sith"));
}
[NUnit.Framework.Test]
public virtual void Test10() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.CLASS_SPECIFICITY + CssSpecificityConstants.ELEMENT_SPECIFICITY
* 2, GetSpecificity("div p.sith"));
}
[NUnit.Framework.Test]
public virtual void Test11() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.ID_SPECIFICITY, GetSpecificity("#sith"));
}
[NUnit.Framework.Test]
public virtual void Test12() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.ID_SPECIFICITY + CssSpecificityConstants.CLASS_SPECIFICITY
+ CssSpecificityConstants.ELEMENT_SPECIFICITY * 2, GetSpecificity("body #darkside .sith p"));
}
[NUnit.Framework.Test]
public virtual void Test13() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.CLASS_SPECIFICITY * 2 + CssSpecificityConstants.ELEMENT_SPECIFICITY
* 2, GetSpecificity("li:first-child h2 .title"));
}
[NUnit.Framework.Test]
public virtual void Test14() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.ID_SPECIFICITY + CssSpecificityConstants.CLASS_SPECIFICITY
* 2 + CssSpecificityConstants.ELEMENT_SPECIFICITY, GetSpecificity("#nav .selected > a:hover"));
}
[NUnit.Framework.Test]
public virtual void Test15() {
NUnit.Framework.Assert.AreEqual(2, GetSpecificity("p:before"));
NUnit.Framework.Assert.AreEqual(2, GetSpecificity("p::before"));
}
[NUnit.Framework.Test]
public virtual void Test16() {
NUnit.Framework.Assert.AreEqual(2, GetSpecificity("a::hover"));
}
[NUnit.Framework.Test]
public virtual void Test17() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.CLASS_SPECIFICITY * 2, GetSpecificity(".class_name:nth-child(3n + 1)"
));
}
[NUnit.Framework.Test]
public virtual void Test18() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.CLASS_SPECIFICITY * 2, GetSpecificity(".class_name:nth-child(2n - 3)"
));
}
[NUnit.Framework.Test]
public virtual void Test19() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.CLASS_SPECIFICITY * 2, GetSpecificity(".class_name:hover"
));
}
[NUnit.Framework.Test]
public virtual void Test20() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.CLASS_SPECIFICITY, GetSpecificity(":not(p)"));
}
[NUnit.Framework.Test]
public virtual void Test21() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.CLASS_SPECIFICITY, GetSpecificity(":not(#id)"));
}
[NUnit.Framework.Test]
public virtual void Test22() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.CLASS_SPECIFICITY, GetSpecificity(":not(.class_name)"
));
}
[NUnit.Framework.Test]
public virtual void PageTest01() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.ID_SPECIFICITY, GetPageSelectorSpecificity("customPageName"
));
}
[NUnit.Framework.Test]
public virtual void PageTest02() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.ID_SPECIFICITY + CssSpecificityConstants.CLASS_SPECIFICITY
, GetPageSelectorSpecificity("customPageName:first"));
}
[NUnit.Framework.Test]
public virtual void PageTest03() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.ID_SPECIFICITY + CssSpecificityConstants.CLASS_SPECIFICITY
* 2, GetPageSelectorSpecificity("customPageName:first:blank"));
}
[NUnit.Framework.Test]
public virtual void PageTest04() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.ELEMENT_SPECIFICITY * 2, GetPageSelectorSpecificity
(":left:right"));
}
[NUnit.Framework.Test]
public virtual void PageTest05() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.ID_SPECIFICITY + CssSpecificityConstants.CLASS_SPECIFICITY
, GetPageSelectorSpecificity("left:blank"));
}
[NUnit.Framework.Test]
public virtual void PageTest06() {
NUnit.Framework.Assert.AreEqual(CssSpecificityConstants.ELEMENT_SPECIFICITY + CssSpecificityConstants.CLASS_SPECIFICITY
, GetPageSelectorSpecificity(":left:blank"));
}
private int GetSpecificity(String selector) {
return new CssSelector(selector).CalculateSpecificity();
}
private int GetPageSelectorSpecificity(String selector) {
return new CssPageSelector(selector).CalculateSpecificity();
}
}
}

View File

@@ -0,0 +1,115 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using TSpdf.Layout.Properties;
using TSpdf.StyledXmlParser.Css;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.StyledXmlParser.Css.Util {
[NUnit.Framework.Category("UnitTest")]
public class CssBackgroundUtilsTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void ParseBackgroundRepeatTest() {
NUnit.Framework.Assert.AreEqual(BackgroundRepeat.BackgroundRepeatValue.REPEAT, CssBackgroundUtils.ParseBackgroundRepeat
("repeat"));
NUnit.Framework.Assert.AreEqual(BackgroundRepeat.BackgroundRepeatValue.REPEAT, CssBackgroundUtils.ParseBackgroundRepeat
("RePeAt"));
NUnit.Framework.Assert.AreEqual(BackgroundRepeat.BackgroundRepeatValue.NO_REPEAT, CssBackgroundUtils.ParseBackgroundRepeat
("no-repeat"));
NUnit.Framework.Assert.AreEqual(BackgroundRepeat.BackgroundRepeatValue.REPEAT, CssBackgroundUtils.ParseBackgroundRepeat
("no- repeat"));
NUnit.Framework.Assert.AreEqual(BackgroundRepeat.BackgroundRepeatValue.ROUND, CssBackgroundUtils.ParseBackgroundRepeat
("round"));
NUnit.Framework.Assert.AreEqual(BackgroundRepeat.BackgroundRepeatValue.REPEAT, CssBackgroundUtils.ParseBackgroundRepeat
("ro!und"));
NUnit.Framework.Assert.AreEqual(BackgroundRepeat.BackgroundRepeatValue.SPACE, CssBackgroundUtils.ParseBackgroundRepeat
("space"));
NUnit.Framework.Assert.AreEqual(BackgroundRepeat.BackgroundRepeatValue.REPEAT, CssBackgroundUtils.ParseBackgroundRepeat
(" space "));
NUnit.Framework.Assert.AreEqual(BackgroundRepeat.BackgroundRepeatValue.REPEAT, CssBackgroundUtils.ParseBackgroundRepeat
("something"));
}
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.URL_IS_NOT_CLOSED_IN_CSS_EXPRESSION
)]
[NUnit.Framework.Test]
public virtual void ResolveBackgroundPropertyTypeTest() {
NUnit.Framework.Assert.AreEqual(CssBackgroundUtils.BackgroundPropertyType.UNDEFINED, CssBackgroundUtils.ResolveBackgroundPropertyType
("jaja"));
NUnit.Framework.Assert.AreEqual(CssBackgroundUtils.BackgroundPropertyType.UNDEFINED, CssBackgroundUtils.ResolveBackgroundPropertyType
("ul(rock_texture.jpg)"));
NUnit.Framework.Assert.AreEqual(CssBackgroundUtils.BackgroundPropertyType.UNDEFINED, CssBackgroundUtils.ResolveBackgroundPropertyType
("url(rock_texture.jpg"));
NUnit.Framework.Assert.AreEqual(CssBackgroundUtils.BackgroundPropertyType.UNDEFINED, CssBackgroundUtils.ResolveBackgroundPropertyType
("url(rock(_texture.jpg)"));
NUnit.Framework.Assert.AreEqual(CssBackgroundUtils.BackgroundPropertyType.UNDEFINED, CssBackgroundUtils.ResolveBackgroundPropertyType
("url(rock_t(ext)ure.jpg)"));
NUnit.Framework.Assert.AreEqual(CssBackgroundUtils.BackgroundPropertyType.UNDEFINED, CssBackgroundUtils.ResolveBackgroundPropertyType
("url(url(rock_texture.jpg)"));
NUnit.Framework.Assert.AreEqual(CssBackgroundUtils.BackgroundPropertyType.BACKGROUND_IMAGE, CssBackgroundUtils
.ResolveBackgroundPropertyType("url(rock_texture.jpg)"));
NUnit.Framework.Assert.AreEqual(CssBackgroundUtils.BackgroundPropertyType.BACKGROUND_IMAGE, CssBackgroundUtils
.ResolveBackgroundPropertyType("linear-gradient(#e66465, #9198e5)"));
NUnit.Framework.Assert.AreEqual(CssBackgroundUtils.BackgroundPropertyType.BACKGROUND_IMAGE, CssBackgroundUtils
.ResolveBackgroundPropertyType("none"));
NUnit.Framework.Assert.AreEqual(CssBackgroundUtils.BackgroundPropertyType.BACKGROUND_REPEAT, CssBackgroundUtils
.ResolveBackgroundPropertyType("repeat-x"));
NUnit.Framework.Assert.AreEqual(CssBackgroundUtils.BackgroundPropertyType.BACKGROUND_POSITION_X, CssBackgroundUtils
.ResolveBackgroundPropertyType("left"));
NUnit.Framework.Assert.AreEqual(CssBackgroundUtils.BackgroundPropertyType.BACKGROUND_POSITION_Y, CssBackgroundUtils
.ResolveBackgroundPropertyType("bottom"));
NUnit.Framework.Assert.AreEqual(CssBackgroundUtils.BackgroundPropertyType.BACKGROUND_POSITION, CssBackgroundUtils
.ResolveBackgroundPropertyType("center"));
NUnit.Framework.Assert.AreEqual(CssBackgroundUtils.BackgroundPropertyType.BACKGROUND_POSITION_OR_SIZE, CssBackgroundUtils
.ResolveBackgroundPropertyType("10%"));
NUnit.Framework.Assert.AreEqual(CssBackgroundUtils.BackgroundPropertyType.BACKGROUND_SIZE, CssBackgroundUtils
.ResolveBackgroundPropertyType("contain"));
NUnit.Framework.Assert.AreEqual(CssBackgroundUtils.BackgroundPropertyType.BACKGROUND_ORIGIN_OR_CLIP, CssBackgroundUtils
.ResolveBackgroundPropertyType("padding-box"));
NUnit.Framework.Assert.AreEqual(CssBackgroundUtils.BackgroundPropertyType.BACKGROUND_ATTACHMENT, CssBackgroundUtils
.ResolveBackgroundPropertyType("fixed"));
}
[NUnit.Framework.Test]
public virtual void GetBackgroundPropertyNameFromType() {
NUnit.Framework.Assert.AreEqual(CommonCssConstants.BACKGROUND_COLOR, CssBackgroundUtils.GetBackgroundPropertyNameFromType
(CssBackgroundUtils.BackgroundPropertyType.BACKGROUND_COLOR));
NUnit.Framework.Assert.AreEqual(CommonCssConstants.BACKGROUND_IMAGE, CssBackgroundUtils.GetBackgroundPropertyNameFromType
(CssBackgroundUtils.BackgroundPropertyType.BACKGROUND_IMAGE));
NUnit.Framework.Assert.AreEqual(CommonCssConstants.BACKGROUND_CLIP, CssBackgroundUtils.GetBackgroundPropertyNameFromType
(CssBackgroundUtils.BackgroundPropertyType.BACKGROUND_CLIP));
NUnit.Framework.Assert.AreEqual(CommonCssConstants.BACKGROUND_ORIGIN, CssBackgroundUtils.GetBackgroundPropertyNameFromType
(CssBackgroundUtils.BackgroundPropertyType.BACKGROUND_ORIGIN));
NUnit.Framework.Assert.AreEqual(CommonCssConstants.BACKGROUND_POSITION, CssBackgroundUtils.GetBackgroundPropertyNameFromType
(CssBackgroundUtils.BackgroundPropertyType.BACKGROUND_POSITION));
NUnit.Framework.Assert.AreEqual(CommonCssConstants.BACKGROUND_REPEAT, CssBackgroundUtils.GetBackgroundPropertyNameFromType
(CssBackgroundUtils.BackgroundPropertyType.BACKGROUND_REPEAT));
NUnit.Framework.Assert.AreEqual(CommonCssConstants.BACKGROUND_SIZE, CssBackgroundUtils.GetBackgroundPropertyNameFromType
(CssBackgroundUtils.BackgroundPropertyType.BACKGROUND_SIZE));
NUnit.Framework.Assert.AreEqual(CommonCssConstants.BACKGROUND_ATTACHMENT, CssBackgroundUtils.GetBackgroundPropertyNameFromType
(CssBackgroundUtils.BackgroundPropertyType.BACKGROUND_ATTACHMENT));
NUnit.Framework.Assert.AreEqual(CommonCssConstants.UNDEFINED_NAME, CssBackgroundUtils.GetBackgroundPropertyNameFromType
(CssBackgroundUtils.BackgroundPropertyType.UNDEFINED));
}
}
}

View File

@@ -0,0 +1,278 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Commons.Utils;
using TSpdf.Kernel.Colors;
using TSpdf.Layout.Properties;
using TSpdf.StyledXmlParser.Css;
using TSpdf.StyledXmlParser.Exceptions;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.StyledXmlParser.Css.Util {
[NUnit.Framework.Category("UnitTest")]
public class CssDimensionParsingUtilsTest : ExtendedTSpdfTest {
private const float EPS = 0.0001f;
[NUnit.Framework.Test]
public virtual void ParseAbsoluteFontSizeTest() {
NUnit.Framework.Assert.AreEqual(75, CssDimensionParsingUtils.ParseAbsoluteFontSize("100", CommonCssConstants
.PX), EPS);
NUnit.Framework.Assert.AreEqual(75, CssDimensionParsingUtils.ParseAbsoluteFontSize("100px"), EPS);
NUnit.Framework.Assert.AreEqual(12, CssDimensionParsingUtils.ParseAbsoluteFontSize(CommonCssConstants.MEDIUM
), EPS);
NUnit.Framework.Assert.AreEqual(0, CssDimensionParsingUtils.ParseAbsoluteFontSize("", ""), EPS);
}
[NUnit.Framework.Test]
public virtual void ParseRelativeFontSizeTest() {
NUnit.Framework.Assert.AreEqual(120, CssDimensionParsingUtils.ParseRelativeFontSize("10em", 12), EPS);
NUnit.Framework.Assert.AreEqual(12.5f, CssDimensionParsingUtils.ParseRelativeFontSize(CommonCssConstants.SMALLER
, 15), EPS);
}
[NUnit.Framework.Test]
public virtual void ParseResolutionValidDpiUnit() {
NUnit.Framework.Assert.AreEqual(10f, CssDimensionParsingUtils.ParseResolution("10dpi"), 0);
}
[NUnit.Framework.Test]
public virtual void ParseResolutionValidDpcmUnit() {
NUnit.Framework.Assert.AreEqual(25.4f, CssDimensionParsingUtils.ParseResolution("10dpcm"), 0);
}
[NUnit.Framework.Test]
public virtual void ParseResolutionValidDppxUnit() {
NUnit.Framework.Assert.AreEqual(960f, CssDimensionParsingUtils.ParseResolution("10dppx"), 0);
}
[NUnit.Framework.Test]
public virtual void ParseResolutionInvalidUnit() {
Exception e = NUnit.Framework.Assert.Catch(typeof(StyledXMLParserException), () => CssDimensionParsingUtils
.ParseResolution("10incorrectUnit"));
NUnit.Framework.Assert.AreEqual(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INCORRECT_RESOLUTION_UNIT_VALUE
, e.Message);
}
[NUnit.Framework.Test]
public virtual void ParseInvalidFloat() {
String value = "invalidFloat";
try {
NUnit.Framework.Assert.IsNull(CssDimensionParsingUtils.ParseFloat(value));
}
catch (Exception) {
NUnit.Framework.Assert.Fail();
}
}
[NUnit.Framework.Test]
public virtual void ParseAbsoluteLengthFrom10px() {
String value = "10px";
float actual = CssDimensionParsingUtils.ParseAbsoluteLength(value, CommonCssConstants.PX);
float expected = 7.5f;
NUnit.Framework.Assert.AreEqual(expected, actual, 0);
}
[NUnit.Framework.Test]
public virtual void ParseAbsoluteLengthFrom10cm() {
String value = "10cm";
float actual = CssDimensionParsingUtils.ParseAbsoluteLength(value, CommonCssConstants.CM);
float expected = 283.46457f;
NUnit.Framework.Assert.AreEqual(expected, actual, 0);
}
[NUnit.Framework.Test]
public virtual void ParseAbsoluteLengthFrom10in() {
String value = "10in";
float actual = CssDimensionParsingUtils.ParseAbsoluteLength(value, CommonCssConstants.IN);
float expected = 720.0f;
NUnit.Framework.Assert.AreEqual(expected, actual, 0);
}
[NUnit.Framework.Test]
public virtual void ParseAbsoluteLengthFrom10pt() {
String value = "10pt";
float actual = CssDimensionParsingUtils.ParseAbsoluteLength(value, CommonCssConstants.PT);
float expected = 10.0f;
NUnit.Framework.Assert.AreEqual(expected, actual, 0);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.UNKNOWN_ABSOLUTE_METRIC_LENGTH_PARSED
, Count = 1)]
public virtual void ParseAbsoluteLengthFromUnknownType() {
String value = "10pateekes";
float actual = CssDimensionParsingUtils.ParseAbsoluteLength(value, "pateekes");
float expected = 10.0f;
NUnit.Framework.Assert.AreEqual(expected, actual, 0);
}
[NUnit.Framework.Test]
public virtual void ParseLength() {
NUnit.Framework.Assert.AreEqual(9, CssDimensionParsingUtils.ParseAbsoluteLength("12"), 0);
NUnit.Framework.Assert.AreEqual(576, CssDimensionParsingUtils.ParseAbsoluteLength("8inch"), 0);
NUnit.Framework.Assert.AreEqual(576, CssDimensionParsingUtils.ParseAbsoluteLength("8", CommonCssConstants.
IN), 0);
}
[NUnit.Framework.Test]
public virtual void ParseAbsoluteLengthTest() {
NUnit.Framework.Assert.AreEqual(75, CssDimensionParsingUtils.ParseAbsoluteLength("100", CommonCssConstants
.PX), EPS);
NUnit.Framework.Assert.AreEqual(75, CssDimensionParsingUtils.ParseAbsoluteLength("100px"), EPS);
}
[NUnit.Framework.Test]
public virtual void ParseAbsoluteLengthFromNAN() {
String value = "Definitely not a number";
Exception e = NUnit.Framework.Assert.Catch(typeof(StyledXMLParserException), () => CssDimensionParsingUtils
.ParseAbsoluteLength(value));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(StyledXMLParserException.NAN, "Definitely not a number"
), e.Message);
}
[NUnit.Framework.Test]
public virtual void ParseAbsoluteLengthFromNull() {
String value = null;
Exception e = NUnit.Framework.Assert.Catch(typeof(StyledXMLParserException), () => CssDimensionParsingUtils
.ParseAbsoluteLength(value));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(StyledXMLParserException.NAN, "null"), e.Message);
}
[NUnit.Framework.Test]
public virtual void ParseAbsoluteLengthExponentialPtTest() {
String value = "1e2pt";
float actual = CssDimensionParsingUtils.ParseAbsoluteLength(value);
float expected = 1e2f;
NUnit.Framework.Assert.AreEqual(expected, actual, 0);
}
[NUnit.Framework.Test]
public virtual void ParseAbsoluteLengthExponentialPxTest() {
String value = "1e2px";
float actual = CssDimensionParsingUtils.ParseAbsoluteLength(value);
float expected = 1e2f * 0.75f;
NUnit.Framework.Assert.AreEqual(expected, actual, 0);
}
[NUnit.Framework.Test]
public virtual void ParseAbsoluteLengthExponentialCapitalTest() {
String value = "1E-4";
float actual = CssDimensionParsingUtils.ParseAbsoluteLength(value);
float expected = 1e-4f * 0.75f;
NUnit.Framework.Assert.AreEqual(expected, actual, 1e-9);
}
[NUnit.Framework.Test]
public virtual void ParseAbsoluteLength12cmTest() {
// Calculations in CssUtils#parseAbsoluteLength were changed to work
// with double values instead of float to improve precision and eliminate
// the difference between java and .net. So the test verifies this fix.
NUnit.Framework.Assert.AreEqual(340.15747f, CssDimensionParsingUtils.ParseAbsoluteLength("12cm"), 0f);
}
[NUnit.Framework.Test]
public virtual void ParseAbsoluteLength12qTest() {
// Calculations in CssUtils#parseAbsoluteLength were changed to work
// with double values instead of float to improve precision and eliminate
// the difference between java and .net. So the test verifies this fix
NUnit.Framework.Assert.AreEqual(8.503937f, CssDimensionParsingUtils.ParseAbsoluteLength("12q"), 0f);
}
[NUnit.Framework.Test]
public virtual void ParseDoubleIntegerValueTest() {
double? expectedString = 5.0;
double? actualString = CssDimensionParsingUtils.ParseDouble("5");
NUnit.Framework.Assert.AreEqual(expectedString, actualString);
}
[NUnit.Framework.Test]
public virtual void ParseDoubleManyCharsAfterDotTest() {
double? expectedString = 5.123456789;
double? actualString = CssDimensionParsingUtils.ParseDouble("5.123456789");
NUnit.Framework.Assert.AreEqual(expectedString, actualString);
}
[NUnit.Framework.Test]
public virtual void ParseDoubleManyCharsAfterDotNegativeTest() {
double? expectedString = -5.123456789;
double? actualString = CssDimensionParsingUtils.ParseDouble("-5.123456789");
NUnit.Framework.Assert.AreEqual(expectedString, actualString);
}
[NUnit.Framework.Test]
public virtual void ParseDoubleNullValueTest() {
double? expectedString = null;
double? actualString = CssDimensionParsingUtils.ParseDouble(null);
NUnit.Framework.Assert.AreEqual(expectedString, actualString);
}
[NUnit.Framework.Test]
public virtual void ParseDoubleNegativeTextTest() {
double? expectedString = null;
double? actualString = CssDimensionParsingUtils.ParseDouble("text");
NUnit.Framework.Assert.AreEqual(expectedString, actualString);
}
[NUnit.Framework.Test]
public virtual void ParseSimpleDeviceCmykTest() {
TransparentColor expected = new TransparentColor(new DeviceCmyk(0f, 0.4f, 0.6f, 1f), 1);
TransparentColor actual = CssDimensionParsingUtils.ParseColor("device-cmyk(0 40% 60% 100%)");
NUnit.Framework.Assert.AreEqual(expected.GetColor(), actual.GetColor());
NUnit.Framework.Assert.AreEqual(expected.GetOpacity(), actual.GetOpacity(), 0.0001f);
}
[NUnit.Framework.Test]
public virtual void ParseDeviceCmykWithOpacityTest() {
TransparentColor expected = new TransparentColor(new DeviceCmyk(0f, 0.4f, 0.6f, 1f), 0.5f);
TransparentColor actual = CssDimensionParsingUtils.ParseColor("device-cmyk(0 40% 60% 100% / .5)");
NUnit.Framework.Assert.AreEqual(expected.GetColor(), actual.GetColor());
NUnit.Framework.Assert.AreEqual(expected.GetOpacity(), actual.GetOpacity(), 0.0001f);
}
[NUnit.Framework.Test]
public virtual void ParseDeviceCmykWithFallbackAndOpacityTest() {
TransparentColor expected = new TransparentColor(new DeviceCmyk(0f, 0.4f, 0.6f, 1f), 0.5f);
TransparentColor actual = CssDimensionParsingUtils.ParseColor("device-cmyk(0 40% 60% 100% / .5 rgb(178 34 34))"
);
NUnit.Framework.Assert.AreEqual(expected.GetColor(), actual.GetColor());
NUnit.Framework.Assert.AreEqual(expected.GetOpacity(), actual.GetOpacity(), 0.0001f);
}
[NUnit.Framework.Test]
public virtual void ParseRgbTest() {
TransparentColor expected = new TransparentColor(new DeviceRgb(255, 255, 128), 1f);
TransparentColor actual = CssDimensionParsingUtils.ParseColor("rgb(255, 255, 128)");
NUnit.Framework.Assert.AreEqual(expected.GetColor(), actual.GetColor());
NUnit.Framework.Assert.AreEqual(expected.GetOpacity(), actual.GetOpacity(), 0.0001f);
}
[NUnit.Framework.Test]
public virtual void ParseInvalidColorTest() {
TransparentColor expected = new TransparentColor(new DeviceRgb(0, 0, 0), 1f);
TransparentColor actual = CssDimensionParsingUtils.ParseColor("currentcolor");
NUnit.Framework.Assert.AreEqual(expected.GetColor(), actual.GetColor());
NUnit.Framework.Assert.AreEqual(expected.GetOpacity(), actual.GetOpacity(), 0.0001f);
}
}
}

View File

@@ -0,0 +1,80 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Util {
[NUnit.Framework.Category("UnitTest")]
public class CssPropertyNormalizerTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void CheckUrlNormalizationSimpleTest() {
Test("url('data:image/png;base64,iVBORw0K')", "url('data:image/png;base64,iVBORw0K')");
}
[NUnit.Framework.Test]
public virtual void CheckUrlNormalizationUppercaseTest() {
Test("URL('data:image/png;base64,iVBORw0K')", "url('data:image/png;base64,iVBORw0K')");
Test("uRL('data:image/png;base64,iVBORw0K')", "url('data:image/png;base64,iVBORw0K')");
Test("urL('data:image/png;base64,iVBORw0K')", "url('data:image/png;base64,iVBORw0K')");
}
[NUnit.Framework.Test]
public virtual void CheckUrlNormalizationWhitespacesTest() {
Test(" url( 'data:image/png;base64,iVBORw0K' )", "url('data:image/png;base64,iVBORw0K')");
}
[NUnit.Framework.Test]
public virtual void CheckUrlNormalizationLineTerminatorsTest() {
// Test is initially added to ensure equal behavior between Java and C#.
// The behavior itself might be reconsidered in the future. Browsers do not forgive newlines in base64 expressions
Test("url(data:image/png;base64,iVBOR\nw0K)", "url(data:image/png;base64,iVBOR\nw0K)");
Test("url(data:image/png;base64,iVBOR\rw0K)", "url(data:image/png;base64,iVBOR\rw0K)");
Test("url(data:image/png;base64,iVBOR\r\nw0K)", "url(data:image/png;base64,iVBOR\r\nw0K)");
}
private void Test(String input, String expectedOutput) {
String result = CssPropertyNormalizer.Normalize(input);
NUnit.Framework.Assert.AreEqual(expectedOutput, result);
}
}
}

View File

@@ -0,0 +1,118 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Util {
[NUnit.Framework.Category("UnitTest")]
public class CssTypesValidationUtilsTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void TestIsAngleCorrectValues() {
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsAngleValue("10deg"));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsAngleValue("-20grad"));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsAngleValue("30.5rad"));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsAngleValue("0rad"));
}
[NUnit.Framework.Test]
public virtual void TestIsAngleNullValue() {
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsAngleValue(null));
}
[NUnit.Framework.Test]
public virtual void TestIsAngleIncorrectValues() {
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsAngleValue("deg"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsAngleValue("-20,6grad"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsAngleValue("0"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsAngleValue("10in"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsAngleValue("10px"));
}
[NUnit.Framework.Test]
public virtual void ValidateMetricValue() {
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsMetricValue("1px"));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsMetricValue("1in"));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsMetricValue("1cm"));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsMetricValue("1mm"));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsMetricValue("1pc"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsMetricValue("1em"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsMetricValue("1rem"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsMetricValue("1ex"));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsMetricValue("1pt"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsMetricValue("1inch"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsMetricValue("+1m"));
}
[NUnit.Framework.Test]
public virtual void IsNegativeValueTest() {
// Invalid values
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsNegativeValue(null));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsNegativeValue("-..23"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsNegativeValue("12 34"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsNegativeValue("12reeem"));
// Valid not negative values
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsNegativeValue(".23"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsNegativeValue("+123"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsNegativeValue("57%"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsNegativeValue("3.7em"));
// Valid negative values
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsNegativeValue("-1.7rem"));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsNegativeValue("-43.56%"));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsNegativeValue("-12"));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsNegativeValue("-0.123"));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsNegativeValue("-.34"));
}
[NUnit.Framework.Test]
public virtual void ValidateNumericValue() {
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsNumber("1"));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsNumber("12"));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsNumber("1.2"));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsNumber(".12"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsNumber("12f"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsNumber("f1.2"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsNumber(".12f"));
}
[NUnit.Framework.Test]
public virtual void TestSpacesBeforeUnitTypes() {
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsAngleValue("10 deg"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsEmValue("10 em"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsExValue("10 ex"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsRelativeValue("10 %"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsRemValue("10 rem"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsMetricValue("10 px"));
NUnit.Framework.Assert.IsFalse(CssTypesValidationUtils.IsPercentageValue("10 %"));
}
[NUnit.Framework.Test]
public virtual void TestSpacesAfterUnitTypes() {
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsAngleValue("10deg "));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsEmValue("10em "));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsExValue("10ex "));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsRelativeValue("10% "));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsRemValue("10rem "));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsMetricValue("10px "));
NUnit.Framework.Assert.IsTrue(CssTypesValidationUtils.IsPercentageValue("10% "));
}
}
}

View File

@@ -0,0 +1,395 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using TSpdf.Commons.Utils;
using TSpdf.Layout.Properties;
using TSpdf.StyledXmlParser;
using TSpdf.StyledXmlParser.Css;
using TSpdf.StyledXmlParser.Css.Pseudo;
using TSpdf.StyledXmlParser.Node;
using TSpdf.StyledXmlParser.Node.Impl.Jsoup.Node;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.StyledXmlParser.Css.Util {
[NUnit.Framework.Category("UnitTest")]
public class CssUtilsTest : ExtendedTSpdfTest {
private static float EPS = 0.0001f;
[NUnit.Framework.Test]
public virtual void ConvertFloatMaximumToPdfTest() {
float expected = float.PositiveInfinity;
float actual = CssUtils.ConvertPtsToPx(float.MaxValue);
NUnit.Framework.Assert.AreEqual(expected, actual, 0f);
}
[NUnit.Framework.Test]
public virtual void ConvertFloatMinimumToPdfTest() {
float expected = 1.4E-45f;
float actual = CssUtils.ConvertPtsToPx(float.Epsilon);
NUnit.Framework.Assert.AreEqual(expected, actual, 0f);
}
[NUnit.Framework.Test]
public virtual void ExtractShorthandPropertiesFromEmptyStringTest() {
String sourceString = "";
IList<IList<String>> expected = new List<IList<String>>();
expected.Add(new List<String>());
NUnit.Framework.Assert.AreEqual(expected, CssUtils.ExtractShorthandProperties(sourceString));
}
[NUnit.Framework.Test]
public virtual void ExtractShorthandPropertiesFromStringWithOnePropertyTest() {
String sourceString = "square inside url('sqpurple.gif')";
IList<IList<String>> expected = new List<IList<String>>();
IList<String> layer = new List<String>();
layer.Add("square");
layer.Add("inside");
layer.Add("url('sqpurple.gif')");
expected.Add(layer);
NUnit.Framework.Assert.AreEqual(expected, CssUtils.ExtractShorthandProperties(sourceString));
}
[NUnit.Framework.Test]
public virtual void ExtractShorthandPropertiesFromStringWithMultiplyPropertiesTest() {
String sourceString = "center no-repeat url('sqpurple.gif'), #eee 35% url('sqpurple.gif')";
IList<IList<String>> expected = new List<IList<String>>();
IList<String> layer = new List<String>();
layer.Add("center");
layer.Add("no-repeat");
layer.Add("url('sqpurple.gif')");
expected.Add(layer);
layer = new List<String>();
layer.Add("#eee");
layer.Add("35%");
layer.Add("url('sqpurple.gif')");
expected.Add(layer);
NUnit.Framework.Assert.AreEqual(expected, CssUtils.ExtractShorthandProperties(sourceString));
}
[NUnit.Framework.Test]
public virtual void NormalConvertPtsToPxTest() {
float[] input = new float[] { -1f, 0f, 1f };
float[] expected = new float[] { -1.3333334f, 0f, 1.3333334f };
for (int i = 0; i < input.Length; i++) {
float actual = CssUtils.ConvertPtsToPx(input[i]);
NUnit.Framework.Assert.AreEqual(expected[i], actual, 0f);
}
}
[NUnit.Framework.Test]
public virtual void NormalizeProperty() {
NUnit.Framework.Assert.AreEqual("part1 part2", CssUtils.NormalizeCssProperty(" part1 part2 "));
NUnit.Framework.Assert.AreEqual("\" the next quote is ESCAPED \\\\\\\" still IN string \"", CssUtils.NormalizeCssProperty
("\" the next quote is ESCAPED \\\\\\\" still IN string \""));
NUnit.Framework.Assert.AreEqual("\" the next quote is NOT ESCAPED \\\\\" not in the string", CssUtils.NormalizeCssProperty
("\" the next quote is NOT ESCAPED \\\\\" NOT in THE string"));
NUnit.Framework.Assert.AreEqual("\" You CAN put 'Single Quotes' in double quotes WITHOUT escaping\"", CssUtils
.NormalizeCssProperty("\" You CAN put 'Single Quotes' in double quotes WITHOUT escaping\""));
NUnit.Framework.Assert.AreEqual("' You CAN put \"DOUBLE Quotes\" in double quotes WITHOUT escaping'", CssUtils
.NormalizeCssProperty("' You CAN put \"DOUBLE Quotes\" in double quotes WITHOUT escaping'"));
NUnit.Framework.Assert.AreEqual("\" ( BLA \" attr(href)\" BLA ) \"", CssUtils.NormalizeCssProperty("\" ( BLA \" AttR( Href )\" BLA ) \""
));
NUnit.Framework.Assert.AreEqual("\" ( \"attr(href) \" ) \"", CssUtils.NormalizeCssProperty("\" ( \"aTTr( hREf ) \" ) \""
));
NUnit.Framework.Assert.AreEqual("rgba(255,255,255,0.2)", CssUtils.NormalizeCssProperty("rgba( 255, 255 , 255 ,0.2 )"
));
}
[NUnit.Framework.Test]
public virtual void NormalizeUrlTest() {
NUnit.Framework.Assert.AreEqual("url(data:application/font-woff;base64,2CBPCRXmgywtV1t4oWwjBju0kqkvfhPs0cYdMgFtDSY5uL7MIGT5wiGs078HrvBHekp0Yf=)"
, CssUtils.NormalizeCssProperty("url(data:application/font-woff;base64,2CBPCRXmgywtV1t4oWwjBju0kqkvfhPs0cYdMgFtDSY5uL7MIGT5wiGs078HrvBHekp0Yf=)"
));
NUnit.Framework.Assert.AreEqual("url(\"quoted Url\")", CssUtils.NormalizeCssProperty(" url( \"quoted Url\")"
));
NUnit.Framework.Assert.AreEqual("url('quoted Url')", CssUtils.NormalizeCssProperty(" url( 'quoted Url')"
));
NUnit.Framework.Assert.AreEqual("url(haveEscapedEndBracket\\))", CssUtils.NormalizeCssProperty("url( haveEscapedEndBracket\\) )"
));
}
[NUnit.Framework.Test]
public virtual void ParseUnicodeRangeTest() {
NUnit.Framework.Assert.AreEqual("[(0; 1048575)]", CssUtils.ParseUnicodeRange("U+?????").ToString());
NUnit.Framework.Assert.AreEqual("[(38; 38)]", CssUtils.ParseUnicodeRange("U+26").ToString());
NUnit.Framework.Assert.AreEqual("[(0; 127)]", CssUtils.ParseUnicodeRange(" U+0-7F").ToString());
NUnit.Framework.Assert.AreEqual("[(37; 255)]", CssUtils.ParseUnicodeRange("U+0025-00FF").ToString());
NUnit.Framework.Assert.AreEqual("[(1024; 1279)]", CssUtils.ParseUnicodeRange("U+4??").ToString());
NUnit.Framework.Assert.AreEqual("[(262224; 327519)]", CssUtils.ParseUnicodeRange("U+4??5?").ToString());
NUnit.Framework.Assert.AreEqual("[(37; 255), (1024; 1279)]", CssUtils.ParseUnicodeRange("U+0025-00FF, U+4??"
).ToString());
NUnit.Framework.Assert.IsNull(CssUtils.ParseUnicodeRange("U+??????"));
// more than 5 question marks are not allowed
NUnit.Framework.Assert.IsNull(CssUtils.ParseUnicodeRange("UU+7-10"));
// wrong syntax
NUnit.Framework.Assert.IsNull(CssUtils.ParseUnicodeRange("U+7?-9?"));
// wrong syntax
NUnit.Framework.Assert.IsNull(CssUtils.ParseUnicodeRange("U+7-"));
}
// wrong syntax
[NUnit.Framework.Test]
public virtual void ElementNodeIsStyleSheetLink() {
TSpdf.StyledXmlParser.Jsoup.Nodes.Element element = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element(TSpdf.StyledXmlParser.Jsoup.Parser.Tag
.ValueOf("link"), "");
element.Attr(CommonAttributeConstants.REL, CommonAttributeConstants.STYLESHEET);
JsoupElementNode elementNode = new JsoupElementNode(element);
NUnit.Framework.Assert.IsTrue(CssUtils.IsStyleSheetLink(elementNode));
}
[NUnit.Framework.Test]
public virtual void ElementNodeIsNotLink() {
TSpdf.StyledXmlParser.Jsoup.Nodes.Element element = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element(TSpdf.StyledXmlParser.Jsoup.Parser.Tag
.ValueOf("p"), "");
element.Attr(CommonAttributeConstants.REL, CommonAttributeConstants.STYLESHEET);
JsoupElementNode elementNode = new JsoupElementNode(element);
NUnit.Framework.Assert.IsFalse(CssUtils.IsStyleSheetLink(elementNode));
}
[NUnit.Framework.Test]
public virtual void ElementNodeAttributeIsNotStylesheet() {
TSpdf.StyledXmlParser.Jsoup.Nodes.Element element = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element(TSpdf.StyledXmlParser.Jsoup.Parser.Tag
.ValueOf("link"), "");
element.Attr(CommonAttributeConstants.REL, "");
JsoupElementNode elementNode = new JsoupElementNode(element);
NUnit.Framework.Assert.IsFalse(CssUtils.IsStyleSheetLink(elementNode));
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.INCORRECT_CHARACTER_SEQUENCE)]
public virtual void SplitStringWithCommaTest() {
NUnit.Framework.Assert.AreEqual(new List<String>(), CssUtils.SplitStringWithComma(null));
NUnit.Framework.Assert.AreEqual(JavaUtil.ArraysAsList("value1", "value2", "value3"), CssUtils.SplitStringWithComma
("value1,value2,value3"));
NUnit.Framework.Assert.AreEqual(JavaUtil.ArraysAsList("value1", " value2", " value3"), CssUtils.SplitStringWithComma
("value1, value2, value3"));
NUnit.Framework.Assert.AreEqual(JavaUtil.ArraysAsList("value1", "(value,with,comma)", "value3"), CssUtils.
SplitStringWithComma("value1,(value,with,comma),value3"));
NUnit.Framework.Assert.AreEqual(JavaUtil.ArraysAsList("value1", "(val(ue,with,comma),value3"), CssUtils.SplitStringWithComma
("value1,(val(ue,with,comma),value3"));
NUnit.Framework.Assert.AreEqual(JavaUtil.ArraysAsList("value1", "(value,with)", "comma)", "value3"), CssUtils
.SplitStringWithComma("value1,(value,with),comma),value3"));
NUnit.Framework.Assert.AreEqual(JavaUtil.ArraysAsList("value1", "( v2,v3)", "(v4, v5)", "value3"), CssUtils
.SplitStringWithComma("value1,( v2,v3),(v4, v5),value3"));
NUnit.Framework.Assert.AreEqual(JavaUtil.ArraysAsList("v.al*ue1\"", "( v2,v3)", "\"(v4,v5;);", "value3"),
CssUtils.SplitStringWithComma("v.al*ue1\",( v2,v3),\"(v4,v5;);,value3"));
}
[NUnit.Framework.Test]
public virtual void SplitStringTest() {
NUnit.Framework.Assert.AreEqual(new List<String>(), CssUtils.SplitString(null, ','));
NUnit.Framework.Assert.AreEqual(JavaUtil.ArraysAsList("value1", "(value,with,comma)", "value3"), CssUtils.
SplitString("value1,(value,with,comma),value3", ',', new EscapeGroup('(', ')')));
NUnit.Framework.Assert.AreEqual(JavaUtil.ArraysAsList("value1 ", " (val(ue,with,comma),value3"), CssUtils.
SplitString("value1 , (val(ue,with,comma),value3", ',', new EscapeGroup('(', ')')));
NUnit.Framework.Assert.AreEqual(JavaUtil.ArraysAsList("some text", " (some", " text in", " brackets)", " \"some, text, in quotes,\""
), CssUtils.SplitString("some text, (some, text in, brackets), \"some, text, in quotes,\"", ',', new EscapeGroup
('\"')));
NUnit.Framework.Assert.AreEqual(JavaUtil.ArraysAsList("some text", " (some. text in. brackets)", " \"some. text. in quotes.\""
), CssUtils.SplitString("some text. (some. text in. brackets). \"some. text. in quotes.\"", '.', new EscapeGroup
('\"'), new EscapeGroup('(', ')')));
NUnit.Framework.Assert.AreEqual(JavaUtil.ArraysAsList("value1", "(value", "with", "comma)", "value3"), CssUtils
.SplitString("value1,(value,with,comma),value3", ','));
NUnit.Framework.Assert.AreEqual(JavaUtil.ArraysAsList("value1", "value", "with", "comma", "value3"), CssUtils
.SplitString("value1,value,with,comma,value3", ',', new EscapeGroup(',')));
}
[NUnit.Framework.Test]
public virtual void ParseBlendModeTest() {
NUnit.Framework.Assert.AreEqual(BlendMode.NORMAL, CssUtils.ParseBlendMode(null));
NUnit.Framework.Assert.AreEqual(BlendMode.NORMAL, CssUtils.ParseBlendMode(CommonCssConstants.NORMAL));
NUnit.Framework.Assert.AreEqual(BlendMode.MULTIPLY, CssUtils.ParseBlendMode(CommonCssConstants.MULTIPLY));
NUnit.Framework.Assert.AreEqual(BlendMode.SCREEN, CssUtils.ParseBlendMode(CommonCssConstants.SCREEN));
NUnit.Framework.Assert.AreEqual(BlendMode.OVERLAY, CssUtils.ParseBlendMode(CommonCssConstants.OVERLAY));
NUnit.Framework.Assert.AreEqual(BlendMode.DARKEN, CssUtils.ParseBlendMode(CommonCssConstants.DARKEN));
NUnit.Framework.Assert.AreEqual(BlendMode.LIGHTEN, CssUtils.ParseBlendMode(CommonCssConstants.LIGHTEN));
NUnit.Framework.Assert.AreEqual(BlendMode.COLOR_DODGE, CssUtils.ParseBlendMode(CommonCssConstants.COLOR_DODGE
));
NUnit.Framework.Assert.AreEqual(BlendMode.COLOR_BURN, CssUtils.ParseBlendMode(CommonCssConstants.COLOR_BURN
));
NUnit.Framework.Assert.AreEqual(BlendMode.HARD_LIGHT, CssUtils.ParseBlendMode(CommonCssConstants.HARD_LIGHT
));
NUnit.Framework.Assert.AreEqual(BlendMode.SOFT_LIGHT, CssUtils.ParseBlendMode(CommonCssConstants.SOFT_LIGHT
));
NUnit.Framework.Assert.AreEqual(BlendMode.DIFFERENCE, CssUtils.ParseBlendMode(CommonCssConstants.DIFFERENCE
));
NUnit.Framework.Assert.AreEqual(BlendMode.EXCLUSION, CssUtils.ParseBlendMode(CommonCssConstants.EXCLUSION)
);
NUnit.Framework.Assert.AreEqual(BlendMode.HUE, CssUtils.ParseBlendMode(CommonCssConstants.HUE));
NUnit.Framework.Assert.AreEqual(BlendMode.SATURATION, CssUtils.ParseBlendMode(CommonCssConstants.SATURATION
));
NUnit.Framework.Assert.AreEqual(BlendMode.COLOR, CssUtils.ParseBlendMode(CommonCssConstants.COLOR));
NUnit.Framework.Assert.AreEqual(BlendMode.LUMINOSITY, CssUtils.ParseBlendMode(CommonCssConstants.LUMINOSITY
));
NUnit.Framework.Assert.AreEqual(BlendMode.NORMAL, CssUtils.ParseBlendMode("invalid"));
NUnit.Framework.Assert.AreEqual(BlendMode.NORMAL, CssUtils.ParseBlendMode("SCREEN"));
}
[NUnit.Framework.Test]
public virtual void TestWrongAttrTest01() {
String strToParse = "attr((href))";
String result = CssUtils.ExtractAttributeValue(strToParse, null);
NUnit.Framework.Assert.IsNull(result);
}
[NUnit.Framework.Test]
public virtual void TestWrongAttrTest02() {
String strToParse = "attr('href')";
String result = CssUtils.ExtractAttributeValue(strToParse, null);
NUnit.Framework.Assert.IsNull(result);
}
[NUnit.Framework.Test]
public virtual void TestWrongAttrTest03() {
String strToParse = "attrrname)";
String result = CssUtils.ExtractAttributeValue(strToParse, null);
NUnit.Framework.Assert.IsNull(result);
}
[NUnit.Framework.Test]
public virtual void TestExtractingAttrTest01() {
IElementNode iNode = new CssPseudoElementNode(null, "url");
String strToParse = "attr(url)";
String result = CssUtils.ExtractAttributeValue(strToParse, iNode);
NUnit.Framework.Assert.AreEqual("", result);
}
[NUnit.Framework.Test]
public virtual void TestExtractingAttrTest02() {
IElementNode iNode = new CssPseudoElementNode(null, "test");
String strToParse = "attr(url url)";
String result = CssUtils.ExtractAttributeValue(strToParse, iNode);
NUnit.Framework.Assert.IsNull(result);
}
[NUnit.Framework.Test]
public virtual void TestExtractingAttrTest03() {
IElementNode iNode = new CssPseudoElementNode(null, "test");
String strToParse = "attr(url url,#one)";
String result = CssUtils.ExtractAttributeValue(strToParse, iNode);
NUnit.Framework.Assert.AreEqual("#one", result);
}
[NUnit.Framework.Test]
public virtual void TestExtractingAttrTest04() {
IElementNode iNode = new CssPseudoElementNode(null, "test");
String strToParse = "attr()";
String result = CssUtils.ExtractAttributeValue(strToParse, iNode);
NUnit.Framework.Assert.IsNull(result);
}
[NUnit.Framework.Test]
public virtual void TestExtractingAttrTest05() {
IElementNode iNode = new CssPseudoElementNode(null, "test");
String strToParse = "attr('\')";
String result = CssUtils.ExtractAttributeValue(strToParse, iNode);
NUnit.Framework.Assert.IsNull(result);
}
[NUnit.Framework.Test]
public virtual void TestExtractingAttrTest06() {
IElementNode iNode = new CssPseudoElementNode(null, "test");
String strToParse = "attr(str,\"hey\")";
String result = CssUtils.ExtractAttributeValue(strToParse, iNode);
NUnit.Framework.Assert.AreEqual("hey", result);
}
[NUnit.Framework.Test]
public virtual void TestExtractingAttrTest07() {
IElementNode iNode = new CssPseudoElementNode(null, "test");
String strToParse = "attr(str string)";
String result = CssUtils.ExtractAttributeValue(strToParse, iNode);
NUnit.Framework.Assert.AreEqual("", result);
}
[NUnit.Framework.Test]
public virtual void TestExtractingAttrTest08() {
IElementNode iNode = new CssPseudoElementNode(null, "test");
String strToParse = "attr(str string,\"value\")";
String result = CssUtils.ExtractAttributeValue(strToParse, iNode);
NUnit.Framework.Assert.AreEqual("value", result);
}
[NUnit.Framework.Test]
public virtual void TestExtractingAttrTest09() {
IElementNode iNode = new CssPseudoElementNode(null, "test");
String strToParse = "attr(str string,\"val,ue\")";
String result = CssUtils.ExtractAttributeValue(strToParse, iNode);
NUnit.Framework.Assert.AreEqual("val,ue", result);
}
[NUnit.Framework.Test]
public virtual void TestExtractingAttrTest10() {
IElementNode iNode = new CssPseudoElementNode(null, "test");
String strToParse = "attr(str string,'val,ue')";
String result = CssUtils.ExtractAttributeValue(strToParse, iNode);
NUnit.Framework.Assert.AreEqual("val,ue", result);
}
[NUnit.Framework.Test]
public virtual void TestExtractingAttrTest11() {
IElementNode iNode = new CssPseudoElementNode(null, "test");
String strToParse = "attr(name, \"value\", \"value\", \"value\")";
String result = CssUtils.ExtractAttributeValue(strToParse, iNode);
NUnit.Framework.Assert.IsNull(result);
}
[NUnit.Framework.Test]
public virtual void WrongAttributeTypeTest() {
IElementNode iNode = new CssPseudoElementNode(null, "test");
String strToParse = "attr(str mem)";
String result = CssUtils.ExtractAttributeValue(strToParse, iNode);
NUnit.Framework.Assert.IsNull(result);
}
[NUnit.Framework.Test]
public virtual void WrongParamsInAttrFunctionTest() {
IElementNode iNode = new CssPseudoElementNode(null, "test");
String strToParse = "attr(str mem lol)";
String result = CssUtils.ExtractAttributeValue(strToParse, iNode);
NUnit.Framework.Assert.IsNull(result);
}
}
}

View File

@@ -0,0 +1,63 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.StyledXmlParser.Css.Validate.Impl.Datatype;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Validate {
[NUnit.Framework.Category("UnitTest")]
public class ArrayDataTypeValidatorTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void NullValueTest() {
ICssDataTypeValidator validator = new ArrayDataTypeValidator(new ArrayDataTypeValidatorTest.TestValidator(
));
NUnit.Framework.Assert.IsFalse(validator.IsValid(null));
}
[NUnit.Framework.Test]
public virtual void NormalValueTest() {
ICssDataTypeValidator validator = new ArrayDataTypeValidator(new ArrayDataTypeValidatorTest.TestValidator(
));
NUnit.Framework.Assert.IsTrue(validator.IsValid(""));
NUnit.Framework.Assert.IsTrue(validator.IsValid("test"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("test is, test, ttest"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("(te,st)"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("(te,st), test,"));
}
[NUnit.Framework.Test]
public virtual void InvalidValuesTest() {
ICssDataTypeValidator validator = new ArrayDataTypeValidator(new ArrayDataTypeValidatorTest.TestValidator(
));
NUnit.Framework.Assert.IsFalse(validator.IsValid("norma"));
NUnit.Framework.Assert.IsFalse(validator.IsValid("te,st"));
NUnit.Framework.Assert.IsFalse(validator.IsValid("(te,st),, test,"));
}
private class TestValidator : ICssDataTypeValidator {
public virtual bool IsValid(String objectString) {
return objectString.Contains("test") || objectString.Contains("te,st");
}
}
}
}

View File

@@ -0,0 +1,161 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using TSpdf.StyledXmlParser.Css.Validate.Impl.Datatype;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Validate {
[NUnit.Framework.Category("UnitTest")]
public class CssBackgroundValidatorTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void NullValueTest() {
ICssDataTypeValidator validator = new CssBackgroundValidator("any property");
NUnit.Framework.Assert.IsFalse(validator.IsValid(null));
}
[NUnit.Framework.Test]
public virtual void UndefinedValueTest() {
ICssDataTypeValidator validator = new CssBackgroundValidator("undefined");
NUnit.Framework.Assert.IsFalse(validator.IsValid("ja"));
}
[NUnit.Framework.Test]
public virtual void InitialInheritUnsetValueTest() {
ICssDataTypeValidator validator = new CssBackgroundValidator("any property");
NUnit.Framework.Assert.IsTrue(validator.IsValid("initial"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("inherit"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("unset"));
}
[NUnit.Framework.Test]
public virtual void EmptyValueTest() {
ICssDataTypeValidator validator = new CssBackgroundValidator("any property");
NUnit.Framework.Assert.IsFalse(validator.IsValid(""));
}
[NUnit.Framework.Test]
public virtual void PropertyValueCorrespondsPropertyTypeTest() {
ICssDataTypeValidator validator = new CssBackgroundValidator("background-repeat");
NUnit.Framework.Assert.IsTrue(validator.IsValid("repeat-x"));
NUnit.Framework.Assert.IsFalse(validator.IsValid("cover"));
validator = new CssBackgroundValidator("background-image");
NUnit.Framework.Assert.IsTrue(validator.IsValid("url(something.png)"));
NUnit.Framework.Assert.IsFalse(validator.IsValid("5px"));
validator = new CssBackgroundValidator("background-attachment");
NUnit.Framework.Assert.IsTrue(validator.IsValid("fixed"));
NUnit.Framework.Assert.IsFalse(validator.IsValid("5px"));
}
[NUnit.Framework.Test]
public virtual void PropertyValueWithMultiTypesCorrespondsPropertyTypeTest() {
ICssDataTypeValidator positionValidator = new CssBackgroundValidator("background-position-x");
ICssDataTypeValidator sizeValidator = new CssBackgroundValidator("background-size");
NUnit.Framework.Assert.IsTrue(positionValidator.IsValid("5px"));
NUnit.Framework.Assert.IsTrue(sizeValidator.IsValid("5px"));
NUnit.Framework.Assert.IsTrue(positionValidator.IsValid("5%"));
NUnit.Framework.Assert.IsTrue(sizeValidator.IsValid("5%"));
NUnit.Framework.Assert.IsTrue(positionValidator.IsValid("left"));
NUnit.Framework.Assert.IsFalse(sizeValidator.IsValid("left"));
NUnit.Framework.Assert.IsFalse(positionValidator.IsValid("contain"));
NUnit.Framework.Assert.IsTrue(sizeValidator.IsValid("contain"));
ICssDataTypeValidator originValidator = new CssBackgroundValidator("background-origin");
ICssDataTypeValidator clipValidator = new CssBackgroundValidator("background-clip");
NUnit.Framework.Assert.IsTrue(originValidator.IsValid("border-box"));
NUnit.Framework.Assert.IsTrue(clipValidator.IsValid("border-box"));
NUnit.Framework.Assert.IsTrue(originValidator.IsValid("padding-box"));
NUnit.Framework.Assert.IsTrue(clipValidator.IsValid("padding-box"));
NUnit.Framework.Assert.IsTrue(originValidator.IsValid("content-box"));
NUnit.Framework.Assert.IsTrue(clipValidator.IsValid("content-box"));
}
[NUnit.Framework.Test]
public virtual void CheckMultiValuePositionXYTest() {
ICssDataTypeValidator positionValidator = new CssBackgroundValidator("background-position-x");
NUnit.Framework.Assert.IsFalse(positionValidator.IsValid("50px left"));
NUnit.Framework.Assert.IsFalse(positionValidator.IsValid("50px bottom"));
NUnit.Framework.Assert.IsFalse(positionValidator.IsValid("center 50pt"));
NUnit.Framework.Assert.IsFalse(positionValidator.IsValid("50px 50pt"));
NUnit.Framework.Assert.IsFalse(positionValidator.IsValid("left right"));
NUnit.Framework.Assert.IsFalse(positionValidator.IsValid("bottom"));
NUnit.Framework.Assert.IsTrue(positionValidator.IsValid("left 10pt"));
NUnit.Framework.Assert.IsTrue(positionValidator.IsValid("center"));
positionValidator = new CssBackgroundValidator("background-position-y");
NUnit.Framework.Assert.IsTrue(positionValidator.IsValid("bottom 10pt"));
NUnit.Framework.Assert.IsTrue(positionValidator.IsValid("10pt"));
NUnit.Framework.Assert.IsFalse(positionValidator.IsValid("right"));
ICssDataTypeValidator notPositionValidator = new CssBackgroundValidator("background-size");
NUnit.Framework.Assert.IsTrue(notPositionValidator.IsValid("10px 15pt"));
}
[NUnit.Framework.Test]
public virtual void MultiValuesAllowedForThisTypeTest() {
ICssDataTypeValidator validator = new CssBackgroundValidator("background-size");
NUnit.Framework.Assert.IsTrue(validator.IsValid("5px 10%"));
validator = new CssBackgroundValidator("background-position-x");
NUnit.Framework.Assert.IsTrue(validator.IsValid("left 10px"));
NUnit.Framework.Assert.IsFalse(validator.IsValid("5px 10%"));
NUnit.Framework.Assert.IsFalse(validator.IsValid("left left left left left"));
validator = new CssBackgroundValidator("background-position-y");
NUnit.Framework.Assert.IsTrue(validator.IsValid("bottom 10px"));
NUnit.Framework.Assert.IsFalse(validator.IsValid("5px 10%"));
NUnit.Framework.Assert.IsFalse(validator.IsValid("bottom bottom bottom bottom"));
validator = new CssBackgroundValidator("background-repeat");
NUnit.Framework.Assert.IsTrue(validator.IsValid("repeat round"));
NUnit.Framework.Assert.IsFalse(validator.IsValid("repeat-x repeat"));
validator = new CssBackgroundValidator("background-image");
NUnit.Framework.Assert.IsFalse(validator.IsValid("url(something.png) url(something2.png)"));
validator = new CssBackgroundValidator("background-clip");
NUnit.Framework.Assert.IsFalse(validator.IsValid("content-box padding-box"));
validator = new CssBackgroundValidator("background-origin");
NUnit.Framework.Assert.IsFalse(validator.IsValid("content-box padding-box"));
validator = new CssBackgroundValidator("background-attachment");
NUnit.Framework.Assert.IsFalse(validator.IsValid("fixed scroll"));
}
[NUnit.Framework.Test]
public virtual void MultiValuesAllowedForThisValueTest() {
ICssDataTypeValidator validator = new CssBackgroundValidator("background-repeat");
NUnit.Framework.Assert.IsTrue(validator.IsValid("repeat no-repeat"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("round space"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("no-repeat space"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("round repeat"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("space repeat"));
NUnit.Framework.Assert.IsFalse(validator.IsValid("repeat-x repeat"));
NUnit.Framework.Assert.IsFalse(validator.IsValid("repeat-y no-repeat"));
NUnit.Framework.Assert.IsFalse(validator.IsValid("round repeat-x"));
NUnit.Framework.Assert.IsFalse(validator.IsValid("space repeat-x"));
validator = new CssBackgroundValidator("background-size");
NUnit.Framework.Assert.IsTrue(validator.IsValid("5px 5px"));
NUnit.Framework.Assert.IsFalse(validator.IsValid("contain 5px"));
NUnit.Framework.Assert.IsFalse(validator.IsValid("cover 10%"));
}
[NUnit.Framework.Test]
public virtual void SeveralValuesTest() {
ICssDataTypeValidator validator = new CssBackgroundValidator("background-image");
NUnit.Framework.Assert.IsTrue(validator.IsValid("url(img.png),url(img2.png),url(img3.jpg)"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("url(img.png),none,url(img3.jpg)"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("linear-gradient(red, red, red),url(img2.png),url(img3.jpg)"
));
}
}
}

View File

@@ -0,0 +1,64 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using TSpdf.StyledXmlParser.Css.Validate.Impl.Datatype;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Validate {
[NUnit.Framework.Category("UnitTest")]
public class CssBlendModeValidatorTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void NullValueTest() {
ICssDataTypeValidator validator = new CssBlendModeValidator();
NUnit.Framework.Assert.IsFalse(validator.IsValid(null));
}
[NUnit.Framework.Test]
public virtual void NormalValueTest() {
ICssDataTypeValidator validator = new CssBlendModeValidator();
NUnit.Framework.Assert.IsTrue(validator.IsValid("normal"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("multiply"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("screen"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("overlay"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("darken"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("lighten"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("color-dodge"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("color-burn"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("hard-light"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("soft-light"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("difference"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("exclusion"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("hue"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("saturation"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("color"));
NUnit.Framework.Assert.IsTrue(validator.IsValid("luminosity"));
}
[NUnit.Framework.Test]
public virtual void InvalidValuesTest() {
ICssDataTypeValidator validator = new CssBlendModeValidator();
NUnit.Framework.Assert.IsFalse(validator.IsValid(""));
NUnit.Framework.Assert.IsFalse(validator.IsValid("norma"));
NUnit.Framework.Assert.IsFalse(validator.IsValid("NORMAL"));
}
}
}

View File

@@ -0,0 +1,403 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.StyledXmlParser.Css;
using TSpdf.StyledXmlParser.Css.Validate.Impl;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Validate {
[NUnit.Framework.Category("UnitTest")]
public class CssDeclarationValidationMasterTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void FontSizeEnumValidationTest() {
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.FONT_SIZE, "larger")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.FONT_SIZE, "smaller")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.FONT_SIZE, "xx-small")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.FONT_SIZE, "x-small")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.FONT_SIZE, "small")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.FONT_SIZE, "medium")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.FONT_SIZE, "large")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.FONT_SIZE, "x-large")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.FONT_SIZE, "xx-large")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.FONT_SIZE, "smaler")));
}
[NUnit.Framework.Test]
public virtual void FontSizeNumericValidationTest() {
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.FONT_SIZE, "5px")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.FONT_SIZE, "5jaja")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.FONT_SIZE, "normal")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.FONT_SIZE, "5%")));
}
[NUnit.Framework.Test]
public virtual void WordSpacingValidationTest() {
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.WORD_SPACING, "5px")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.WORD_SPACING, "5jaja")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.WORD_SPACING, "normal")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.WORD_SPACING, "5%")));
}
[NUnit.Framework.Test]
public virtual void LetterSpacingValidationTest() {
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.LETTER_SPACING, "5px")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.LETTER_SPACING, "5jaja")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.LETTER_SPACING, "normal")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.LETTER_SPACING, "5%")));
}
[NUnit.Framework.Test]
public virtual void TextIndentValidationTest() {
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.TEXT_INDENT, "5px")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.TEXT_INDENT, "5jaja")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.TEXT_INDENT, "normal")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.TEXT_INDENT, "5%")));
}
[NUnit.Framework.Test]
public virtual void LineHeightValidationTest() {
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.LINE_HEIGHT, "5px")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.LINE_HEIGHT, "5jaja")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.LINE_HEIGHT, "normal")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.LINE_HEIGHT, "5%")));
}
[NUnit.Framework.Test]
public virtual void BackgroundRepeatValidationTest() {
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_REPEAT, "initial")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_REPEAT, "no-repeat")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_REPEAT, "repeat no-repeat")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_REPEAT, "space")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_REPEAT, "round")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_REPEAT, "space repeat")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_REPEAT, "no-repeat round")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_REPEAT, "no-repeat,repeat")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_REPEAT, "no-repeat repeat,repeat")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_REPEAT, "repeat-x, repeat no-repeat")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_REPEAT, "5px")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_REPEAT, "ja")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_REPEAT, "repeat-x repeat")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_REPEAT, "initial repeat")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_REPEAT, "repeat, repeat-x repeat")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_REPEAT, "ja, repeat")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_REPEAT, "initial, repeat")));
}
[NUnit.Framework.Test]
public virtual void BackgroundPositionValidationTest() {
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_POSITION_X, "initial")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_POSITION_Y, "-0")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_POSITION_Y, "5px")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_POSITION_X, "5em")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_POSITION_Y, "5px, 5%, bottom")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_POSITION_X, "left 5%, right")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_POSITION_X, "5")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_POSITION_Y, "ja")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_POSITION_X, "initial 5px")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_POSITION_Y, "ja, 5px")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_POSITION_X, "initial, 5px")));
}
[NUnit.Framework.Test]
public virtual void BackgroundSizeTest() {
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "initial")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "0")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "10px")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "10%")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "10% 10px")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "10px 10em")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "auto")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "auto 10px")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "10px auto")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "cover")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "contain")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "5px, 10%, auto")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "5px 10%, 20em")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "ja")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "10")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "cover 10px")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "initial 10px")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "10px contain")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "ja, 5px")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "5px, ja")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_SIZE, "initial, 10px")));
}
[NUnit.Framework.Test]
public virtual void BackgroundOriginTest() {
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_ORIGIN, "initial")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_ORIGIN, "border-box")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_ORIGIN, "padding-box")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_ORIGIN, "content-box")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_ORIGIN, "content-box, border-box")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_ORIGIN, "5px")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_ORIGIN, "ja")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_ORIGIN, "border-box border-box")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_ORIGIN, "content-box padding-box")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_ORIGIN, "ja, padding-box")));
}
[NUnit.Framework.Test]
public virtual void BackgroundClipTest() {
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_CLIP, "initial")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_CLIP, "border-box")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_CLIP, "padding-box")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_CLIP, "content-box")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_CLIP, "content-box, border-box")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_CLIP, "5px")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_CLIP, "ja")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_CLIP, "border-box border-box")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_CLIP, "content-box padding-box")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_CLIP, "ja, padding-box")));
}
[NUnit.Framework.Test]
public virtual void BackgroundImageTest() {
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_IMAGE, "initial")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_IMAGE, "url(rock_texture.jpg)")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_IMAGE, "linear-gradient(red,green,blue)")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_IMAGE, "url()")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_IMAGE, "none")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_IMAGE, "url(img.jpg),url(img2.jpg)")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_IMAGE, "none,url(img2.jpg)")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_IMAGE, "linear-gradient(red,green,blue),url(img2.jpg)")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_IMAGE, "ja")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_IMAGE, "5px")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_IMAGE, "url(url(rock_texture.jpg)")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_IMAGE, "true-linear-gradient(red,green,blue)")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_IMAGE, "url(img.jpg) url(img2.jpg)")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.BACKGROUND_IMAGE, "initial,url(img.jpg)")));
}
[NUnit.Framework.Test]
public virtual void OverflowWrapTest() {
String[] overflowWrapOrWordWrap = new String[] { CommonCssConstants.OVERFLOW_WRAP, CommonCssConstants.WORDWRAP
};
foreach (String overflowWrap in overflowWrapOrWordWrap) {
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(overflowWrap
, "normal")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(overflowWrap
, "anywhere")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(overflowWrap
, "break-word")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(overflowWrap
, "inherit")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(overflowWrap
, "unset")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(overflowWrap
, "initial")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(overflowWrap
, "auto")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(overflowWrap
, "norm")));
}
}
[NUnit.Framework.Test]
public virtual void WordWrapTest() {
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.WORD_BREAK, "normal")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.WORD_BREAK, "break-all")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.WORD_BREAK, "keep-all")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.WORD_BREAK, "break-word")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.WORD_BREAK, "inherit")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.WORD_BREAK, "unset")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.WORD_BREAK, "initial")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.WORD_BREAK, "auto")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.WORD_BREAK, "norm")));
}
[NUnit.Framework.Test]
public virtual void JustifyContentTest() {
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.JUSTIFY_CONTENT, "inherit")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.JUSTIFY_CONTENT, "right")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.JUSTIFY_CONTENT, "normal")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.JUSTIFY_CONTENT, "space-between")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.JUSTIFY_CONTENT, "self-end")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.JUSTIFY_CONTENT, "unsafe self-end")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.JUSTIFY_CONTENT, "stretch")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.JUSTIFY_CONTENT, "space-evenly")));
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.JUSTIFY_CONTENT, "flex-start")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.JUSTIFY_CONTENT, "baseline")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.JUSTIFY_CONTENT, "safe right")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.JUSTIFY_CONTENT, "unsafe normal")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.JUSTIFY_CONTENT, "unsafe space-between")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.JUSTIFY_CONTENT, "self-center")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.JUSTIFY_CONTENT, "self-end unsafe")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.JUSTIFY_CONTENT, "safe stretch")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.JUSTIFY_CONTENT, "space_evenly")));
NUnit.Framework.Assert.IsFalse(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.JUSTIFY_CONTENT, "flex-start left")));
}
[NUnit.Framework.Test]
public virtual void ChangeValidatorTest() {
try {
CssDeclarationValidationMaster.SetValidator(new CssDeviceCmykAwareValidator());
NUnit.Framework.Assert.IsTrue(CssDeclarationValidationMaster.CheckDeclaration(new CssDeclaration(CommonCssConstants
.COLOR, "device-cmyk(0, 100%, 70%, 0)")));
}
finally {
CssDeclarationValidationMaster.SetValidator(new CssDefaultValidator());
}
}
}
}

View File

@@ -0,0 +1,133 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using TSpdf.StyledXmlParser.Css.Validate.Impl.Datatype;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Validate {
[NUnit.Framework.Category("UnitTest")]
public class CssLengthValueValidatorTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void ZeroValueTest() {
ICssDataTypeValidator validator1 = new CssLengthValueValidator(false);
NUnit.Framework.Assert.IsTrue(validator1.IsValid("0"));
NUnit.Framework.Assert.IsTrue(validator1.IsValid("0px"));
NUnit.Framework.Assert.IsTrue(validator1.IsValid("-0px"));
ICssDataTypeValidator validator2 = new CssLengthValueValidator(true);
NUnit.Framework.Assert.IsTrue(validator2.IsValid("0"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("0px"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("-0"));
}
[NUnit.Framework.Test]
public virtual void NullValueTest() {
ICssDataTypeValidator validator1 = new CssLengthValueValidator(false);
NUnit.Framework.Assert.IsFalse(validator1.IsValid(null));
ICssDataTypeValidator validator2 = new CssLengthValueValidator(true);
NUnit.Framework.Assert.IsFalse(validator2.IsValid(null));
}
[NUnit.Framework.Test]
public virtual void InitialInheritUnsetValuesTest() {
ICssDataTypeValidator validator1 = new CssLengthValueValidator(false);
NUnit.Framework.Assert.IsTrue(validator1.IsValid("initial"));
NUnit.Framework.Assert.IsTrue(validator1.IsValid("inherit"));
NUnit.Framework.Assert.IsTrue(validator1.IsValid("unset"));
ICssDataTypeValidator validator2 = new CssLengthValueValidator(true);
NUnit.Framework.Assert.IsTrue(validator2.IsValid("initial"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("inherit"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("unset"));
}
[NUnit.Framework.Test]
public virtual void NormalValueTest() {
ICssDataTypeValidator validator1 = new CssLengthValueValidator(false);
NUnit.Framework.Assert.IsFalse(validator1.IsValid("normal"));
ICssDataTypeValidator validator2 = new CssLengthValueValidator(true);
NUnit.Framework.Assert.IsFalse(validator2.IsValid("normal"));
}
[NUnit.Framework.Test]
public virtual void InvalidValuesTest() {
ICssDataTypeValidator validator1 = new CssLengthValueValidator(false);
NUnit.Framework.Assert.IsFalse(validator1.IsValid(""));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("dja"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("5pixels"));
ICssDataTypeValidator validator2 = new CssLengthValueValidator(true);
NUnit.Framework.Assert.IsFalse(validator2.IsValid(""));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("dja"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("5pixels"));
}
[NUnit.Framework.Test]
public virtual void AbsoluteValuesTest() {
ICssDataTypeValidator validator1 = new CssLengthValueValidator(false);
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12"));
NUnit.Framework.Assert.IsTrue(validator1.IsValid("12pt"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("-12pt"));
NUnit.Framework.Assert.IsTrue(validator1.IsValid("12px"));
NUnit.Framework.Assert.IsTrue(validator1.IsValid("12in"));
NUnit.Framework.Assert.IsTrue(validator1.IsValid("12cm"));
NUnit.Framework.Assert.IsTrue(validator1.IsValid("12mm"));
NUnit.Framework.Assert.IsTrue(validator1.IsValid("12pc"));
NUnit.Framework.Assert.IsTrue(validator1.IsValid("12q"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12 pt"));
ICssDataTypeValidator validator2 = new CssLengthValueValidator(true);
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("12pt"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("-12pt"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("12px"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("12in"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("12cm"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("12mm"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("12pc"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("12q"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12 pt"));
}
[NUnit.Framework.Test]
public virtual void RelativeValuesTest() {
ICssDataTypeValidator validator1 = new CssLengthValueValidator(false);
NUnit.Framework.Assert.IsTrue(validator1.IsValid("12em"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("-12em"));
NUnit.Framework.Assert.IsTrue(validator1.IsValid("12rem"));
NUnit.Framework.Assert.IsTrue(validator1.IsValid("12ex"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12 em"));
ICssDataTypeValidator validator2 = new CssLengthValueValidator(true);
NUnit.Framework.Assert.IsTrue(validator2.IsValid("12em"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("-12em"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("12rem"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("12ex"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12 em"));
}
[NUnit.Framework.Test]
public virtual void PercentValueTest() {
ICssDataTypeValidator validator1 = new CssLengthValueValidator(false);
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12%"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("-12%"));
ICssDataTypeValidator validator2 = new CssLengthValueValidator(true);
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12%"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("-12%"));
}
}
}

View File

@@ -0,0 +1,129 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using TSpdf.StyledXmlParser.Css.Validate.Impl.Datatype;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Validate {
[NUnit.Framework.Category("UnitTest")]
public class CssNumberValueValidatorTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void ZeroValueTest() {
ICssDataTypeValidator validator1 = new CssNumberValueValidator(false);
NUnit.Framework.Assert.IsTrue(validator1.IsValid("0"));
ICssDataTypeValidator validator2 = new CssNumberValueValidator(true);
NUnit.Framework.Assert.IsTrue(validator2.IsValid("0"));
}
[NUnit.Framework.Test]
public virtual void NullValueTest() {
ICssDataTypeValidator validator1 = new CssNumberValueValidator(false);
NUnit.Framework.Assert.IsFalse(validator1.IsValid(null));
ICssDataTypeValidator validator2 = new CssNumberValueValidator(true);
NUnit.Framework.Assert.IsFalse(validator2.IsValid(null));
}
[NUnit.Framework.Test]
public virtual void InitialInheritUnsetValuesTest() {
ICssDataTypeValidator validator1 = new CssNumberValueValidator(false);
NUnit.Framework.Assert.IsTrue(validator1.IsValid("initial"));
NUnit.Framework.Assert.IsTrue(validator1.IsValid("inherit"));
NUnit.Framework.Assert.IsTrue(validator1.IsValid("unset"));
ICssDataTypeValidator validator2 = new CssNumberValueValidator(true);
NUnit.Framework.Assert.IsTrue(validator2.IsValid("initial"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("inherit"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("unset"));
}
[NUnit.Framework.Test]
public virtual void NormalValueTest() {
ICssDataTypeValidator validator1 = new CssNumberValueValidator(false);
NUnit.Framework.Assert.IsFalse(validator1.IsValid("normal"));
ICssDataTypeValidator validator2 = new CssNumberValueValidator(true);
NUnit.Framework.Assert.IsFalse(validator2.IsValid("normal"));
}
[NUnit.Framework.Test]
public virtual void InvalidValuesTest() {
ICssDataTypeValidator validator1 = new CssNumberValueValidator(false);
NUnit.Framework.Assert.IsFalse(validator1.IsValid(""));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("dja"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("5pixels"));
ICssDataTypeValidator validator2 = new CssNumberValueValidator(true);
NUnit.Framework.Assert.IsFalse(validator2.IsValid(""));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("dja"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("5pixels"));
}
[NUnit.Framework.Test]
public virtual void AbsoluteValuesTest() {
ICssDataTypeValidator validator1 = new CssNumberValueValidator(false);
NUnit.Framework.Assert.IsTrue(validator1.IsValid("12"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12pt"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("-12pt"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12px"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12in"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12cm"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12mm"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12pc"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12q"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12 pt"));
ICssDataTypeValidator validator2 = new CssNumberValueValidator(true);
NUnit.Framework.Assert.IsTrue(validator2.IsValid("12"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12pt"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("-12pt"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12px"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12in"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12cm"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12mm"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12pc"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12q"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12 pt"));
}
[NUnit.Framework.Test]
public virtual void RelativeValuesTest() {
ICssDataTypeValidator validator1 = new CssNumberValueValidator(false);
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12em"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("-12em"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12rem"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12ex"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12 em"));
ICssDataTypeValidator validator2 = new CssNumberValueValidator(true);
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12em"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("-12em"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12rem"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12ex"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12 em"));
}
[NUnit.Framework.Test]
public virtual void PercentValueTest() {
ICssDataTypeValidator validator1 = new CssNumberValueValidator(false);
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12%"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("-12%"));
ICssDataTypeValidator validator2 = new CssNumberValueValidator(true);
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12%"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("-12%"));
}
}
}

View File

@@ -0,0 +1,129 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using TSpdf.StyledXmlParser.Css.Validate.Impl.Datatype;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Css.Validate {
[NUnit.Framework.Category("UnitTest")]
public class CssPercentageValueValidatorTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void ZeroValueTest() {
ICssDataTypeValidator validator1 = new CssPercentageValueValidator(false);
NUnit.Framework.Assert.IsFalse(validator1.IsValid("0"));
ICssDataTypeValidator validator2 = new CssPercentageValueValidator(true);
NUnit.Framework.Assert.IsFalse(validator2.IsValid("0"));
}
[NUnit.Framework.Test]
public virtual void NullValueTest() {
ICssDataTypeValidator validator1 = new CssPercentageValueValidator(false);
NUnit.Framework.Assert.IsFalse(validator1.IsValid(null));
ICssDataTypeValidator validator2 = new CssPercentageValueValidator(true);
NUnit.Framework.Assert.IsFalse(validator2.IsValid(null));
}
[NUnit.Framework.Test]
public virtual void InitialInheritUnsetValuesTest() {
ICssDataTypeValidator validator1 = new CssPercentageValueValidator(false);
NUnit.Framework.Assert.IsTrue(validator1.IsValid("initial"));
NUnit.Framework.Assert.IsTrue(validator1.IsValid("inherit"));
NUnit.Framework.Assert.IsTrue(validator1.IsValid("unset"));
ICssDataTypeValidator validator2 = new CssPercentageValueValidator(true);
NUnit.Framework.Assert.IsTrue(validator2.IsValid("initial"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("inherit"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("unset"));
}
[NUnit.Framework.Test]
public virtual void NormalValueTest() {
ICssDataTypeValidator validator1 = new CssPercentageValueValidator(false);
NUnit.Framework.Assert.IsFalse(validator1.IsValid("normal"));
ICssDataTypeValidator validator2 = new CssPercentageValueValidator(true);
NUnit.Framework.Assert.IsFalse(validator2.IsValid("normal"));
}
[NUnit.Framework.Test]
public virtual void InvalidValuesTest() {
ICssDataTypeValidator validator1 = new CssPercentageValueValidator(false);
NUnit.Framework.Assert.IsFalse(validator1.IsValid(""));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("dja"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("5pixels"));
ICssDataTypeValidator validator2 = new CssPercentageValueValidator(true);
NUnit.Framework.Assert.IsFalse(validator2.IsValid(""));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("dja"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("5pixels"));
}
[NUnit.Framework.Test]
public virtual void AbsoluteValuesTest() {
ICssDataTypeValidator validator1 = new CssPercentageValueValidator(false);
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12pt"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("-12pt"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12px"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12in"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12cm"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12mm"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12pc"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12q"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12 pt"));
ICssDataTypeValidator validator2 = new CssPercentageValueValidator(true);
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12pt"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("-12pt"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12px"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12in"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12cm"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12mm"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12pc"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12q"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12 pt"));
}
[NUnit.Framework.Test]
public virtual void RelativeValuesTest() {
ICssDataTypeValidator validator1 = new CssPercentageValueValidator(false);
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12em"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("-12em"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12rem"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12ex"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("12 em"));
ICssDataTypeValidator validator2 = new CssPercentageValueValidator(true);
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12em"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("-12em"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12rem"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12ex"));
NUnit.Framework.Assert.IsFalse(validator2.IsValid("12 em"));
}
[NUnit.Framework.Test]
public virtual void PercentValueTest() {
ICssDataTypeValidator validator1 = new CssPercentageValueValidator(false);
NUnit.Framework.Assert.IsTrue(validator1.IsValid("12%"));
NUnit.Framework.Assert.IsFalse(validator1.IsValid("-12%"));
ICssDataTypeValidator validator2 = new CssPercentageValueValidator(true);
NUnit.Framework.Assert.IsTrue(validator2.IsValid("12%"));
NUnit.Framework.Assert.IsTrue(validator2.IsValid("-12%"));
}
}
}

View File

@@ -0,0 +1,73 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.IO;
using TSpdf.StyledXmlParser.Node;
using TSpdf.StyledXmlParser.Node.Impl.Jsoup;
using TSpdf.StyledXmlParser.Node.Impl.Jsoup.Node;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.StyledXmlParser.Jsoup {
[NUnit.Framework.Category("UnitTest")]
public class JsoupXmlParserTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void TestXmlDeclarationAndComment() {
String xml = "<?xml version=\"1.0\" standalone=\"no\"?>\n" + "<!-- just declaration and comment -->";
Stream stream = new MemoryStream(xml.GetBytes());
IDocumentNode node = new JsoupXmlParser().Parse(stream, "UTF-8");
// only text (whitespace) child node shall be fetched.
NUnit.Framework.Assert.AreEqual(1, node.ChildNodes().Count);
}
[NUnit.Framework.Test]
[LogMessage(TSpdf.StyledXmlParser.Logs.StyledXmlParserLogMessageConstant.ERROR_ADDING_CHILD_NODE)]
public virtual void TestMessageAddingChild() {
TSpdf.StyledXmlParser.Jsoup.Nodes.Element jsoupSVGRoot = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element(TSpdf.StyledXmlParser.Jsoup.Parser.Tag
.ValueOf("svg"), "");
INode root = new JsoupElementNode(jsoupSVGRoot);
root.AddChild(null);
NUnit.Framework.Assert.AreEqual(0, root.ChildNodes().Count);
}
}
}

View File

@@ -0,0 +1,56 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.IO;
namespace TSpdf.StyledXmlParser.Jsoup {
internal class PortTestUtil {
public static readonly String sourceFolder =
TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext.CurrentContext.TestDirectory) +
"/";
public static FileInfo GetFile(String filename) {
return new FileInfo(sourceFolder + "resources/TSpdf/styledxmlparser/jsoup" + filename);
}
}
}

View File

@@ -0,0 +1,37 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup {
[NUnit.Framework.Category("UnitTest")]
public class PortUtilTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void TrimControlCodesTest() {
for (int i = 0; i < ' ' + 1; ++i) {
String str = new String(new char[] { (char)i });
NUnit.Framework.Assert.IsTrue(String.IsNullOrEmpty(PortUtil.TrimControlCodes(str)));
}
}
}
}

View File

@@ -0,0 +1,57 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Text.RegularExpressions;
namespace TSpdf.StyledXmlParser.Jsoup {
/// <summary>Text utils to ease testing</summary>
/// <author>Jonathan Hedley, jonathan@hedley.net</author>
public class TextUtil {
internal static Regex stripper = TSpdf.Commons.Utils.StringUtil.RegexCompile("\\r?\\n\\s*");
public static String StripNewlines(String text)
{
return stripper.Replace(text, "");
}
}
}

View File

@@ -0,0 +1,217 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.IO;
using TSpdf.StyledXmlParser.Jsoup.Integration;
using TSpdf.StyledXmlParser.Jsoup.Nodes;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Helper {
[NUnit.Framework.Category("UnitTest")]
public class DataUtilTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void TestCharset() {
NUnit.Framework.Assert.AreEqual("utf-8", DataUtil.GetCharsetFromContentType("text/html;charset=utf-8 "));
NUnit.Framework.Assert.AreEqual("UTF-8", DataUtil.GetCharsetFromContentType("text/html; charset=UTF-8"));
NUnit.Framework.Assert.AreEqual("ISO-8859-1", DataUtil.GetCharsetFromContentType("text/html; charset=ISO-8859-1"
));
NUnit.Framework.Assert.IsNull(DataUtil.GetCharsetFromContentType("text/html"));
NUnit.Framework.Assert.IsNull(DataUtil.GetCharsetFromContentType(null));
NUnit.Framework.Assert.IsNull(DataUtil.GetCharsetFromContentType("text/html;charset=Unknown"));
}
[NUnit.Framework.Test]
public virtual void TestQuotedCharset() {
NUnit.Framework.Assert.AreEqual("utf-8", DataUtil.GetCharsetFromContentType("text/html; charset=\"utf-8\""
));
NUnit.Framework.Assert.AreEqual("UTF-8", DataUtil.GetCharsetFromContentType("text/html;charset=\"UTF-8\"")
);
NUnit.Framework.Assert.AreEqual("ISO-8859-1", DataUtil.GetCharsetFromContentType("text/html; charset=\"ISO-8859-1\""
));
NUnit.Framework.Assert.IsNull(DataUtil.GetCharsetFromContentType("text/html; charset=\"Unsupported\""));
NUnit.Framework.Assert.AreEqual("UTF-8", DataUtil.GetCharsetFromContentType("text/html; charset='UTF-8'"));
}
private System.IO.Stream Stream(String data) {
return new MemoryStream(data.GetBytes(System.Text.Encoding.UTF8));
}
private System.IO.Stream Stream(String data, String charset) {
try {
return new MemoryStream(data.GetBytes(charset));
}
catch (ArgumentException) {
NUnit.Framework.Assert.Fail();
}
return null;
}
[NUnit.Framework.Test]
public virtual void DiscardsSpuriousByteOrderMark() {
String html = "\uFEFF<html><head><title>One</title></head><body>Two</body></html>";
Document doc = DataUtil.ParseInputStream(Stream(html), "UTF-8", "http://foo.com/", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.HtmlParser());
NUnit.Framework.Assert.AreEqual("One", doc.Head().Text());
}
[NUnit.Framework.Test]
public virtual void DiscardsSpuriousByteOrderMarkWhenNoCharsetSet() {
String html = "\uFEFF<html><head><title>One</title></head><body>Two</body></html>";
Document doc = DataUtil.ParseInputStream(Stream(html), null, "http://foo.com/", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.HtmlParser());
NUnit.Framework.Assert.AreEqual("One", doc.Head().Text());
NUnit.Framework.Assert.AreEqual("UTF-8", doc.OutputSettings().Charset().DisplayName());
}
[NUnit.Framework.Test]
public virtual void ShouldNotThrowExceptionOnEmptyCharset() {
NUnit.Framework.Assert.IsNull(DataUtil.GetCharsetFromContentType("text/html; charset="));
NUnit.Framework.Assert.IsNull(DataUtil.GetCharsetFromContentType("text/html; charset=;"));
}
[NUnit.Framework.Test]
public virtual void ShouldSelectFirstCharsetOnWeirdMultileCharsetsInMetaTags() {
NUnit.Framework.Assert.AreEqual("ISO-8859-1", DataUtil.GetCharsetFromContentType("text/html; charset=ISO-8859-1, charset=1251"
));
}
[NUnit.Framework.Test]
public virtual void ShouldCorrectCharsetForDuplicateCharsetString() {
NUnit.Framework.Assert.AreEqual("iso-8859-1", DataUtil.GetCharsetFromContentType("text/html; charset=charset=iso-8859-1"
));
}
[NUnit.Framework.Test]
public virtual void ShouldReturnNullForIllegalCharsetNames() {
NUnit.Framework.Assert.IsNull(DataUtil.GetCharsetFromContentType("text/html; charset=$HJKDF§$/("));
}
[NUnit.Framework.Test]
public virtual void WrongMetaCharsetFallback() {
String html = "<html><head><meta charset=iso-8></head><body></body></html>";
Document doc = DataUtil.ParseInputStream(Stream(html), null, "http://example.com", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.HtmlParser());
String expected = "<html>\n" + " <head>\n" + " <meta charset=\"iso-8\">\n" + " </head>\n" + " <body></body>\n"
+ "</html>";
NUnit.Framework.Assert.AreEqual(expected, doc.ToString());
}
[NUnit.Framework.Test]
public virtual void SecondMetaElementWithContentTypeContainsCharsetParameter() {
String html = "<html><head>" + "<meta http-equiv=\"Content-Type\" content=\"text/html\">" + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=euc-kr\">"
+ "</head><body>한국어</body></html>";
Document doc = DataUtil.ParseInputStream(Stream(html, "euc-kr"), null, "http://example.com", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.HtmlParser());
NUnit.Framework.Assert.AreEqual("한국어", doc.Body().Text());
}
[NUnit.Framework.Test]
public virtual void FirstMetaElementWithCharsetShouldBeUsedForDecoding() {
String html = "<html><head>" + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">"
+ "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=koi8-u\">" + "</head><body>Übergrößenträger</body></html>";
Document doc = DataUtil.ParseInputStream(Stream(html, "iso-8859-1"), null, "http://example.com", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.HtmlParser());
NUnit.Framework.Assert.AreEqual("Übergrößenträger", doc.Body().Text());
}
[NUnit.Framework.Test]
public virtual void SupportsBOMinFiles() {
// test files from http://www.i18nl10n.com/korean/utftest/
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/bomtests/bom_utf16be.html");
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, null, "http://example.com");
NUnit.Framework.Assert.IsTrue(doc.Title().Contains("UTF-16BE"));
NUnit.Framework.Assert.IsTrue(doc.Text().Contains("가각갂갃간갅"));
@in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/bomtests/bom_utf16le.html");
doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, null, "http://example.com");
NUnit.Framework.Assert.IsTrue(doc.Title().Contains("UTF-16LE"));
NUnit.Framework.Assert.IsTrue(doc.Text().Contains("가각갂갃간갅"));
@in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/bomtests/bom_utf32be.html");
doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, null, "http://example.com");
NUnit.Framework.Assert.IsTrue(doc.Title().Contains("UTF-32BE"));
NUnit.Framework.Assert.IsTrue(doc.Text().Contains("가각갂갃간갅"));
@in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/bomtests/bom_utf32le.html");
doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, null, "http://example.com");
NUnit.Framework.Assert.IsTrue(doc.Title().Contains("UTF-32LE"));
NUnit.Framework.Assert.IsTrue(doc.Text().Contains("가각갂갃간갅"));
}
[NUnit.Framework.Test]
public virtual void SupportsUTF8BOM() {
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/bomtests/bom_utf8.html");
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, null, "http://example.com");
NUnit.Framework.Assert.AreEqual("OK", doc.Head().Select("title").Text());
}
[NUnit.Framework.Test]
public virtual void NoExtraNULLBytes() {
byte[] b = "<html><head><meta charset=\"UTF-8\"></head><body><div><u>ü</u>ü</div></body></html>".GetBytes(
"UTF-8");
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(new MemoryStream(b), null, "");
NUnit.Framework.Assert.IsFalse(doc.OuterHtml().Contains("\u0000"));
}
[NUnit.Framework.Test]
public virtual void SupportsZippedUTF8BOM() {
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/bomtests/bom_utf8.html.gz");
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, null, "http://example.com");
NUnit.Framework.Assert.AreEqual("OK", doc.Head().Select("title").Text());
NUnit.Framework.Assert.AreEqual("There is a UTF8 BOM at the top (before the XML decl). If not read correctly, will look like a non-joining space."
, doc.Body().Text());
}
[NUnit.Framework.Test]
public virtual void SupportsXmlCharsetDeclaration() {
String encoding = "iso-8859-1";
System.IO.Stream soup = new MemoryStream(("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" + "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"
+ "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">Hellö Wörld!</html>").GetBytes
(encoding));
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(soup, null, "");
NUnit.Framework.Assert.AreEqual("Hellö Wörld!", doc.Body().Text());
}
[NUnit.Framework.Test]
public virtual void LLoadsGzipFile() {
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/gzip.html.gz");
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, null);
NUnit.Framework.Assert.AreEqual("Gzip test", doc.Title());
NUnit.Framework.Assert.AreEqual("This is a gzipped HTML file.", doc.SelectFirst("p").Text());
}
[NUnit.Framework.Test]
public virtual void LoadsZGzipFile() {
// compressed on win, with z suffix
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/gzip.html.z");
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, null);
NUnit.Framework.Assert.AreEqual("Gzip test", doc.Title());
NUnit.Framework.Assert.AreEqual("This is a gzipped HTML file.", doc.SelectFirst("p").Text());
}
[NUnit.Framework.Test]
public virtual void HandlesFakeGzipFile() {
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/fake-gzip.html.gz");
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, null);
NUnit.Framework.Assert.AreEqual("This is not gzipped", doc.Title());
NUnit.Framework.Assert.AreEqual("And should still be readable.", doc.SelectFirst("p").Text());
}
}
}

View File

@@ -0,0 +1,42 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Helper {
[NUnit.Framework.Category("UnitTest")]
public class ValidateTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void TestNotNull() {
Validate.NotNull("foo");
bool threw = false;
try {
Validate.NotNull(null);
}
catch (ArgumentException) {
threw = true;
}
NUnit.Framework.Assert.IsTrue(threw);
}
}
}

View File

@@ -0,0 +1,89 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.IO;
using TSpdf.StyledXmlParser.Jsoup.Nodes;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Integration {
/// <summary>Tests fixes for issues raised by the OSS Fuzz project @ https://oss-fuzz.com/testcases?project=jsoup
/// </summary>
[NUnit.Framework.Category("IntegrationTest")]
public class FuzzFixesTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void BlankAbsAttr() {
// https://github.com/jhy/jsoup/issues/1541
String html = "b<bodY abs: abs:abs: abs:abs:abs>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
NUnit.Framework.Assert.IsNotNull(doc);
}
[NUnit.Framework.Test]
public virtual void ResetInsertionMode() {
// https://github.com/jhy/jsoup/issues/1538
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/fuzztests/1538.html");
// lots of escape chars etc.
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, "UTF-8");
NUnit.Framework.Assert.IsNotNull(doc);
}
[NUnit.Framework.Test]
public virtual void XmlDeclOverflow() {
// https://github.com/jhy/jsoup/issues/1539
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/fuzztests/1539.html");
// lots of escape chars etc.
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, "UTF-8");
NUnit.Framework.Assert.IsNotNull(doc);
Document docXml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(new FileStream(@in.FullName, FileMode.Open, FileAccess.Read
), "UTF-8", "https://example.com", TSpdf.StyledXmlParser.Jsoup.Parser.Parser.XmlParser());
NUnit.Framework.Assert.IsNotNull(docXml);
}
[NUnit.Framework.Test]
public virtual void XmlDeclOverflowOOM() {
// https://github.com/jhy/jsoup/issues/1569
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/fuzztests/1569.html");
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, "UTF-8");
NUnit.Framework.Assert.IsNotNull(doc);
Document docXml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(new FileStream(@in.FullName, FileMode.Open, FileAccess.Read
), "UTF-8", "https://example.com", TSpdf.StyledXmlParser.Jsoup.Parser.Parser.XmlParser());
NUnit.Framework.Assert.IsNotNull(docXml);
}
[NUnit.Framework.Test]
public virtual void StackOverflowState14() {
// https://github.com/jhy/jsoup/issues/1543
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/fuzztests/1543.html");
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, "UTF-8");
NUnit.Framework.Assert.IsNotNull(doc);
}
[NUnit.Framework.Test]
public virtual void ParseTimeout() {
// https://github.com/jhy/jsoup/issues/1544
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/fuzztests/1544.html");
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, "UTF-8");
NUnit.Framework.Assert.IsNotNull(doc);
}
}
}

View File

@@ -0,0 +1,284 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.IO;
using System.IO.Compression;
using TSpdf.Commons.Utils;
using TSpdf.StyledXmlParser.Jsoup.Helper;
using TSpdf.StyledXmlParser.Jsoup.Nodes;
using TSpdf.StyledXmlParser.Jsoup.Parser;
using TSpdf.StyledXmlParser.Jsoup.Select;
using TSpdf.Test;
using NUnit.Framework;
namespace TSpdf.StyledXmlParser.Jsoup.Integration {
/// <summary>Integration test: parses from real-world example HTML.</summary>
/// <author>Jonathan Hedley, jonathan@hedley.net</author>
public class ParseTest : ExtendedTSpdfTest {
public static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/styledxmlparser/jsoup";
[NUnit.Framework.Test]
public void TestSmhBizArticle() {
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/smh-biz-article-1.html.gz");
Document doc = Jsoup.Parse(@in, "UTF-8",
"http://www.smh.com.au/business/the-boards-next-fear-the-female-quota-20100106-lteq.html");
NUnit.Framework.Assert.AreEqual("The boards next fear: the female quota",
doc.Title()); // note that the apos in the source is a literal (8217), not escaped or '
NUnit.Framework.Assert.AreEqual("en", doc.Select("html").Attr("xml:lang"));
Elements articleBody = doc.Select(".articleBody > *");
NUnit.Framework.Assert.AreEqual(17, articleBody.Count);
}
[NUnit.Framework.Test]
public void TestNewsHomepage() {
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/news-com-au-home.html.gz");
Document doc = Jsoup.Parse(@in, "UTF-8", "http://www.news.com.au/");
NUnit.Framework.Assert.AreEqual("News.com.au | News from Australia and around the world online | NewsComAu", doc.Title());
NUnit.Framework.Assert.AreEqual("Brace yourself for Metro meltdown", doc.Select(".id1225817868581 h4").Text().Trim());
Element a = doc.Select("a[href=/entertainment/horoscopes]").First();
NUnit.Framework.Assert.AreEqual("/entertainment/horoscopes", a.Attr("href"));
NUnit.Framework.Assert.AreEqual("http://www.news.com.au/entertainment/horoscopes", a.Attr("abs:href"));
Element hs = doc.Select("a[href*=naughty-corners-are-a-bad-idea]").First();
NUnit.Framework.Assert.AreEqual(
"http://www.heraldsun.com.au/news/naughty-corners-are-a-bad-idea-for-kids/story-e6frf7jo-1225817899003",
hs.Attr("href"));
NUnit.Framework.Assert.AreEqual(hs.Attr("href"), hs.Attr("abs:href"));
}
[NUnit.Framework.Test]
public void TestGoogleSearchIpod() {
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/google-ipod.html.gz");
Document doc = Jsoup.Parse(@in, "UTF-8", "http://www.google.com/search?hl=en&q=ipod&aq=f&oq=&aqi=g10");
NUnit.Framework.Assert.AreEqual("ipod - Google Search", doc.Title());
Elements results = doc.Select("h3.r > a");
NUnit.Framework.Assert.AreEqual(12, results.Count);
NUnit.Framework.Assert.AreEqual(
"http://news.google.com/news?hl=en&q=ipod&um=1&ie=UTF-8&ei=uYlKS4SbBoGg6gPf-5XXCw&sa=X&oi=news_group&ct=title&resnum=1&ved=0CCIQsQQwAA",
results[0].Attr("href"));
NUnit.Framework.Assert.AreEqual("http://www.apple.com/itunes/",
results[1].Attr("href"));
}
[NUnit.Framework.Test]
public void TestYahooJp() {
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/yahoo-jp.html.gz");
Document doc = Jsoup.Parse(@in, "UTF-8", "http://www.yahoo.co.jp/index.html"); // http charset is utf-8.
NUnit.Framework.Assert.AreEqual("Yahoo! JAPAN", doc.Title());
Element a = doc.Select("a[href=t/2322m2]").First();
NUnit.Framework.Assert.AreEqual("http://www.yahoo.co.jp/_ylh=X3oDMTB0NWxnaGxsBF9TAzIwNzcyOTYyNjUEdGlkAzEyBHRtcGwDZ2Ex/t/2322m2",
a.Attr("abs:href")); // session put into <base>
NUnit.Framework.Assert.AreEqual("全国、人気の駅ランキング", a.Text());
}
[NUnit.Framework.Test]
public virtual void TestBaidu() {
// tests <meta http-equiv="Content-Type" content="text/html;charset=gb2312">
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/baidu-cn-home.html");
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, null, "http://www.baidu.com");
// http charset is gb2312, but NOT specifying it, to test http-equiv parse
TSpdf.StyledXmlParser.Jsoup.Nodes.Element submit = doc.Select("#su").First();
NUnit.Framework.Assert.AreEqual("百度一下", submit.Attr("value"));
// test from attribute match
submit = doc.Select("input[value=百度一下]").First();
NUnit.Framework.Assert.AreEqual("su", submit.Id());
TSpdf.StyledXmlParser.Jsoup.Nodes.Element newsLink = doc.Select("a:contains(新)").First();
NUnit.Framework.Assert.AreEqual("http://news.baidu.com/", newsLink.AbsUrl("href"));
// check auto-detect from meta
NUnit.Framework.Assert.AreEqual("GB2312", doc.OutputSettings().Charset().DisplayName());
NUnit.Framework.Assert.AreEqual("<title>百度一下,你就知道 </title>", doc.Select("title").OuterHtml());
doc.OutputSettings().Charset("ascii");
NUnit.Framework.Assert.AreEqual("<title>&#x767e;&#x5ea6;&#x4e00;&#x4e0b;&#xff0c;&#x4f60;&#x5c31;&#x77e5;&#x9053; </title>"
, doc.Select("title").OuterHtml());
}
[NUnit.Framework.Test]
public virtual void TestBaiduVariant() {
// tests <meta charset> when preceded by another <meta>
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/baidu-variant.html");
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, null, "http://www.baidu.com/");
// http charset is gb2312, but NOT specifying it, to test http-equiv parse
// check auto-detect from meta
NUnit.Framework.Assert.AreEqual("GB2312", doc.OutputSettings().Charset().DisplayName());
NUnit.Framework.Assert.AreEqual("<title>百度一下,你就知道</title>", doc.Select("title").OuterHtml());
}
[NUnit.Framework.Test]
public virtual void TestHtml5Charset() {
// test that <meta charset="gb2312"> works
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/meta-charset-1.html");
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, null, "http://example.com/");
//gb2312, has html5 <meta charset>
NUnit.Framework.Assert.AreEqual("新", doc.Text());
NUnit.Framework.Assert.AreEqual("GB2312", doc.OutputSettings().Charset().DisplayName());
// double check, no charset, falls back to utf8 which is incorrect
@in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/meta-charset-2.html");
//
doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, null, "http://example.com");
// gb2312, no charset
NUnit.Framework.Assert.AreEqual("UTF-8", doc.OutputSettings().Charset().DisplayName());
NUnit.Framework.Assert.AreNotEqual("新", doc.Text());
// confirm fallback to utf8
@in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/meta-charset-3.html");
doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, null, "http://example.com/");
// utf8, no charset
NUnit.Framework.Assert.AreEqual("UTF-8", doc.OutputSettings().Charset().DisplayName());
NUnit.Framework.Assert.AreEqual("新", doc.Text());
}
[NUnit.Framework.Test]
public virtual void TestBrokenHtml5CharsetWithASingleDoubleQuote() {
Stream @in = InputStreamFrom("<html>\n" + "<head><meta charset=UTF-8\"></head>\n" + "<body></body>\n" + "</html>"
);
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, null, "http://example.com/");
NUnit.Framework.Assert.AreEqual("UTF-8", doc.OutputSettings().Charset().DisplayName());
}
[NUnit.Framework.Test]
public void TestNytArticle()
{
// has tags like <nyt_text>
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/nyt-article-1.html.gz");
Document doc = Jsoup.Parse(@in, null, "http://www.nytimes.com/2010/07/26/business/global/26bp.html?hp");
Element headline = doc.Select("nyt_headline[version=1.0]").First();
NUnit.Framework.Assert.AreEqual("As BP Lays Out Future, It Will Not Include Hayward", headline.Text());
}
[NUnit.Framework.Test]
public void TestYahooArticle()
{
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/yahoo-article-1.html.gz");
Document doc = Jsoup.Parse(@in, "UTF-8", "http://news.yahoo.com/s/nm/20100831/bs_nm/us_gm_china");
Element p = doc.Select("p:contains(Volt will be sold in the United States)").First();
NUnit.Framework.Assert.AreEqual(
"In July, GM said its electric Chevrolet Volt will be sold in the United States at $41,000 -- $8,000 more than its nearest competitor, the Nissan Leaf.",
p.Text());
}
[NUnit.Framework.Test]
public virtual void TestLowercaseUtf8Charset() {
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/lowercase-charset-test.html");
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, null);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element form = doc.Select("#form").First();
NUnit.Framework.Assert.AreEqual(2, form.Children().Count);
NUnit.Framework.Assert.AreEqual("UTF-8", doc.OutputSettings().Charset().Name());
}
[NUnit.Framework.Test]
public void TestXwiki() {
// https://github.com/jhy/jsoup/issues/1324
// this tests that when in CharacterReader we hit a buffer while marked, we preserve the mark when buffered up and can rewind
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/xwiki-1324.html.gz");
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, null, "https://localhost/");
NUnit.Framework.Assert.AreEqual("XWiki Jetty HSQLDB 12.1-SNAPSHOT", doc.Select("#xwikiplatformversion").Text());
// was getting busted at =userdirectory, because it hit the bufferup point but the mark was then lost. so
// updated to preserve the mark.
String wantHtml = "<a class=\"list-group-item\" data-id=\"userdirectory\" href=\"/xwiki/bin/admin/XWiki/XWikiPreferences?editor=globaladmin&amp;section=userdirectory\" title=\"Customize the user directory live table.\">User Directory</a>";
NUnit.Framework.Assert.AreEqual(wantHtml, doc.Select("[data-id=userdirectory]").OuterHtml());
}
[NUnit.Framework.Test]
public void TestXwikiExpanded() {
// https://github.com/jhy/jsoup/issues/1324
// this tests that if there is a huge illegal character reference, we can get through a buffer and rewind, and still catch that it's an invalid refence,
// and the parse tree is correct.
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/xwiki-edit.html.gz");
TSpdf.StyledXmlParser.Jsoup.Parser.Parser parser = TSpdf.StyledXmlParser.Jsoup.Parser.Parser.HtmlParser();
Document doc = Jsoup.Parse(new GZipStream(new FileStream(@in.FullName, FileMode.Open, FileAccess.Read), CompressionMode.Decompress), "UTF-8", "https://localhost/", parser.SetTrackErrors(100));
ParseErrorList errors = parser.GetErrors();
NUnit.Framework.Assert.AreEqual("XWiki Jetty HSQLDB 12.1-SNAPSHOT", doc.Select("#xwikiplatformversion").Text());
// not an invalid reference because did not look legit
NUnit.Framework.Assert.AreEqual(0, errors.Count);
// was getting busted at =userdirectory, because it hit the bufferup point but the mark was then lost. so
// updated to preserve the mark.
String wantHtml = "<a class=\"list-group-item\" data-id=\"userdirectory\" href=\"/xwiki/bin/admin/XWiki/XWikiPreferences?editor=globaladmin&amp;RIGHTHERERIGHTHERERIGHTHERERIGHTHERE";
NUnit.Framework.Assert.IsTrue(doc.Select("[data-id=userdirectory]").OuterHtml().StartsWith(wantHtml));
}
[NUnit.Framework.Test]
public virtual void TestWikiExpandedFromString() {
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/xwiki-edit.html.gz");
String html = GetFileAsString(@in);
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
NUnit.Framework.Assert.AreEqual("XWiki Jetty HSQLDB 12.1-SNAPSHOT", doc.Select("#xwikiplatformversion").Text
());
String wantHtml = "<a class=\"list-group-item\" data-id=\"userdirectory\" href=\"/xwiki/bin/admin/XWiki/XWikiPreferences?editor=globaladmin&amp;RIGHTHERERIGHTHERERIGHTHERERIGHTHERE";
NUnit.Framework.Assert.IsTrue(doc.Select("[data-id=userdirectory]").OuterHtml().StartsWith(wantHtml));
}
[NUnit.Framework.Test]
public virtual void TestWikiFromString() {
FileInfo @in = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/xwiki-1324.html.gz");
String html = GetFileAsString(@in);
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
NUnit.Framework.Assert.AreEqual("XWiki Jetty HSQLDB 12.1-SNAPSHOT", doc.Select("#xwikiplatformversion").Text
());
String wantHtml = "<a class=\"list-group-item\" data-id=\"userdirectory\" href=\"/xwiki/bin/admin/XWiki/XWikiPreferences?editor=globaladmin&amp;section=userdirectory\" title=\"Customize the user directory live table.\">User Directory</a>";
NUnit.Framework.Assert.AreEqual(wantHtml, doc.Select("[data-id=userdirectory]").OuterHtml());
}
public static Stream InputStreamFrom(String s) {
return new MemoryStream(s.GetBytes(System.Text.Encoding.UTF8));
}
public static String GetFileAsString(FileInfo file) {
byte[] bytes;
if (file.Name.EndsWith(".gz")) {
Stream stream = new GZipStream(new FileStream(file.FullName, FileMode.Open, FileAccess.Read), System.IO.Compression.CompressionMode.Decompress);
ByteBuffer byteBuffer = DataUtil.ReadToByteBuffer(stream, 0);
bytes = ((byte[])byteBuffer.Array());
}
else {
bytes = File.ReadAllBytes(file.FullName);
}
return JavaUtil.GetStringForBytes(bytes);
}
}
}

View File

@@ -0,0 +1,67 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.StyledXmlParser.Jsoup;
using TSpdf.StyledXmlParser.Jsoup.Safety;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Integration {
/// <summary>Check that we can extend Safelist methods</summary>
[NUnit.Framework.Category("IntegrationTest")]
public class SafelistExtensionTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void CanCustomizeSafeTests() {
SafelistExtensionTest.OpenSafelist openSafelist = new SafelistExtensionTest.OpenSafelist(Safelist.Relaxed(
));
Safelist safelist = Safelist.Relaxed();
String html = "<p><opentag openattr>Hello</opentag></p>";
String openClean = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, openSafelist);
String clean = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, safelist);
NUnit.Framework.Assert.AreEqual("<p><opentag openattr=\"\">Hello</opentag></p>", TextUtil.StripNewlines(openClean
));
NUnit.Framework.Assert.AreEqual("<p>Hello</p>", clean);
}
// passes tags and attributes starting with "open"
private class OpenSafelist : Safelist {
public OpenSafelist(Safelist safelist)
: base(safelist) {
}
protected internal override bool IsSafeAttribute(String tagName, TSpdf.StyledXmlParser.Jsoup.Nodes.Element
el, TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute attr) {
if (attr.Key.StartsWith("open")) {
return true;
}
return base.IsSafeAttribute(tagName, el, attr);
}
protected internal override bool IsSafeTag(String tag) {
if (tag.StartsWith("open")) {
return true;
}
return base.IsSafeTag(tag);
}
}
}
}

View File

@@ -0,0 +1,195 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Commons.Utils;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Internal {
[NUnit.Framework.Category("UnitTest")]
public class StringUtilTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void Join() {
NUnit.Framework.Assert.AreEqual("", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Join(JavaCollectionsUtil
.SingletonList(""), " "));
NUnit.Framework.Assert.AreEqual("one", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Join(JavaCollectionsUtil
.SingletonList("one"), " "));
NUnit.Framework.Assert.AreEqual("one two three", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Join(JavaUtil.ArraysAsList
("one", "two", "three"), " "));
}
[NUnit.Framework.Test]
public virtual void Padding() {
NUnit.Framework.Assert.AreEqual("", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Padding(0));
NUnit.Framework.Assert.AreEqual(" ", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Padding(1));
NUnit.Framework.Assert.AreEqual(" ", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Padding(2));
NUnit.Framework.Assert.AreEqual(" ", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Padding
(15));
NUnit.Framework.Assert.AreEqual(" ", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil
.Padding(45));
}
// we tap out at 30
[NUnit.Framework.Test]
public virtual void PaddingInACan() {
String[] padding = TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.padding;
NUnit.Framework.Assert.AreEqual(21, padding.Length);
for (int i = 0; i < padding.Length; i++) {
NUnit.Framework.Assert.AreEqual(i, padding[i].Length);
}
}
[NUnit.Framework.Test]
public virtual void IsBlank() {
NUnit.Framework.Assert.IsTrue(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsBlank(null));
NUnit.Framework.Assert.IsTrue(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsBlank(""));
NUnit.Framework.Assert.IsTrue(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsBlank(" "));
NUnit.Framework.Assert.IsTrue(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsBlank(" \r\n "));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsBlank("hello"));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsBlank(" hello "));
}
[NUnit.Framework.Test]
public virtual void IsNumeric() {
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsNumeric(null));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsNumeric(" "));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsNumeric("123 546"));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsNumeric("hello"));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsNumeric("123.334"));
NUnit.Framework.Assert.IsTrue(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsNumeric("1"));
NUnit.Framework.Assert.IsTrue(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsNumeric("1234"));
}
[NUnit.Framework.Test]
public virtual void IsWhitespace() {
NUnit.Framework.Assert.IsTrue(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsWhitespace('\t'));
NUnit.Framework.Assert.IsTrue(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsWhitespace('\n'));
NUnit.Framework.Assert.IsTrue(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsWhitespace('\r'));
NUnit.Framework.Assert.IsTrue(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsWhitespace('\f'));
NUnit.Framework.Assert.IsTrue(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsWhitespace(' '));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsWhitespace('\u00a0'));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsWhitespace('\u2000'));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsWhitespace('\u3000'));
}
[NUnit.Framework.Test]
public virtual void NormaliseWhiteSpace() {
NUnit.Framework.Assert.AreEqual(" ", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.NormaliseWhitespace(" \r \n \r\n"
));
NUnit.Framework.Assert.AreEqual(" hello there ", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.NormaliseWhitespace
(" hello \r \n there \n"));
NUnit.Framework.Assert.AreEqual("hello", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.NormaliseWhitespace
("hello"));
NUnit.Framework.Assert.AreEqual("hello there", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.NormaliseWhitespace
("hello\nthere"));
}
[NUnit.Framework.Test]
public virtual void NormaliseWhiteSpaceHandlesHighSurrogates() {
String test71540chars = "\ud869\udeb2\u304b\u309a 1";
String test71540charsExpectedSingleWhitespace = "\ud869\udeb2\u304b\u309a 1";
NUnit.Framework.Assert.AreEqual(test71540charsExpectedSingleWhitespace, TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.NormaliseWhitespace
(test71540chars));
String extractedText = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(test71540chars).Text();
NUnit.Framework.Assert.AreEqual(test71540charsExpectedSingleWhitespace, extractedText);
}
[NUnit.Framework.Test]
public virtual void ResolvesRelativeUrls() {
NUnit.Framework.Assert.AreEqual("http://example.com/one/two?three", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com", "./one/two?three"));
NUnit.Framework.Assert.AreEqual("http://example.com/one/two?three", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com?one", "./one/two?three"));
NUnit.Framework.Assert.AreEqual("http://example.com/one/two?three#four", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com", "./one/two?three#four"));
NUnit.Framework.Assert.AreEqual("https://example.com/one", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/", "https://example.com/one"));
NUnit.Framework.Assert.AreEqual("http://example.com/one/two.html", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/two/", "../one/two.html"));
NUnit.Framework.Assert.AreEqual("https://example2.com/one", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("https://example.com/", "//example2.com/one"));
NUnit.Framework.Assert.AreEqual("https://example.com:8080/one", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("https://example.com:8080", "./one"));
NUnit.Framework.Assert.AreEqual("https://example2.com/one", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/", "https://example2.com/one"));
NUnit.Framework.Assert.AreEqual("https://example.com/one", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("wrong", "https://example.com/one"));
NUnit.Framework.Assert.AreEqual("https://example.com/one", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("https://example.com/one", ""));
NUnit.Framework.Assert.AreEqual("", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve("wrong", "also wrong"
));
NUnit.Framework.Assert.AreEqual("ftp://example.com/one", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("ftp://example.com/two/", "../one"));
NUnit.Framework.Assert.AreEqual("ftp://example.com/one/two.c", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("ftp://example.com/one/", "./two.c"));
NUnit.Framework.Assert.AreEqual("ftp://example.com/one/two.c", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("ftp://example.com/one/", "two.c"));
// examples taken from rfc3986 section 5.4.2
NUnit.Framework.Assert.AreEqual("http://example.com/g", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/b/c/d;p?q", "../../../g"));
NUnit.Framework.Assert.AreEqual("http://example.com/g", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/b/c/d;p?q", "../../../../g"));
NUnit.Framework.Assert.AreEqual("http://example.com/g", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/b/c/d;p?q", "/./g"));
NUnit.Framework.Assert.AreEqual("http://example.com/g", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/b/c/d;p?q", "/../g"));
NUnit.Framework.Assert.AreEqual("http://example.com/b/c/g.", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/b/c/d;p?q", "g."));
NUnit.Framework.Assert.AreEqual("http://example.com/b/c/.g", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/b/c/d;p?q", ".g"));
NUnit.Framework.Assert.AreEqual("http://example.com/b/c/g..", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/b/c/d;p?q", "g.."));
NUnit.Framework.Assert.AreEqual("http://example.com/b/c/..g", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/b/c/d;p?q", "..g"));
NUnit.Framework.Assert.AreEqual("http://example.com/b/g", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/b/c/d;p?q", "./../g"));
NUnit.Framework.Assert.AreEqual("http://example.com/b/c/g/", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/b/c/d;p?q", "./g/."));
NUnit.Framework.Assert.AreEqual("http://example.com/b/c/g/h", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/b/c/d;p?q", "g/./h"));
NUnit.Framework.Assert.AreEqual("http://example.com/b/c/h", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/b/c/d;p?q", "g/../h"));
NUnit.Framework.Assert.AreEqual("http://example.com/b/c/g;x=1/y", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/b/c/d;p?q", "g;x=1/./y"));
NUnit.Framework.Assert.AreEqual("http://example.com/b/c/y", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/b/c/d;p?q", "g;x=1/../y"));
NUnit.Framework.Assert.AreEqual("http://example.com/b/c/g?y/./x", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/b/c/d;p?q", "g?y/./x"));
NUnit.Framework.Assert.AreEqual("http://example.com/b/c/g?y/../x", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/b/c/d;p?q", "g?y/../x"));
NUnit.Framework.Assert.AreEqual("http://example.com/b/c/g#s/./x", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/b/c/d;p?q", "g#s/./x"));
NUnit.Framework.Assert.AreEqual("http://example.com/b/c/g#s/../x", TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.Resolve
("http://example.com/b/c/d;p?q", "g#s/../x"));
}
[NUnit.Framework.Test]
public virtual void IsAscii() {
NUnit.Framework.Assert.IsTrue(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsAscii(""));
NUnit.Framework.Assert.IsTrue(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsAscii("example.com"));
NUnit.Framework.Assert.IsTrue(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsAscii("One Two"));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsAscii("🧔"));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsAscii("测试"));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsAscii("测试.com"));
}
}
}

View File

@@ -0,0 +1,121 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Nodes {
public class AttributeTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void Html() {
TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute attr = new TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute("key",
"value &");
NUnit.Framework.Assert.AreEqual("key=\"value &amp;\"", attr.Html());
NUnit.Framework.Assert.AreEqual(attr.Html(), attr.ToString());
}
[NUnit.Framework.Test]
public virtual void TestWithSupplementaryCharacterInAttributeKeyAndValue() {
String s = new String(TSpdf.IO.Util.TextUtil.ToChars(135361));
TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute attr = new TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute(s, "A"
+ s + "B");
NUnit.Framework.Assert.AreEqual(s + "=\"A" + s + "B\"", attr.Html());
NUnit.Framework.Assert.AreEqual(attr.Html(), attr.ToString());
}
[NUnit.Framework.Test]
public virtual void ValidatesKeysNotEmpty() {
NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => new TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute
(" ", "Check"));
}
[NUnit.Framework.Test]
public virtual void ValidatesKeysNotEmptyViaSet() {
NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => {
TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute attr = new TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute("One",
"Check");
attr.SetKey(" ");
}
);
}
[NUnit.Framework.Test]
public virtual void BooleanAttributesAreEmptyStringValues() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div hidden>");
Attributes attributes = doc.Body().Child(0).Attributes();
NUnit.Framework.Assert.AreEqual("", attributes.Get("hidden"));
IEnumerator<Attribute> enumerator = attributes.GetEnumerator();
NUnit.Framework.Assert.IsTrue(enumerator.MoveNext());
TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute first = enumerator.Current;
NUnit.Framework.Assert.AreEqual("hidden", first.Key);
NUnit.Framework.Assert.AreEqual("", first.Value);
NUnit.Framework.Assert.IsFalse(first.HasDeclaredValue());
NUnit.Framework.Assert.IsTrue(TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute.IsBooleanAttribute(first.Key));
}
[NUnit.Framework.Test]
public virtual void SettersOnOrphanAttribute() {
TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute attr = new TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute("one",
"two");
attr.SetKey("three");
String oldVal = attr.SetValue("four");
NUnit.Framework.Assert.AreEqual("two", oldVal);
NUnit.Framework.Assert.AreEqual("three", attr.Key);
NUnit.Framework.Assert.AreEqual("four", attr.Value);
NUnit.Framework.Assert.IsNull(attr.parent);
}
[NUnit.Framework.Test]
public virtual void HasValue() {
TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute a1 = new TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute("one", ""
);
TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute a2 = new TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute("two", null
);
TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute a3 = new TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute("thr", "thr"
);
NUnit.Framework.Assert.IsTrue(a1.HasDeclaredValue());
NUnit.Framework.Assert.IsFalse(a2.HasDeclaredValue());
NUnit.Framework.Assert.IsTrue(a3.HasDeclaredValue());
}
}
}

View File

@@ -0,0 +1,228 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Nodes {
/// <summary>Tests for Attributes.</summary>
/// <author>Jonathan Hedley</author>
public class AttributesTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void Html() {
Attributes a = new Attributes();
a.Put("Tot", "a&p");
a.Put("Hello", "There");
a.Put("data-name", "Jsoup");
NUnit.Framework.Assert.AreEqual(3, a.Size());
NUnit.Framework.Assert.IsTrue(a.HasKey("Tot"));
NUnit.Framework.Assert.IsTrue(a.HasKey("Hello"));
NUnit.Framework.Assert.IsTrue(a.HasKey("data-name"));
NUnit.Framework.Assert.IsFalse(a.HasKey("tot"));
NUnit.Framework.Assert.IsTrue(a.HasKeyIgnoreCase("tot"));
NUnit.Framework.Assert.AreEqual("There", a.GetIgnoreCase("hEllo"));
IDictionary<String, String> dataset = a.Dataset();
NUnit.Framework.Assert.AreEqual(1, dataset.Count);
NUnit.Framework.Assert.AreEqual("Jsoup", dataset.Get("name"));
NUnit.Framework.Assert.AreEqual("", a.Get("tot"));
NUnit.Framework.Assert.AreEqual("a&p", a.Get("Tot"));
NUnit.Framework.Assert.AreEqual("a&p", a.GetIgnoreCase("tot"));
NUnit.Framework.Assert.AreEqual(" Tot=\"a&amp;p\" Hello=\"There\" data-name=\"Jsoup\"", a.Html());
NUnit.Framework.Assert.AreEqual(a.Html(), a.ToString());
}
[NUnit.Framework.Test]
public virtual void TestIteratorUpdateable() {
Attributes a = new Attributes();
a.Put("Tot", "a&p");
a.Put("Hello", "There");
NUnit.Framework.Assert.IsFalse(a.HasKey("Foo"));
IEnumerator<TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute> iterator = a.GetEnumerator();
iterator.MoveNext();
TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute attr = iterator.Current;
iterator.MoveNext();
attr.SetKey("Foo");
attr = iterator.Current;
attr.SetKey("Bar");
attr.SetValue("Qux");
NUnit.Framework.Assert.AreEqual("a&p", a.Get("Foo"));
NUnit.Framework.Assert.AreEqual("Qux", a.Get("Bar"));
NUnit.Framework.Assert.IsFalse(a.HasKey("Tot"));
NUnit.Framework.Assert.IsFalse(a.HasKey("Hello"));
}
[NUnit.Framework.Test]
public virtual void TestIteratorHasNext() {
Attributes a = new Attributes();
a.Put("Tot", "1");
a.Put("Hello", "2");
a.Put("data-name", "3");
int seen = 0;
foreach (TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute attribute in a) {
seen++;
NUnit.Framework.Assert.AreEqual(seen.ToString(), attribute.Value);
}
NUnit.Framework.Assert.AreEqual(3, seen);
}
[NUnit.Framework.Test]
public virtual void TestIterator() {
Attributes a = new Attributes();
String[][] datas = new String[][] { new String[] { "Tot", "raul" }, new String[] { "Hello", "pismuth" }, new
String[] { "data-name", "Jsoup" } };
foreach (String[] atts in datas) {
a.Put(atts[0], atts[1]);
}
int i = 0;
foreach (TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute attribute in a) {
NUnit.Framework.Assert.AreEqual(datas[i][0], attribute.Key);
NUnit.Framework.Assert.AreEqual(datas[i][1], attribute.Value);
i++;
}
NUnit.Framework.Assert.AreEqual(datas.Length, i);
}
[NUnit.Framework.Test]
public virtual void TestIteratorSkipsInternal() {
Attributes a = new Attributes();
a.Put("One", "One");
a.Put(Attributes.InternalKey("baseUri"), "example.com");
a.Put("Two", "Two");
a.Put(Attributes.InternalKey("another"), "example.com");
IEnumerator<TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute> it = a.GetEnumerator();
NUnit.Framework.Assert.IsTrue(it.MoveNext());
NUnit.Framework.Assert.AreEqual("One", it.Current.Key);
NUnit.Framework.Assert.IsTrue(it.MoveNext());
NUnit.Framework.Assert.AreEqual("Two", it.Current.Key);
NUnit.Framework.Assert.IsFalse(it.MoveNext());
int seen = 0;
foreach (TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute attribute in a) {
seen++;
}
NUnit.Framework.Assert.AreEqual(2, seen);
}
[NUnit.Framework.Test]
public virtual void TestListSkipsInternal() {
Attributes a = new Attributes();
a.Put("One", "One");
a.Put(Attributes.InternalKey("baseUri"), "example.com");
a.Put("Two", "Two");
a.Put(Attributes.InternalKey("another"), "example.com");
IList<TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute> attributes = a.AsList();
NUnit.Framework.Assert.AreEqual(2, attributes.Count);
NUnit.Framework.Assert.AreEqual("One", attributes[0].Key);
NUnit.Framework.Assert.AreEqual("Two", attributes[1].Key);
}
[NUnit.Framework.Test]
public virtual void HtmlSkipsInternals() {
Attributes a = new Attributes();
a.Put("One", "One");
a.Put(Attributes.InternalKey("baseUri"), "example.com");
a.Put("Two", "Two");
a.Put(Attributes.InternalKey("another"), "example.com");
NUnit.Framework.Assert.AreEqual(" One=\"One\" Two=\"Two\"", a.Html());
}
[NUnit.Framework.Test]
public virtual void TestIteratorEmpty() {
Attributes a = new Attributes();
IEnumerator<TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute> iterator = a.GetEnumerator();
NUnit.Framework.Assert.IsFalse(iterator.MoveNext());
}
[NUnit.Framework.Test]
public virtual void RemoveCaseSensitive() {
Attributes a = new Attributes();
a.Put("Tot", "a&p");
a.Put("tot", "one");
a.Put("Hello", "There");
a.Put("hello", "There");
a.Put("data-name", "Jsoup");
NUnit.Framework.Assert.AreEqual(5, a.Size());
a.Remove("Tot");
a.Remove("Hello");
NUnit.Framework.Assert.AreEqual(3, a.Size());
NUnit.Framework.Assert.IsTrue(a.HasKey("tot"));
NUnit.Framework.Assert.IsFalse(a.HasKey("Tot"));
}
[NUnit.Framework.Test]
public virtual void TestSetKeyConsistency() {
Attributes a = new Attributes();
a.Put("a", "a");
foreach (TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute at in a) {
at.SetKey("b");
}
NUnit.Framework.Assert.IsFalse(a.HasKey("a"));
NUnit.Framework.Assert.IsTrue(a.HasKey("b"));
}
[NUnit.Framework.Test]
public virtual void TestBoolean() {
Attributes ats = new Attributes();
ats.Put("a", "a");
ats.Put("B", "b");
ats.Put("c", null);
NUnit.Framework.Assert.IsTrue(ats.HasDeclaredValueForKey("a"));
NUnit.Framework.Assert.IsFalse(ats.HasDeclaredValueForKey("A"));
NUnit.Framework.Assert.IsTrue(ats.HasDeclaredValueForKeyIgnoreCase("A"));
NUnit.Framework.Assert.IsFalse(ats.HasDeclaredValueForKey("c"));
NUnit.Framework.Assert.IsFalse(ats.HasDeclaredValueForKey("C"));
NUnit.Framework.Assert.IsFalse(ats.HasDeclaredValueForKeyIgnoreCase("C"));
}
[NUnit.Framework.Test]
public virtual void TestSizeWhenHasInternal() {
Attributes a = new Attributes();
a.Put("One", "One");
a.Put("Two", "Two");
NUnit.Framework.Assert.AreEqual(2, a.Size());
a.Put(Attributes.InternalKey("baseUri"), "example.com");
a.Put(Attributes.InternalKey("another"), "example.com");
NUnit.Framework.Assert.AreEqual(2, a.Size());
}
}
}

View File

@@ -0,0 +1,85 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Nodes {
[NUnit.Framework.Category("UnitTest")]
public class CommentTest : ExtendedTSpdfTest {
private Comment comment = new Comment(" This is one heck of a comment! ");
private Comment decl = new Comment("?xml encoding='ISO-8859-1'?");
[NUnit.Framework.Test]
public virtual void NodeName() {
NUnit.Framework.Assert.AreEqual("#comment", comment.NodeName());
}
[NUnit.Framework.Test]
public virtual void GetData() {
NUnit.Framework.Assert.AreEqual(" This is one heck of a comment! ", comment.GetData());
}
[NUnit.Framework.Test]
public virtual void TestToString() {
NUnit.Framework.Assert.AreEqual("<!-- This is one heck of a comment! -->", comment.ToString());
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><!-- comment--></div>");
NUnit.Framework.Assert.AreEqual("<div>\n <!-- comment-->\n</div>", doc.Body().Html());
doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p>One<!-- comment -->Two</p>");
NUnit.Framework.Assert.AreEqual("<p>One<!-- comment -->Two</p>", doc.Body().Html());
NUnit.Framework.Assert.AreEqual("OneTwo", doc.Text());
}
[NUnit.Framework.Test]
public virtual void TestHtmlNoPretty() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<!-- a simple comment -->");
doc.OutputSettings().PrettyPrint(false);
NUnit.Framework.Assert.AreEqual("<!-- a simple comment --><html><head></head><body></body></html>", doc.Html
());
TSpdf.StyledXmlParser.Jsoup.Nodes.Node node = doc.ChildNode(0);
Comment c1 = (Comment)node;
NUnit.Framework.Assert.AreEqual("<!-- a simple comment -->", c1.OuterHtml());
}
[NUnit.Framework.Test]
public virtual void TestClone() {
Comment c1 = (Comment)comment.Clone();
NUnit.Framework.Assert.AreNotSame(comment, c1);
NUnit.Framework.Assert.AreEqual(comment.GetData(), comment.GetData());
c1.SetData("New");
NUnit.Framework.Assert.AreEqual("New", c1.GetData());
NUnit.Framework.Assert.AreNotEqual(c1.GetData(), comment.GetData());
}
[NUnit.Framework.Test]
public virtual void IsXmlDeclaration() {
NUnit.Framework.Assert.IsFalse(comment.IsXmlDeclaration());
NUnit.Framework.Assert.IsTrue(decl.IsXmlDeclaration());
}
[NUnit.Framework.Test]
public virtual void AsXmlDeclaration() {
XmlDeclaration xmlDeclaration = decl.AsXmlDeclaration();
NUnit.Framework.Assert.IsNotNull(xmlDeclaration);
}
}
}

View File

@@ -0,0 +1,451 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.IO;
using System.Text;
using System.Threading;
using TSpdf.Commons.Utils;
using TSpdf.StyledXmlParser.Jsoup;
using TSpdf.StyledXmlParser.Jsoup.Parser;
using TSpdf.StyledXmlParser.Jsoup.Select;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Nodes {
/// <summary>Tests for Document.</summary>
/// <author>Jonathan Hedley, jonathan@hedley.net</author>
[NUnit.Framework.Category("UnitTest")]
public class DocumentTest : ExtendedTSpdfTest {
private const String charsetUtf8 = "UTF-8";
private const String charsetIso8859 = "ISO-8859-1";
[NUnit.Framework.Test]
public virtual void SetTextPreservesDocumentStructure() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p>Hello</p>");
doc.Text("Replaced");
NUnit.Framework.Assert.AreEqual("Replaced", doc.Text());
NUnit.Framework.Assert.AreEqual("Replaced", doc.Body().Text());
NUnit.Framework.Assert.AreEqual(1, doc.Select("head").Count);
}
[NUnit.Framework.Test]
public virtual void TestTitles() {
Document noTitle = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p>Hello</p>");
Document withTitle = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<title>First</title><title>Ignore</title><p>Hello</p>"
);
NUnit.Framework.Assert.AreEqual("", noTitle.Title());
noTitle.Title("Hello");
NUnit.Framework.Assert.AreEqual("Hello", noTitle.Title());
NUnit.Framework.Assert.AreEqual("Hello", noTitle.Select("title").First().Text());
NUnit.Framework.Assert.AreEqual("First", withTitle.Title());
withTitle.Title("Hello");
NUnit.Framework.Assert.AreEqual("Hello", withTitle.Title());
NUnit.Framework.Assert.AreEqual("Hello", withTitle.Select("title").First().Text());
Document normaliseTitle = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<title> Hello\nthere \n now \n"
);
NUnit.Framework.Assert.AreEqual("Hello there now", normaliseTitle.Title());
}
[NUnit.Framework.Test]
public virtual void TestOutputEncoding() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p title=π>π & < > </p>");
// default is utf-8
NUnit.Framework.Assert.AreEqual("<p title=\"π\">π &amp; &lt; &gt; </p>", doc.Body().Html());
NUnit.Framework.Assert.AreEqual("UTF-8", doc.OutputSettings().Charset().Name());
doc.OutputSettings().Charset("ascii");
NUnit.Framework.Assert.AreEqual(Entities.EscapeMode.@base, doc.OutputSettings().EscapeMode());
NUnit.Framework.Assert.AreEqual("<p title=\"&#x3c0;\">&#x3c0; &amp; &lt; &gt; </p>", doc.Body().Html());
doc.OutputSettings().EscapeMode(Entities.EscapeMode.extended);
NUnit.Framework.Assert.AreEqual("<p title=\"&pi;\">&pi; &amp; &lt; &gt; </p>", doc.Body().Html());
}
[NUnit.Framework.Test]
public virtual void TestXhtmlReferences() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("&lt; &gt; &amp; &quot; &apos; &times;");
doc.OutputSettings().EscapeMode(Entities.EscapeMode.xhtml);
NUnit.Framework.Assert.AreEqual("&lt; &gt; &amp; \" ' ×", doc.Body().Html());
}
[NUnit.Framework.Test]
public virtual void TestNormalisesStructure() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<html><head><script>one</script><noscript><p>two</p></noscript></head><body><p>three</p></body><p>four</p></html>"
);
NUnit.Framework.Assert.AreEqual("<html><head><script>one</script><noscript>&lt;p&gt;two</noscript></head><body><p>three</p><p>four</p></body></html>"
, TextUtil.StripNewlines(doc.Html()));
}
[NUnit.Framework.Test]
public virtual void AccessorsWillNormalizeStructure() {
Document doc = new Document("");
NUnit.Framework.Assert.AreEqual("", doc.Html());
TSpdf.StyledXmlParser.Jsoup.Nodes.Element body = doc.Body();
NUnit.Framework.Assert.AreEqual("body", body.TagName());
TSpdf.StyledXmlParser.Jsoup.Nodes.Element head = doc.Head();
NUnit.Framework.Assert.AreEqual("head", head.TagName());
NUnit.Framework.Assert.AreEqual("<html><head></head><body></body></html>", TextUtil.StripNewlines(doc.Html
()));
}
[NUnit.Framework.Test]
public virtual void AccessorsAreCaseInsensitive() {
TSpdf.StyledXmlParser.Jsoup.Parser.Parser parser = TSpdf.StyledXmlParser.Jsoup.Parser.Parser.HtmlParser().
Settings(ParseSettings.preserveCase);
Document doc = parser.ParseInput("<!DOCTYPE html><HTML><HEAD><TITLE>SHOUTY</TITLE></HEAD><BODY>HELLO</BODY></HTML>"
, "");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element body = doc.Body();
NUnit.Framework.Assert.AreEqual("BODY", body.TagName());
NUnit.Framework.Assert.AreEqual("body", body.NormalName());
TSpdf.StyledXmlParser.Jsoup.Nodes.Element head = doc.Head();
NUnit.Framework.Assert.AreEqual("HEAD", head.TagName());
NUnit.Framework.Assert.AreEqual("body", body.NormalName());
TSpdf.StyledXmlParser.Jsoup.Nodes.Element root = doc.SelectFirst("html");
NUnit.Framework.Assert.AreEqual("HTML", root.TagName());
NUnit.Framework.Assert.AreEqual("html", root.NormalName());
NUnit.Framework.Assert.AreEqual("SHOUTY", doc.Title());
}
[NUnit.Framework.Test]
public virtual void TestClone() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<title>Hello</title> <p>One<p>Two");
Document clone = (Document)doc.Clone();
NUnit.Framework.Assert.AreEqual("<html><head><title>Hello</title> </head><body><p>One</p><p>Two</p></body></html>"
, TextUtil.StripNewlines(clone.Html()));
clone.Title("Hello there");
clone.Select("p").First().Text("One more").Attr("id", "1");
NUnit.Framework.Assert.AreEqual("<html><head><title>Hello there</title> </head><body><p id=\"1\">One more</p><p>Two</p></body></html>"
, TextUtil.StripNewlines(clone.Html()));
NUnit.Framework.Assert.AreEqual("<html><head><title>Hello</title> </head><body><p>One</p><p>Two</p></body></html>"
, TextUtil.StripNewlines(doc.Html()));
}
[NUnit.Framework.Test]
public virtual void TestClonesDeclarations() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<!DOCTYPE html><html><head><title>Doctype test");
Document clone = (Document)doc.Clone();
NUnit.Framework.Assert.AreEqual(doc.Html(), clone.Html());
NUnit.Framework.Assert.AreEqual("<!doctype html><html><head><title>Doctype test</title></head><body></body></html>"
, TextUtil.StripNewlines(clone.Html()));
}
[NUnit.Framework.Test]
public virtual void TestLocationFromString() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p>Hello");
NUnit.Framework.Assert.AreEqual("", doc.Location());
}
[NUnit.Framework.Test]
public virtual void TestHtmlAndXmlSyntax() {
String h = "<!DOCTYPE html><body><img async checked='checked' src='&<>\"'>&lt;&gt;&amp;&quot;<foo />bar";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
doc.OutputSettings().Syntax(TSpdf.StyledXmlParser.Jsoup.Nodes.Syntax.html);
NUnit.Framework.Assert.AreEqual("<!doctype html>\n" + "<html>\n" + " <head></head>\n" + " <body>\n" + " <img async checked src=\"&amp;<>&quot;\">&lt;&gt;&amp;\"<foo />bar\n"
+ " </body>\n" + "</html>", doc.Html());
doc.OutputSettings().Syntax(TSpdf.StyledXmlParser.Jsoup.Nodes.Syntax.xml);
NUnit.Framework.Assert.AreEqual("<!DOCTYPE html>\n" + "<html>\n" + " <head></head>\n" + " <body>\n" + " <img async=\"\" checked=\"checked\" src=\"&amp;&lt;>&quot;\" />&lt;&gt;&amp;\"<foo />bar\n"
+ " </body>\n" + "</html>", doc.Html());
}
[NUnit.Framework.Test]
public virtual void HtmlParseDefaultsToHtmlOutputSyntax() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("x");
NUnit.Framework.Assert.AreEqual(TSpdf.StyledXmlParser.Jsoup.Nodes.Syntax.html, doc.OutputSettings().Syntax
());
}
[NUnit.Framework.Test]
public virtual void TestHtmlAppendable() {
String htmlContent = "<html><head><title>Hello</title></head><body><p>One</p><p>Two</p></body></html>";
Document document = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(htmlContent);
OutputSettings outputSettings = new OutputSettings();
outputSettings.PrettyPrint(false);
document.OutputSettings(outputSettings);
NUnit.Framework.Assert.AreEqual(htmlContent, document.Html(new StringBuilder()).ToString());
}
[NUnit.Framework.Test]
public virtual void TestOverflowClone() {
StringBuilder sb = new StringBuilder();
sb.Append("<head><base href='https://jsoup.org/'>");
for (int i = 0; i < 100000; i++) {
sb.Append("<div>");
}
sb.Append("<p>Hello <a href='/example.html'>there</a>");
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(sb.ToString());
String expectedLink = "https://jsoup.org/example.html";
NUnit.Framework.Assert.AreEqual(expectedLink, doc.SelectFirst("a").Attr("abs:href"));
Document clone = (Document)doc.Clone();
doc.HasSameValue(clone);
NUnit.Framework.Assert.AreEqual(expectedLink, clone.SelectFirst("a").Attr("abs:href"));
}
[NUnit.Framework.Test]
public virtual void DocumentsWithSameContentAreEqual() {
Document docA = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div/>One");
Document docB = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div/>One");
Document docC = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div/>Two");
NUnit.Framework.Assert.AreNotEqual(docA, docB);
NUnit.Framework.Assert.AreEqual(docA, docA);
NUnit.Framework.Assert.AreEqual(docA.GetHashCode(), docA.GetHashCode());
NUnit.Framework.Assert.AreNotEqual(docA.GetHashCode(), docC.GetHashCode());
}
[NUnit.Framework.Test]
public virtual void DocumentsWithSameContentAreVerifiable() {
Document docA = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div/>One");
Document docB = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div/>One");
Document docC = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div/>Two");
NUnit.Framework.Assert.IsTrue(docA.HasSameValue(docB));
NUnit.Framework.Assert.IsFalse(docA.HasSameValue(docC));
}
[NUnit.Framework.Test]
public virtual void TestMetaCharsetUpdateUtf8() {
Document doc = CreateHtmlDocument("changeThis");
doc.UpdateMetaCharsetElement(true);
doc.Charset(EncodingUtil.GetEncoding(charsetUtf8));
String htmlCharsetUTF8 = "<html>\n" + " <head>\n" + " <meta charset=\"" + charsetUtf8 + "\">\n" + " </head>\n"
+ " <body></body>\n" + "</html>";
NUnit.Framework.Assert.AreEqual(htmlCharsetUTF8, doc.ToString());
TSpdf.StyledXmlParser.Jsoup.Nodes.Element selectedElement = doc.Select("meta[charset]").First();
NUnit.Framework.Assert.AreEqual(charsetUtf8, doc.Charset().Name());
NUnit.Framework.Assert.AreEqual(charsetUtf8, selectedElement.Attr("charset"));
NUnit.Framework.Assert.AreEqual(doc.Charset(), doc.OutputSettings().Charset());
}
[NUnit.Framework.Test]
public virtual void TestMetaCharsetUpdateIso8859() {
Document doc = CreateHtmlDocument("changeThis");
doc.UpdateMetaCharsetElement(true);
doc.Charset(EncodingUtil.GetEncoding(charsetIso8859));
String htmlCharsetISO = "<html>\n" + " <head>\n" + " <meta charset=\"" + charsetIso8859 + "\">\n" + " </head>\n"
+ " <body></body>\n" + "</html>";
NUnit.Framework.Assert.AreEqual(htmlCharsetISO, doc.ToString());
TSpdf.StyledXmlParser.Jsoup.Nodes.Element selectedElement = doc.Select("meta[charset]").First();
NUnit.Framework.Assert.AreEqual(charsetIso8859, doc.Charset().Name());
NUnit.Framework.Assert.AreEqual(charsetIso8859, selectedElement.Attr("charset"));
NUnit.Framework.Assert.AreEqual(doc.Charset(), doc.OutputSettings().Charset());
}
[NUnit.Framework.Test]
public virtual void TestMetaCharsetUpdateNoCharset() {
Document docNoCharset = Document.CreateShell("");
docNoCharset.UpdateMetaCharsetElement(true);
docNoCharset.Charset(EncodingUtil.GetEncoding(charsetUtf8));
NUnit.Framework.Assert.AreEqual(charsetUtf8, docNoCharset.Select("meta[charset]").First().Attr("charset"));
String htmlCharsetUTF8 = "<html>\n" + " <head>\n" + " <meta charset=\"" + charsetUtf8 + "\">\n" + " </head>\n"
+ " <body></body>\n" + "</html>";
NUnit.Framework.Assert.AreEqual(htmlCharsetUTF8, docNoCharset.ToString());
}
[NUnit.Framework.Test]
public virtual void TestMetaCharsetUpdateDisabled() {
Document docDisabled = Document.CreateShell("");
String htmlNoCharset = "<html>\n" + " <head></head>\n" + " <body></body>\n" + "</html>";
NUnit.Framework.Assert.AreEqual(htmlNoCharset, docDisabled.ToString());
NUnit.Framework.Assert.IsNull(docDisabled.Select("meta[charset]").First());
}
[NUnit.Framework.Test]
public virtual void TestMetaCharsetUpdateDisabledNoChanges() {
Document doc = CreateHtmlDocument("dontTouch");
String htmlCharset = "<html>\n" + " <head>\n" + " <meta charset=\"dontTouch\">\n" + " <meta name=\"charset\" content=\"dontTouch\">\n"
+ " </head>\n" + " <body></body>\n" + "</html>";
NUnit.Framework.Assert.AreEqual(htmlCharset, doc.ToString());
TSpdf.StyledXmlParser.Jsoup.Nodes.Element selectedElement = doc.Select("meta[charset]").First();
NUnit.Framework.Assert.IsNotNull(selectedElement);
NUnit.Framework.Assert.AreEqual("dontTouch", selectedElement.Attr("charset"));
selectedElement = doc.Select("meta[name=charset]").First();
NUnit.Framework.Assert.IsNotNull(selectedElement);
NUnit.Framework.Assert.AreEqual("dontTouch", selectedElement.Attr("content"));
}
[NUnit.Framework.Test]
public virtual void TestMetaCharsetUpdateEnabledAfterCharsetChange() {
Document doc = CreateHtmlDocument("dontTouch");
doc.Charset(EncodingUtil.GetEncoding(charsetUtf8));
TSpdf.StyledXmlParser.Jsoup.Nodes.Element selectedElement = doc.Select("meta[charset]").First();
NUnit.Framework.Assert.AreEqual(charsetUtf8, selectedElement.Attr("charset"));
NUnit.Framework.Assert.IsTrue(doc.Select("meta[name=charset]").IsEmpty());
}
[NUnit.Framework.Test]
public virtual void TestMetaCharsetUpdateCleanup() {
Document doc = CreateHtmlDocument("dontTouch");
doc.UpdateMetaCharsetElement(true);
doc.Charset(EncodingUtil.GetEncoding(charsetUtf8));
String htmlCharsetUTF8 = "<html>\n" + " <head>\n" + " <meta charset=\"" + charsetUtf8 + "\">\n" + " </head>\n"
+ " <body></body>\n" + "</html>";
NUnit.Framework.Assert.AreEqual(htmlCharsetUTF8, doc.ToString());
}
[NUnit.Framework.Test]
public virtual void TestMetaCharsetUpdateXmlUtf8() {
Document doc = CreateXmlDocument("1.0", "changeThis", true);
doc.UpdateMetaCharsetElement(true);
doc.Charset(EncodingUtil.GetEncoding(charsetUtf8));
String xmlCharsetUTF8 = "<?xml version=\"1.0\" encoding=\"" + charsetUtf8 + "\"?>\n" + "<root>\n" + " node\n"
+ "</root>";
NUnit.Framework.Assert.AreEqual(xmlCharsetUTF8, doc.ToString());
XmlDeclaration selectedNode = (XmlDeclaration)doc.ChildNode(0);
NUnit.Framework.Assert.AreEqual(charsetUtf8, doc.Charset().Name());
NUnit.Framework.Assert.AreEqual(charsetUtf8, selectedNode.Attr("encoding"));
NUnit.Framework.Assert.AreEqual(doc.Charset(), doc.OutputSettings().Charset());
}
[NUnit.Framework.Test]
public virtual void TestMetaCharsetUpdateXmlIso8859() {
Document doc = CreateXmlDocument("1.0", "changeThis", true);
doc.UpdateMetaCharsetElement(true);
doc.Charset(EncodingUtil.GetEncoding(charsetIso8859));
String xmlCharsetISO = "<?xml version=\"1.0\" encoding=\"" + charsetIso8859 + "\"?>\n" + "<root>\n" + " node\n"
+ "</root>";
NUnit.Framework.Assert.AreEqual(xmlCharsetISO, doc.ToString());
XmlDeclaration selectedNode = (XmlDeclaration)doc.ChildNode(0);
NUnit.Framework.Assert.AreEqual(charsetIso8859, doc.Charset().Name());
NUnit.Framework.Assert.AreEqual(charsetIso8859, selectedNode.Attr("encoding"));
NUnit.Framework.Assert.AreEqual(doc.Charset(), doc.OutputSettings().Charset());
}
[NUnit.Framework.Test]
public virtual void TestMetaCharsetUpdateXmlNoCharset() {
Document doc = CreateXmlDocument("1.0", "none", false);
doc.UpdateMetaCharsetElement(true);
doc.Charset(EncodingUtil.GetEncoding(charsetUtf8));
String xmlCharsetUTF8 = "<?xml version=\"1.0\" encoding=\"" + charsetUtf8 + "\"?>\n" + "<root>\n" + " node\n"
+ "</root>";
NUnit.Framework.Assert.AreEqual(xmlCharsetUTF8, doc.ToString());
XmlDeclaration selectedNode = (XmlDeclaration)doc.ChildNode(0);
NUnit.Framework.Assert.AreEqual(charsetUtf8, selectedNode.Attr("encoding"));
}
[NUnit.Framework.Test]
public virtual void TestMetaCharsetUpdateXmlDisabled() {
Document doc = CreateXmlDocument("none", "none", false);
String xmlNoCharset = "<root>\n" + " node\n" + "</root>";
NUnit.Framework.Assert.AreEqual(xmlNoCharset, doc.ToString());
}
[NUnit.Framework.Test]
public virtual void TestMetaCharsetUpdateXmlDisabledNoChanges() {
Document doc = CreateXmlDocument("dontTouch", "dontTouch", true);
String xmlCharset = "<?xml version=\"dontTouch\" encoding=\"dontTouch\"?>\n" + "<root>\n" + " node\n" + "</root>";
NUnit.Framework.Assert.AreEqual(xmlCharset, doc.ToString());
XmlDeclaration selectedNode = (XmlDeclaration)doc.ChildNode(0);
NUnit.Framework.Assert.AreEqual("dontTouch", selectedNode.Attr("encoding"));
NUnit.Framework.Assert.AreEqual("dontTouch", selectedNode.Attr("version"));
}
[NUnit.Framework.Test]
public virtual void TestMetaCharsetUpdatedDisabledPerDefault() {
Document doc = CreateHtmlDocument("none");
NUnit.Framework.Assert.IsFalse(doc.UpdateMetaCharsetElement());
}
private Document CreateHtmlDocument(String charset) {
Document doc = Document.CreateShell("");
doc.Head().AppendElement("meta").Attr("charset", charset);
doc.Head().AppendElement("meta").Attr("name", "charset").Attr("content", charset);
return doc;
}
private Document CreateXmlDocument(String version, String charset, bool addDecl) {
Document doc = new Document("");
doc.AppendElement("root").Text("node");
doc.OutputSettings().Syntax(TSpdf.StyledXmlParser.Jsoup.Nodes.Syntax.xml);
if (addDecl) {
XmlDeclaration decl = new XmlDeclaration("xml", false);
decl.Attr("version", version);
decl.Attr("encoding", charset);
doc.PrependChild(decl);
}
return doc;
}
[NUnit.Framework.Test]
public virtual void TestShiftJisRoundtrip() {
String input = "<html>" + "<head>" + "<meta http-equiv=\"content-type\" content=\"text/html; charset=Shift_JIS\" />"
+ "</head>" + "<body>" + "before&nbsp;after" + "</body>" + "</html>";
Stream @is = new MemoryStream(input.GetBytes(System.Text.Encoding.ASCII));
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@is, null, "http://example.com");
doc.OutputSettings().EscapeMode(Entities.EscapeMode.xhtml);
String output = TSpdf.Commons.Utils.JavaUtil.GetStringForBytes(doc.Html().GetBytes(doc.OutputSettings().Charset
()), doc.OutputSettings().Charset());
NUnit.Framework.Assert.IsFalse(output.Contains("?"));
NUnit.Framework.Assert.IsTrue(output.Contains("&#xa0;") || output.Contains("&nbsp;"));
}
[NUnit.Framework.Test]
public virtual void ParseAndHtmlOnDifferentThreads() {
String html = "<p>Alrighty then it's not \uD83D\uDCA9. <span>Next</span></p>";
// 💩
String asci = "<p>Alrighty then it's not &#x1f4a9;. <span>Next</span></p>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
String[] @out = new String[1];
Elements p = doc.Select("p");
NUnit.Framework.Assert.AreEqual(html, p.OuterHtml());
Thread thread = new Thread(() => {
@out[0] = p.OuterHtml();
doc.OutputSettings().Charset(System.Text.Encoding.ASCII);
}
);
thread.Start();
thread.Join();
NUnit.Framework.Assert.AreEqual(html, @out[0]);
NUnit.Framework.Assert.AreEqual(System.Text.Encoding.ASCII, doc.OutputSettings().Charset());
NUnit.Framework.Assert.AreEqual(asci, p.OuterHtml());
}
[NUnit.Framework.Test]
public virtual void TestDocumentTypeGet() {
String html = "\n\n<!-- comment --> <!doctype html><p>One</p>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
DocumentType documentType = doc.DocumentType();
NUnit.Framework.Assert.IsNotNull(documentType);
NUnit.Framework.Assert.AreEqual("html", documentType.Name());
}
[NUnit.Framework.Test]
public virtual void FramesetSupportsBodyMethod() {
String html = "<html><head><title>Frame Test</title></head><frameset id=id><frame src=foo.html></frameset>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element head = doc.Head();
NUnit.Framework.Assert.IsNotNull(head);
NUnit.Framework.Assert.AreEqual("Frame Test", doc.Title());
// Frameset docs per html5 spec have no body element - but instead a frameset elelemt
NUnit.Framework.Assert.IsNull(doc.SelectFirst("body"));
TSpdf.StyledXmlParser.Jsoup.Nodes.Element frameset = doc.SelectFirst("frameset");
NUnit.Framework.Assert.IsNotNull(frameset);
// the body() method returns body or frameset and does not otherwise modify the document
// doing it in body() vs parse keeps the html close to original for round-trip option
TSpdf.StyledXmlParser.Jsoup.Nodes.Element body = doc.Body();
NUnit.Framework.Assert.IsNotNull(body);
NUnit.Framework.Assert.AreSame(frameset, body);
NUnit.Framework.Assert.AreEqual("frame", body.Child(0).TagName());
NUnit.Framework.Assert.IsNull(doc.SelectFirst("body"));
// did not vivify a body element
String expected = "<html>\n" + " <head>\n" + " <title>Frame Test</title>\n" + " </head>\n" + " <frameset id=\"id\">\n"
+ " <frame src=\"foo.html\">\n" + " </frameset>\n" + "</html>";
NUnit.Framework.Assert.AreEqual(expected, doc.Html());
}
}
}

View File

@@ -0,0 +1,90 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Nodes {
/// <summary>Tests for the DocumentType node</summary>
/// <author>Jonathan Hedley, http://jonathanhedley.com/</author>
[NUnit.Framework.Category("UnitTest")]
public class DocumentTypeTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void ConstructorValidationOkWithBlankName() {
NUnit.Framework.Assert.DoesNotThrow(() => new DocumentType("", "", ""));
}
[NUnit.Framework.Test]
public virtual void ConstructorValidationThrowsExceptionOnNulls() {
NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => new DocumentType("html", null, null));
}
[NUnit.Framework.Test]
public virtual void ConstructorValidationOkWithBlankPublicAndSystemIds() {
NUnit.Framework.Assert.DoesNotThrow(() => new DocumentType("html", "", ""));
}
[NUnit.Framework.Test]
public virtual void OuterHtmlGeneration() {
DocumentType html5 = new DocumentType("html", "", "");
NUnit.Framework.Assert.AreEqual("<!doctype html>", html5.OuterHtml());
DocumentType publicDocType = new DocumentType("html", "-//IETF//DTD HTML//", "");
NUnit.Framework.Assert.AreEqual("<!DOCTYPE html PUBLIC \"-//IETF//DTD HTML//\">", publicDocType.OuterHtml(
));
DocumentType systemDocType = new DocumentType("html", "", "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd"
);
NUnit.Framework.Assert.AreEqual("<!DOCTYPE html SYSTEM \"http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd\">"
, systemDocType.OuterHtml());
DocumentType combo = new DocumentType("notHtml", "--public", "--system");
NUnit.Framework.Assert.AreEqual("<!DOCTYPE notHtml PUBLIC \"--public\" \"--system\">", combo.OuterHtml());
NUnit.Framework.Assert.AreEqual("notHtml", combo.Name());
NUnit.Framework.Assert.AreEqual("--public", combo.PublicId());
NUnit.Framework.Assert.AreEqual("--system", combo.SystemId());
}
[NUnit.Framework.Test]
public virtual void TestRoundTrip() {
String @base = "<!DOCTYPE html>";
NUnit.Framework.Assert.AreEqual("<!doctype html>", HtmlOutput(@base));
NUnit.Framework.Assert.AreEqual(@base, XmlOutput(@base));
String publicDoc = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
NUnit.Framework.Assert.AreEqual(publicDoc, HtmlOutput(publicDoc));
NUnit.Framework.Assert.AreEqual(publicDoc, XmlOutput(publicDoc));
String systemDoc = "<!DOCTYPE html SYSTEM \"exampledtdfile.dtd\">";
NUnit.Framework.Assert.AreEqual(systemDoc, HtmlOutput(systemDoc));
NUnit.Framework.Assert.AreEqual(systemDoc, XmlOutput(systemDoc));
String legacyDoc = "<!DOCTYPE html SYSTEM \"about:legacy-compat\">";
NUnit.Framework.Assert.AreEqual(legacyDoc, HtmlOutput(legacyDoc));
NUnit.Framework.Assert.AreEqual(legacyDoc, XmlOutput(legacyDoc));
}
private String HtmlOutput(String @in) {
DocumentType type = (DocumentType)TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in).ChildNode(0);
return type.OuterHtml();
}
private String XmlOutput(String @in) {
return TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(@in, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser.XmlParser
()).ChildNode(0).OuterHtml();
}
}
}

View File

@@ -0,0 +1,90 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Text;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Nodes {
[NUnit.Framework.Category("UnitTest")]
public class ElementItTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void TestFastReparent() {
StringBuilder htmlBuf = new StringBuilder();
int rows = 300000;
for (int i = 1; i <= rows; i++) {
htmlBuf.Append("<p>El-").Append(i).Append("</p>");
}
String html = htmlBuf.ToString();
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
long start = System.DateTime.Now.Ticks;
TSpdf.StyledXmlParser.Jsoup.Nodes.Element wrapper = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element("div");
IList<TSpdf.StyledXmlParser.Jsoup.Nodes.Node> childNodes = doc.Body().ChildNodes();
wrapper.InsertChildren(0, childNodes);
long runtime = (System.DateTime.Now.Ticks - start) / 1000000;
NUnit.Framework.Assert.AreEqual(rows, wrapper.childNodes.Count);
NUnit.Framework.Assert.AreEqual(rows, childNodes.Count);
// child nodes is a wrapper, so still there
NUnit.Framework.Assert.AreEqual(0, doc.Body().ChildNodes().Count);
// but on a fresh look, all gone
((TSpdf.StyledXmlParser.Jsoup.Nodes.Element)doc.Body().Empty()).AppendChild(wrapper);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element wrapperAcutal = doc.Body().Children()[0];
NUnit.Framework.Assert.AreEqual(wrapper, wrapperAcutal);
NUnit.Framework.Assert.AreEqual("El-1", wrapperAcutal.Children()[0].Text());
NUnit.Framework.Assert.AreEqual("El-" + rows, wrapperAcutal.Children()[rows - 1].Text());
NUnit.Framework.Assert.IsTrue(runtime <= 10000);
}
[NUnit.Framework.Test]
public virtual void TestFastReparentExistingContent() {
StringBuilder htmlBuf = new StringBuilder();
int rows = 300000;
for (int i = 1; i <= rows; i++) {
htmlBuf.Append("<p>El-").Append(i).Append("</p>");
}
String html = htmlBuf.ToString();
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
long start = System.DateTime.Now.Ticks;
TSpdf.StyledXmlParser.Jsoup.Nodes.Element wrapper = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element("div");
wrapper.Append("<p>Prior Content</p>");
wrapper.Append("<p>End Content</p>");
NUnit.Framework.Assert.AreEqual(2, wrapper.childNodes.Count);
IList<TSpdf.StyledXmlParser.Jsoup.Nodes.Node> childNodes = doc.Body().ChildNodes();
wrapper.InsertChildren(1, childNodes);
long runtime = (System.DateTime.Now.Ticks - start) / 1000000;
NUnit.Framework.Assert.AreEqual(rows + 2, wrapper.childNodes.Count);
NUnit.Framework.Assert.AreEqual(rows, childNodes.Count);
// child nodes is a wrapper, so still there
NUnit.Framework.Assert.AreEqual(0, doc.Body().ChildNodes().Count);
// but on a fresh look, all gone
((TSpdf.StyledXmlParser.Jsoup.Nodes.Element)doc.Body().Empty()).AppendChild(wrapper);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element wrapperAcutal = doc.Body().Children()[0];
NUnit.Framework.Assert.AreEqual(wrapper, wrapperAcutal);
NUnit.Framework.Assert.AreEqual("Prior Content", wrapperAcutal.Children()[0].Text());
NUnit.Framework.Assert.AreEqual("El-1", wrapperAcutal.Children()[1].Text());
NUnit.Framework.Assert.AreEqual("El-" + rows, wrapperAcutal.Children()[rows].Text());
NUnit.Framework.Assert.AreEqual("End Content", wrapperAcutal.Children()[rows + 1].Text());
NUnit.Framework.Assert.IsTrue(runtime <= 10000);
}
}
}

View File

@@ -0,0 +1,193 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Nodes {
[NUnit.Framework.Category("UnitTest")]
public class EntitiesTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void Escape() {
String text = "Hello &<> Å å π 新 there ¾ © »";
String escapedAscii = Entities.Escape(text, new OutputSettings().Charset("ascii").EscapeMode(Entities.EscapeMode
.@base));
String escapedAsciiFull = Entities.Escape(text, new OutputSettings().Charset("ascii").EscapeMode(Entities.EscapeMode
.extended));
String escapedAsciiXhtml = Entities.Escape(text, new OutputSettings().Charset("ascii").EscapeMode(Entities.EscapeMode
.xhtml));
String escapedUtfFull = Entities.Escape(text, new OutputSettings().Charset("UTF-8").EscapeMode(Entities.EscapeMode
.extended));
String escapedUtfMin = Entities.Escape(text, new OutputSettings().Charset("UTF-8").EscapeMode(Entities.EscapeMode
.xhtml));
NUnit.Framework.Assert.AreEqual("Hello &amp;&lt;&gt; &Aring; &aring; &#x3c0; &#x65b0; there &frac34; &copy; &raquo;"
, escapedAscii);
NUnit.Framework.Assert.AreEqual("Hello &amp;&lt;&gt; &angst; &aring; &pi; &#x65b0; there &frac34; &copy; &raquo;"
, escapedAsciiFull);
NUnit.Framework.Assert.AreEqual("Hello &amp;&lt;&gt; &#xc5; &#xe5; &#x3c0; &#x65b0; there &#xbe; &#xa9; &#xbb;"
, escapedAsciiXhtml);
NUnit.Framework.Assert.AreEqual("Hello &amp;&lt;&gt; Å å π 新 there ¾ © »", escapedUtfFull);
NUnit.Framework.Assert.AreEqual("Hello &amp;&lt;&gt; Å å π 新 there ¾ © »", escapedUtfMin);
// odd that it's defined as aring in base but angst in full
// round trip
NUnit.Framework.Assert.AreEqual(text, Entities.Unescape(escapedAscii));
NUnit.Framework.Assert.AreEqual(text, Entities.Unescape(escapedAsciiFull));
NUnit.Framework.Assert.AreEqual(text, Entities.Unescape(escapedAsciiXhtml));
NUnit.Framework.Assert.AreEqual(text, Entities.Unescape(escapedUtfFull));
NUnit.Framework.Assert.AreEqual(text, Entities.Unescape(escapedUtfMin));
}
[NUnit.Framework.Test]
public virtual void EscapedSupplementary() {
String text = "\uD835\uDD59";
String escapedAscii = Entities.Escape(text, new OutputSettings().Charset("ascii").EscapeMode(Entities.EscapeMode
.@base));
NUnit.Framework.Assert.AreEqual("&#x1d559;", escapedAscii);
String escapedAsciiFull = Entities.Escape(text, new OutputSettings().Charset("ascii").EscapeMode(Entities.EscapeMode
.extended));
NUnit.Framework.Assert.AreEqual("&hopf;", escapedAsciiFull);
String escapedUtf = Entities.Escape(text, new OutputSettings().Charset("UTF-8").EscapeMode(Entities.EscapeMode
.extended));
NUnit.Framework.Assert.AreEqual(text, escapedUtf);
}
[NUnit.Framework.Test]
public virtual void UnescapeMultiChars() {
String text = "&NestedGreaterGreater; &nGg; &nGt; &nGtv; &Gt; &gg;";
// gg is not combo, but 8811 could conflict with NestedGreaterGreater or others
String un = "≫ ⋙̸ ≫⃒ ≫̸ ≫ ≫";
NUnit.Framework.Assert.AreEqual(un, Entities.Unescape(text));
String escaped = Entities.Escape(un, new OutputSettings().Charset("ascii").EscapeMode(Entities.EscapeMode.
extended));
NUnit.Framework.Assert.AreEqual("&Gt; &Gg;&#x338; &Gt;&#x20d2; &Gt;&#x338; &Gt; &Gt;", escaped);
NUnit.Framework.Assert.AreEqual(un, Entities.Unescape(escaped));
}
[NUnit.Framework.Test]
public virtual void Xhtml() {
NUnit.Framework.Assert.AreEqual(38, Entities.EscapeMode.xhtml.CodepointForName("amp"));
NUnit.Framework.Assert.AreEqual(62, Entities.EscapeMode.xhtml.CodepointForName("gt"));
NUnit.Framework.Assert.AreEqual(60, Entities.EscapeMode.xhtml.CodepointForName("lt"));
NUnit.Framework.Assert.AreEqual(34, Entities.EscapeMode.xhtml.CodepointForName("quot"));
NUnit.Framework.Assert.AreEqual("amp", Entities.EscapeMode.xhtml.NameForCodepoint(38));
NUnit.Framework.Assert.AreEqual("gt", Entities.EscapeMode.xhtml.NameForCodepoint(62));
NUnit.Framework.Assert.AreEqual("lt", Entities.EscapeMode.xhtml.NameForCodepoint(60));
NUnit.Framework.Assert.AreEqual("quot", Entities.EscapeMode.xhtml.NameForCodepoint(34));
}
[NUnit.Framework.Test]
public virtual void GetByName() {
NUnit.Framework.Assert.AreEqual("≫⃒", Entities.GetByName("nGt"));
NUnit.Framework.Assert.AreEqual("fj", Entities.GetByName("fjlig"));
NUnit.Framework.Assert.AreEqual("≫", Entities.GetByName("gg"));
NUnit.Framework.Assert.AreEqual("©", Entities.GetByName("copy"));
}
[NUnit.Framework.Test]
public virtual void EscapeSupplementaryCharacter() {
String text = new String(TSpdf.IO.Util.TextUtil.ToChars(135361));
String escapedAscii = Entities.Escape(text, new OutputSettings().Charset("ascii").EscapeMode(Entities.EscapeMode
.@base));
NUnit.Framework.Assert.AreEqual("&#x210c1;", escapedAscii);
String escapedUtf = Entities.Escape(text, new OutputSettings().Charset("UTF-8").EscapeMode(Entities.EscapeMode
.@base));
NUnit.Framework.Assert.AreEqual(text, escapedUtf);
}
[NUnit.Framework.Test]
public virtual void NotMissingMultis() {
String text = "&nparsl;";
String un = "\u2AFD\u20E5";
NUnit.Framework.Assert.AreEqual(un, Entities.Unescape(text));
}
[NUnit.Framework.Test]
public virtual void NotMissingSupplementals() {
String text = "&npolint; &qfr;";
String un = "⨔ \uD835\uDD2E";
// 𝔮
NUnit.Framework.Assert.AreEqual(un, Entities.Unescape(text));
}
[NUnit.Framework.Test]
public virtual void Unescape() {
String text = "Hello &AElig; &amp;&LT&gt; &reg &angst; &angst &#960; &#960 &#x65B0; there &! &frac34; &copy; &COPY;";
NUnit.Framework.Assert.AreEqual("Hello Æ &<> ® Å &angst π π 新 there &! ¾ © ©", Entities.Unescape(text));
NUnit.Framework.Assert.AreEqual("&0987654321; &unknown", Entities.Unescape("&0987654321; &unknown"));
}
[NUnit.Framework.Test]
public virtual void StrictUnescape() {
// for attributes, enforce strict unescaping (must look like &#xxx; , not just &#xxx)
String text = "Hello &amp= &amp;";
NUnit.Framework.Assert.AreEqual("Hello &amp= &", Entities.Unescape(text, true));
NUnit.Framework.Assert.AreEqual("Hello &= &", Entities.Unescape(text));
NUnit.Framework.Assert.AreEqual("Hello &= &", Entities.Unescape(text, false));
}
[NUnit.Framework.Test]
public virtual void CaseSensitive() {
String unescaped = "Ü ü & &";
NUnit.Framework.Assert.AreEqual("&Uuml; &uuml; &amp; &amp;", Entities.Escape(unescaped, new OutputSettings
().Charset("ascii").EscapeMode(Entities.EscapeMode.extended)));
String escaped = "&Uuml; &uuml; &amp; &AMP";
NUnit.Framework.Assert.AreEqual("Ü ü & &", Entities.Unescape(escaped));
}
[NUnit.Framework.Test]
public virtual void QuoteReplacements() {
String escaped = "&#92; &#36;";
String unescaped = "\\ $";
NUnit.Framework.Assert.AreEqual(unescaped, Entities.Unescape(escaped));
}
[NUnit.Framework.Test]
public virtual void LetterDigitEntities() {
String html = "<p>&sup1;&sup2;&sup3;&frac14;&frac12;&frac34;</p>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
doc.OutputSettings().Charset("ascii");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element p = doc.Select("p").First();
NUnit.Framework.Assert.AreEqual("&sup1;&sup2;&sup3;&frac14;&frac12;&frac34;", p.Html());
NUnit.Framework.Assert.AreEqual("¹²³¼½¾", p.Text());
doc.OutputSettings().Charset("UTF-8");
NUnit.Framework.Assert.AreEqual("¹²³¼½¾", p.Html());
}
[NUnit.Framework.Test]
public virtual void NoSpuriousDecodes() {
String @string = "http://www.foo.com?a=1&num_rooms=1&children=0&int=VA&b=2";
NUnit.Framework.Assert.AreEqual(@string, Entities.Unescape(@string));
}
[NUnit.Framework.Test]
public virtual void EscapesGtInXmlAttributesButNotInHtml() {
// https://github.com/jhy/jsoup/issues/528 - < is OK in HTML attribute values, but not in XML
String docHtml = "<a title='<p>One</p>'>One</a>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(docHtml);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element element = doc.Select("a").First();
doc.OutputSettings().EscapeMode(Entities.EscapeMode.@base);
NUnit.Framework.Assert.AreEqual("<a title=\"<p>One</p>\">One</a>", element.OuterHtml());
doc.OutputSettings().EscapeMode(Entities.EscapeMode.xhtml);
NUnit.Framework.Assert.AreEqual("<a title=\"&lt;p>One&lt;/p>\">One</a>", element.OuterHtml());
}
}
}

View File

@@ -0,0 +1,139 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.StyledXmlParser.Jsoup.Helper;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Nodes {
/// <summary>Tests for FormElement</summary>
/// <author>Jonathan Hedley</author>
[NUnit.Framework.Category("UnitTest")]
public class FormElementTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void HasAssociatedControls() {
//"button", "fieldset", "input", "keygen", "object", "output", "select", "textarea"
String html = "<form id=1><button id=1><fieldset id=2 /><input id=3><keygen id=4><object id=5><output id=6>"
+ "<select id=7><option></select><textarea id=8><p id=9>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
FormElement form = (FormElement)doc.Select("form").First();
NUnit.Framework.Assert.AreEqual(8, form.Elements().Count);
}
[NUnit.Framework.Test]
public virtual void CreatesFormData() {
String html = "<form><input name='one' value='two'><select name='three'><option value='not'>" + "<option value='four' selected><option value='five' selected><textarea name=six>seven</textarea>"
+ "<input name='seven' type='radio' value='on' checked><input name='seven' type='radio' value='off'>"
+ "<input name='eight' type='checkbox' checked><input name='nine' type='checkbox' value='unset'>" + "<input name='ten' value='text' disabled>"
+ "<input name='eleven' value='text' type='button'>" + "</form>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
FormElement form = (FormElement)doc.Select("form").First();
IList<KeyVal> data = form.FormData();
NUnit.Framework.Assert.AreEqual(6, data.Count);
NUnit.Framework.Assert.AreEqual("one=two", data[0].ToString());
NUnit.Framework.Assert.AreEqual("three=four", data[1].ToString());
NUnit.Framework.Assert.AreEqual("three=five", data[2].ToString());
NUnit.Framework.Assert.AreEqual("six=seven", data[3].ToString());
NUnit.Framework.Assert.AreEqual("seven=on", data[4].ToString());
// set
NUnit.Framework.Assert.AreEqual("eight=on", data[5].ToString());
}
// default
// nine should not appear, not checked checkbox
// ten should not appear, disabled
// eleven should not appear, button
[NUnit.Framework.Test]
public virtual void FormDataUsesFirstAttribute() {
String html = "<form><input name=test value=foo name=test2 value=bar>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
FormElement form = (FormElement)doc.SelectFirst("form");
NUnit.Framework.Assert.AreEqual("test=foo", form.FormData()[0].ToString());
}
[NUnit.Framework.Test]
public virtual void FormsAddedAfterParseAreFormElements() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<body />");
doc.Body().Html("<form action='http://example.com/search'><input name='q' value='search'>");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element formEl = doc.Select("form").First();
NUnit.Framework.Assert.IsTrue(formEl is FormElement);
FormElement form = (FormElement)formEl;
NUnit.Framework.Assert.AreEqual(1, form.Elements().Count);
}
[NUnit.Framework.Test]
public virtual void ControlsAddedAfterParseAreLinkedWithForms() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<body />");
doc.Body().Html("<form />");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element formEl = doc.Select("form").First();
formEl.Append("<input name=foo value=bar>");
NUnit.Framework.Assert.IsTrue(formEl is FormElement);
FormElement form = (FormElement)formEl;
NUnit.Framework.Assert.AreEqual(1, form.Elements().Count);
IList<KeyVal> data = form.FormData();
NUnit.Framework.Assert.AreEqual("foo=bar", data[0].ToString());
}
[NUnit.Framework.Test]
public virtual void UsesOnForCheckboxValueIfNoValueSet() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<form><input type=checkbox checked name=foo></form>"
);
FormElement form = (FormElement)doc.Select("form").First();
IList<KeyVal> data = form.FormData();
NUnit.Framework.Assert.AreEqual("on", data[0].Value());
NUnit.Framework.Assert.AreEqual("foo", data[0].Key());
}
[NUnit.Framework.Test]
public virtual void AdoptedFormsRetainInputs() {
// test for https://github.com/jhy/jsoup/issues/249
String html = "<html>\n" + "<body> \n" + " <table>\n" + " <form action=\"/hello.php\" method=\"post\">\n"
+ " <tr><td>User:</td><td> <input type=\"text\" name=\"user\" /></td></tr>\n" + " <tr><td>Password:</td><td> <input type=\"password\" name=\"pass\" /></td></tr>\n"
+ " <tr><td><input type=\"submit\" name=\"login\" value=\"login\" /></td></tr>\n" + " </form>\n"
+ " </table>\n" + "</body>\n" + "</html>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
FormElement form = (FormElement)doc.Select("form").First();
IList<KeyVal> data = form.FormData();
NUnit.Framework.Assert.AreEqual(3, data.Count);
NUnit.Framework.Assert.AreEqual("user", data[0].Key());
NUnit.Framework.Assert.AreEqual("pass", data[1].Key());
NUnit.Framework.Assert.AreEqual("login", data[2].Key());
}
[NUnit.Framework.Test]
public virtual void RemoveFormElement() {
String html = "<html>\n" + " <body> \n" + " <form action=\"/hello.php\" method=\"post\">\n" + " User:<input type=\"text\" name=\"user\" />\n"
+ " Password:<input type=\"password\" name=\"pass\" />\n" + " <input type=\"submit\" name=\"login\" value=\"login\" />\n"
+ " </form>\n" + " </body>\n" + "</html> ";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
FormElement form = (FormElement)doc.SelectFirst("form");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element pass = form.SelectFirst("input[name=pass]");
pass.Remove();
IList<KeyVal> data = form.FormData();
NUnit.Framework.Assert.AreEqual(2, data.Count);
NUnit.Framework.Assert.AreEqual("user", data[0].Key());
NUnit.Framework.Assert.AreEqual("login", data[1].Key());
NUnit.Framework.Assert.IsNull(doc.SelectFirst("input[name=pass]"));
}
}
}

View File

@@ -0,0 +1,91 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.StyledXmlParser.Jsoup.Select;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Nodes {
[NUnit.Framework.Category("UnitTest")]
public class LeafNodeTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void DoesNotGetAttributesTooEasily() {
// test to make sure we're not setting attributes on all nodes right away
String body = "<p>One <!-- Two --> Three<![CDATA[Four]]></p>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(body);
NUnit.Framework.Assert.IsTrue(HasAnyAttributes(doc));
// should have one - the base uri on the doc
TSpdf.StyledXmlParser.Jsoup.Nodes.Element html = doc.Child(0);
NUnit.Framework.Assert.IsFalse(HasAnyAttributes(html));
String s = doc.OuterHtml();
NUnit.Framework.Assert.IsFalse(HasAnyAttributes(html));
Elements els = doc.Select("p");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element p = els.First();
NUnit.Framework.Assert.AreEqual(1, els.Count);
NUnit.Framework.Assert.IsFalse(HasAnyAttributes(html));
els = doc.Select("p.none");
NUnit.Framework.Assert.IsFalse(HasAnyAttributes(html));
String id = p.Id();
NUnit.Framework.Assert.AreEqual("", id);
NUnit.Framework.Assert.IsFalse(p.HasClass("Foobs"));
NUnit.Framework.Assert.IsFalse(HasAnyAttributes(html));
p.AddClass("Foobs");
NUnit.Framework.Assert.IsTrue(p.HasClass("Foobs"));
NUnit.Framework.Assert.IsTrue(HasAnyAttributes(html));
NUnit.Framework.Assert.IsTrue(HasAnyAttributes(p));
Attributes attributes = p.Attributes();
NUnit.Framework.Assert.IsTrue(attributes.HasKey("class"));
p.ClearAttributes();
NUnit.Framework.Assert.IsFalse(HasAnyAttributes(p));
NUnit.Framework.Assert.IsFalse(HasAnyAttributes(html));
NUnit.Framework.Assert.IsFalse(attributes.HasKey("class"));
}
private bool HasAnyAttributes(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node) {
bool[] found = new bool[1];
node.Filter(new _NodeFilter_78(found));
return found[0];
}
private sealed class _NodeFilter_78 : NodeFilter {
public _NodeFilter_78(bool[] found) {
this.found = found;
}
public override NodeFilter.FilterResult Head(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
if (node.HasAttributes()) {
found[0] = true;
return NodeFilter.FilterResult.STOP;
}
else {
return NodeFilter.FilterResult.CONTINUE;
}
}
public override NodeFilter.FilterResult Tail(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
return NodeFilter.FilterResult.CONTINUE;
}
private readonly bool[] found;
}
}
}

View File

@@ -0,0 +1,369 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Text;
using TSpdf.StyledXmlParser.Jsoup;
using TSpdf.StyledXmlParser.Jsoup.Select;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Nodes {
/// <summary>Tests Nodes</summary>
/// <author>Jonathan Hedley, jonathan@hedley.net</author>
[NUnit.Framework.Category("UnitTest")]
public class NodeTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void HandlesBaseUri() {
TSpdf.StyledXmlParser.Jsoup.Parser.Tag tag = TSpdf.StyledXmlParser.Jsoup.Parser.Tag.ValueOf("a");
Attributes attribs = new Attributes();
attribs.Put("relHref", "/foo");
attribs.Put("absHref", "http://bar/qux");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element noBase = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element(tag, "",
attribs);
NUnit.Framework.Assert.AreEqual("", noBase.AbsUrl("relHref"));
// with no base, should NOT fallback to href attrib, whatever it is
NUnit.Framework.Assert.AreEqual("http://bar/qux", noBase.AbsUrl("absHref"));
// no base but valid attrib, return attrib
TSpdf.StyledXmlParser.Jsoup.Nodes.Element withBase = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element(tag, "http://foo/"
, attribs);
NUnit.Framework.Assert.AreEqual("http://foo/foo", withBase.AbsUrl("relHref"));
// construct abs from base + rel
NUnit.Framework.Assert.AreEqual("http://bar/qux", withBase.AbsUrl("absHref"));
// href is abs, so returns that
NUnit.Framework.Assert.AreEqual("", withBase.AbsUrl("noval"));
TSpdf.StyledXmlParser.Jsoup.Nodes.Element dodgyBase = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element(tag, "fff://no-such-protocol/"
, attribs);
NUnit.Framework.Assert.AreEqual("http://bar/qux", dodgyBase.AbsUrl("absHref"));
}
// base fails, but href good, so get that
[NUnit.Framework.Test]
public virtual void SetBaseUriIsRecursive() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p></p></div>");
String baseUri = "https://jsoup.org";
doc.SetBaseUri(baseUri);
NUnit.Framework.Assert.AreEqual(baseUri, doc.BaseUri());
NUnit.Framework.Assert.AreEqual(baseUri, doc.Select("div").First().BaseUri());
NUnit.Framework.Assert.AreEqual(baseUri, doc.Select("p").First().BaseUri());
}
[NUnit.Framework.Test]
public virtual void HandlesAbsPrefix() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<a href=/foo>Hello</a>", "https://jsoup.org/");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element a = doc.Select("a").First();
NUnit.Framework.Assert.AreEqual("/foo", a.Attr("href"));
NUnit.Framework.Assert.AreEqual("https://jsoup.org/foo", a.Attr("abs:href"));
NUnit.Framework.Assert.IsTrue(a.HasAttr("abs:href"));
}
[NUnit.Framework.Test]
public virtual void HandlesAbsOnImage() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p><img src=\"/rez/osi_logo.png\" /></p>", "https://jsoup.org/"
);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element img = doc.Select("img").First();
NUnit.Framework.Assert.AreEqual("https://jsoup.org/rez/osi_logo.png", img.Attr("abs:src"));
NUnit.Framework.Assert.AreEqual(img.AbsUrl("src"), img.Attr("abs:src"));
}
[NUnit.Framework.Test]
public virtual void HandlesAbsPrefixOnHasAttr() {
// 1: no abs url; 2: has abs url
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<a id=1 href='/foo'>One</a> <a id=2 href='https://jsoup.org/'>Two</a>"
);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element one = doc.Select("#1").First();
TSpdf.StyledXmlParser.Jsoup.Nodes.Element two = doc.Select("#2").First();
NUnit.Framework.Assert.IsFalse(one.HasAttr("abs:href"));
NUnit.Framework.Assert.IsTrue(one.HasAttr("href"));
NUnit.Framework.Assert.AreEqual("", one.AbsUrl("href"));
NUnit.Framework.Assert.IsTrue(two.HasAttr("abs:href"));
NUnit.Framework.Assert.IsTrue(two.HasAttr("href"));
NUnit.Framework.Assert.AreEqual("https://jsoup.org/", two.AbsUrl("href"));
}
[NUnit.Framework.Test]
public virtual void LiteralAbsPrefix() {
// if there is a literal attribute "abs:xxx", don't try and make absolute.
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<a abs:href='odd'>One</a>");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el = doc.Select("a").First();
NUnit.Framework.Assert.IsTrue(el.HasAttr("abs:href"));
NUnit.Framework.Assert.AreEqual("odd", el.Attr("abs:href"));
}
[NUnit.Framework.Test]
public virtual void HandleAbsOnLocalhostFileUris() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<a href='password'>One/a><a href='/var/log/messages'>Two</a>"
, "file://localhost/etc/");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element one = doc.Select("a").First();
NUnit.Framework.Assert.AreEqual("file://localhost/etc/password", one.AbsUrl("href"));
}
[NUnit.Framework.Test]
public virtual void HandlesAbsOnProtocolessAbsoluteUris() {
Document doc1 = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<a href='//example.net/foo'>One</a>", "http://example.com/"
);
Document doc2 = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<a href='//example.net/foo'>One</a>", "https://example.com/"
);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element one = doc1.Select("a").First();
TSpdf.StyledXmlParser.Jsoup.Nodes.Element two = doc2.Select("a").First();
NUnit.Framework.Assert.AreEqual("http://example.net/foo", one.AbsUrl("href"));
NUnit.Framework.Assert.AreEqual("https://example.net/foo", two.AbsUrl("href"));
Document doc3 = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<img src=//www.google.com/images/errors/logo_sm.gif alt=Google>"
, "https://google.com");
NUnit.Framework.Assert.AreEqual("https://www.google.com/images/errors/logo_sm.gif", doc3.Select("img").Attr
("abs:src"));
}
/*
Test for an issue with Java's abs URL handler.
*/
[NUnit.Framework.Test]
public virtual void AbsHandlesRelativeQuery() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<a href='?foo'>One</a> <a href='bar.html?foo'>Two</a>"
, "https://jsoup.org/path/file?bar");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element a1 = doc.Select("a").First();
NUnit.Framework.Assert.AreEqual("https://jsoup.org/path/file?foo", a1.AbsUrl("href"));
TSpdf.StyledXmlParser.Jsoup.Nodes.Element a2 = doc.Select("a")[1];
NUnit.Framework.Assert.AreEqual("https://jsoup.org/path/bar.html?foo", a2.AbsUrl("href"));
}
[NUnit.Framework.Test]
public virtual void AbsHandlesDotFromIndex() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<a href='./one/two.html'>One</a>", "http://example.com"
);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element a1 = doc.Select("a").First();
NUnit.Framework.Assert.AreEqual("http://example.com/one/two.html", a1.AbsUrl("href"));
}
[NUnit.Framework.Test]
public virtual void TestRemove() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p>One <span>two</span> three</p>");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element p = doc.Select("p").First();
p.ChildNode(0).Remove();
NUnit.Framework.Assert.AreEqual("two three", p.Text());
NUnit.Framework.Assert.AreEqual("<span>two</span> three", TextUtil.StripNewlines(p.Html()));
}
[NUnit.Framework.Test]
public virtual void TestReplace() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p>One <span>two</span> three</p>");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element p = doc.Select("p").First();
TSpdf.StyledXmlParser.Jsoup.Nodes.Element insert = doc.CreateElement("em").Text("foo");
p.ChildNode(1).ReplaceWith(insert);
NUnit.Framework.Assert.AreEqual("One <em>foo</em> three", p.Html());
}
[NUnit.Framework.Test]
public virtual void OwnerDocument() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p>Hello");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element p = doc.Select("p").First();
NUnit.Framework.Assert.AreSame(p.OwnerDocument(), doc);
NUnit.Framework.Assert.AreSame(doc.OwnerDocument(), doc);
NUnit.Framework.Assert.IsNull(doc.Parent());
}
[NUnit.Framework.Test]
public virtual void Root() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>Hello");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element p = doc.Select("p").First();
TSpdf.StyledXmlParser.Jsoup.Nodes.Node root = p.Root();
NUnit.Framework.Assert.AreSame(doc, root);
NUnit.Framework.Assert.IsNull(root.Parent());
NUnit.Framework.Assert.AreSame(doc.Root(), doc);
NUnit.Framework.Assert.AreSame(doc.Root(), doc.OwnerDocument());
TSpdf.StyledXmlParser.Jsoup.Nodes.Element standAlone = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element(TSpdf.StyledXmlParser.Jsoup.Parser.Tag
.ValueOf("p"), "");
NUnit.Framework.Assert.IsNull(standAlone.Parent());
NUnit.Framework.Assert.AreSame(standAlone.Root(), standAlone);
NUnit.Framework.Assert.IsNull(standAlone.OwnerDocument());
}
[NUnit.Framework.Test]
public virtual void Before() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p>One <b>two</b> three</p>");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element newNode = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element(TSpdf.StyledXmlParser.Jsoup.Parser.Tag
.ValueOf("em"), "");
newNode.AppendText("four");
doc.Select("b").First().Before(newNode);
NUnit.Framework.Assert.AreEqual("<p>One <em>four</em><b>two</b> three</p>", doc.Body().Html());
doc.Select("b").First().Before("<i>five</i>");
NUnit.Framework.Assert.AreEqual("<p>One <em>four</em><i>five</i><b>two</b> three</p>", doc.Body().Html());
}
[NUnit.Framework.Test]
public virtual void After() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p>One <b>two</b> three</p>");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element newNode = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element(TSpdf.StyledXmlParser.Jsoup.Parser.Tag
.ValueOf("em"), "");
newNode.AppendText("four");
doc.Select("b").First().After(newNode);
NUnit.Framework.Assert.AreEqual("<p>One <b>two</b><em>four</em> three</p>", doc.Body().Html());
doc.Select("b").First().After("<i>five</i>");
NUnit.Framework.Assert.AreEqual("<p>One <b>two</b><i>five</i><em>four</em> three</p>", doc.Body().Html());
}
[NUnit.Framework.Test]
public virtual void Unwrap() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div>One <span>Two <b>Three</b></span> Four</div>"
);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element span = doc.Select("span").First();
TSpdf.StyledXmlParser.Jsoup.Nodes.Node twoText = span.ChildNode(0);
TSpdf.StyledXmlParser.Jsoup.Nodes.Node node = span.Unwrap();
NUnit.Framework.Assert.AreEqual("<div>One Two <b>Three</b> Four</div>", TextUtil.StripNewlines(doc.Body().
Html()));
NUnit.Framework.Assert.IsTrue(node is TextNode);
NUnit.Framework.Assert.AreEqual("Two ", ((TextNode)node).Text());
NUnit.Framework.Assert.AreEqual(node, twoText);
NUnit.Framework.Assert.AreEqual(node.Parent(), doc.Select("div").First());
}
[NUnit.Framework.Test]
public virtual void UnwrapNoChildren() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div>One <span></span> Two</div>");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element span = doc.Select("span").First();
TSpdf.StyledXmlParser.Jsoup.Nodes.Node node = span.Unwrap();
NUnit.Framework.Assert.AreEqual("<div>One Two</div>", TextUtil.StripNewlines(doc.Body().Html()));
NUnit.Framework.Assert.IsNull(node);
}
[NUnit.Framework.Test]
public virtual void Traverse() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>Hello</p></div><div>There</div>");
StringBuilder accum = new StringBuilder();
doc.Select("div").First().Traverse(new _NodeVisitor_290(accum));
NUnit.Framework.Assert.AreEqual("<div><p><#text></#text></p></div>", accum.ToString());
}
private sealed class _NodeVisitor_290 : NodeVisitor {
public _NodeVisitor_290(StringBuilder accum) {
this.accum = accum;
}
public void Head(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
accum.Append("<").Append(node.NodeName()).Append(">");
}
public void Tail(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
accum.Append("</").Append(node.NodeName()).Append(">");
}
private readonly StringBuilder accum;
}
[NUnit.Framework.Test]
public virtual void OrphanNodeReturnsNullForSiblingElements() {
TSpdf.StyledXmlParser.Jsoup.Nodes.Node node = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element(TSpdf.StyledXmlParser.Jsoup.Parser.Tag
.ValueOf("p"), "");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element(TSpdf.StyledXmlParser.Jsoup.Parser.Tag
.ValueOf("p"), "");
NUnit.Framework.Assert.AreEqual(0, node.SiblingIndex());
NUnit.Framework.Assert.AreEqual(0, node.SiblingNodes().Count);
NUnit.Framework.Assert.IsNull(node.PreviousSibling());
NUnit.Framework.Assert.IsNull(node.NextSibling());
NUnit.Framework.Assert.AreEqual(0, el.SiblingElements().Count);
NUnit.Framework.Assert.IsNull(el.PreviousElementSibling());
NUnit.Framework.Assert.IsNull(el.NextElementSibling());
}
[NUnit.Framework.Test]
public virtual void NodeIsNotASiblingOfItself() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>One<p>Two<p>Three</div>");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element p2 = doc.Select("p")[1];
NUnit.Framework.Assert.AreEqual("Two", p2.Text());
IList<TSpdf.StyledXmlParser.Jsoup.Nodes.Node> nodes = p2.SiblingNodes();
NUnit.Framework.Assert.AreEqual(2, nodes.Count);
NUnit.Framework.Assert.AreEqual("<p>One</p>", nodes[0].OuterHtml());
NUnit.Framework.Assert.AreEqual("<p>Three</p>", nodes[1].OuterHtml());
}
[NUnit.Framework.Test]
public virtual void ChildNodesCopy() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div id=1>Text 1 <p>One</p> Text 2 <p>Two<p>Three</div><div id=2>"
);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element div1 = doc.Select("#1").First();
TSpdf.StyledXmlParser.Jsoup.Nodes.Element div2 = doc.Select("#2").First();
IList<TSpdf.StyledXmlParser.Jsoup.Nodes.Node> divChildren = div1.ChildNodesCopy();
NUnit.Framework.Assert.AreEqual(5, divChildren.Count);
TextNode tn1 = (TextNode)div1.ChildNode(0);
TextNode tn2 = (TextNode)divChildren[0];
tn2.Text("Text 1 updated");
NUnit.Framework.Assert.AreEqual("Text 1 ", tn1.Text());
div2.InsertChildren(-1, divChildren);
NUnit.Framework.Assert.AreEqual("<div id=\"1\">Text 1 <p>One</p> Text 2 <p>Two</p><p>Three</p></div><div id=\"2\">Text 1 updated"
+ "<p>One</p> Text 2 <p>Two</p><p>Three</p></div>", TextUtil.StripNewlines(doc.Body().Html()));
}
[NUnit.Framework.Test]
public virtual void SupportsClone() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div class=foo>Text</div>");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el = doc.Select("div").First();
NUnit.Framework.Assert.IsTrue(el.HasClass("foo"));
TSpdf.StyledXmlParser.Jsoup.Nodes.Element elClone = ((Document)doc.Clone()).Select("div").First();
NUnit.Framework.Assert.IsTrue(elClone.HasClass("foo"));
NUnit.Framework.Assert.AreEqual("Text", elClone.Text());
el.RemoveClass("foo");
el.Text("None");
NUnit.Framework.Assert.IsFalse(el.HasClass("foo"));
NUnit.Framework.Assert.IsTrue(elClone.HasClass("foo"));
NUnit.Framework.Assert.AreEqual("None", el.Text());
NUnit.Framework.Assert.AreEqual("Text", elClone.Text());
}
[NUnit.Framework.Test]
public virtual void ChangingAttributeValueShouldReplaceExistingAttributeCaseInsensitive() {
Document document = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<INPUT id=\"foo\" NAME=\"foo\" VALUE=\"\">");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element inputElement = document.Select("#foo").First();
inputElement.Attr("value", "bar");
NUnit.Framework.Assert.AreEqual(SingletonAttributes(), GetAttributesCaseInsensitive(inputElement));
}
private Attributes GetAttributesCaseInsensitive(TSpdf.StyledXmlParser.Jsoup.Nodes.Element element) {
Attributes matches = new Attributes();
foreach (TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute attribute in element.Attributes()) {
if (attribute.Key.EqualsIgnoreCase("value")) {
matches.Put(attribute);
}
}
return matches;
}
private Attributes SingletonAttributes() {
Attributes attributes = new Attributes();
attributes.Put("value", "bar");
return attributes;
}
private static String CreateAnotherValidUrlVersion(String url) {
if (url.StartsWith("file:///")) {
return "file:/" + url.Substring("file:///".Length);
}
else {
if (url.StartsWith("file:/")) {
return "file:///" + url.Substring("file:/".Length);
}
else {
return url;
}
}
}
}
}

View File

@@ -0,0 +1,179 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.StyledXmlParser.Jsoup;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Nodes {
/// <summary>Test TextNodes</summary>
/// <author>Jonathan Hedley, jonathan@hedley.net</author>
[NUnit.Framework.Category("UnitTest")]
public class TextNodeTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void TestBlank() {
TextNode one = new TextNode("");
TextNode two = new TextNode(" ");
TextNode three = new TextNode(" \n\n ");
TextNode four = new TextNode("Hello");
TextNode five = new TextNode(" \nHello ");
NUnit.Framework.Assert.IsTrue(one.IsBlank());
NUnit.Framework.Assert.IsTrue(two.IsBlank());
NUnit.Framework.Assert.IsTrue(three.IsBlank());
NUnit.Framework.Assert.IsFalse(four.IsBlank());
NUnit.Framework.Assert.IsFalse(five.IsBlank());
}
[NUnit.Framework.Test]
public virtual void TestTextBean() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p>One <span>two &amp;</span> three &amp;</p>");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element p = doc.Select("p").First();
TSpdf.StyledXmlParser.Jsoup.Nodes.Element span = doc.Select("span").First();
NUnit.Framework.Assert.AreEqual("two &", span.Text());
TextNode spanText = (TextNode)span.ChildNode(0);
NUnit.Framework.Assert.AreEqual("two &", spanText.Text());
TextNode tn = (TextNode)p.ChildNode(2);
NUnit.Framework.Assert.AreEqual(" three &", tn.Text());
tn.Text(" POW!");
NUnit.Framework.Assert.AreEqual("One <span>two &amp;</span> POW!", TextUtil.StripNewlines(p.Html()));
tn.Attr(tn.NodeName(), "kablam &");
NUnit.Framework.Assert.AreEqual("kablam &", tn.Text());
NUnit.Framework.Assert.AreEqual("One <span>two &amp;</span>kablam &amp;", TextUtil.StripNewlines(p.Html())
);
}
[NUnit.Framework.Test]
public virtual void TestSplitText() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div>Hello there</div>");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element div = doc.Select("div").First();
TextNode tn = (TextNode)div.ChildNode(0);
TextNode tail = tn.SplitText(6);
NUnit.Framework.Assert.AreEqual("Hello ", tn.GetWholeText());
NUnit.Framework.Assert.AreEqual("there", tail.GetWholeText());
tail.Text("there!");
NUnit.Framework.Assert.AreEqual("Hello there!", div.Text());
NUnit.Framework.Assert.AreSame(tn.Parent(), tail.Parent());
}
[NUnit.Framework.Test]
public virtual void TestSplitAnEmbolden() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div>Hello there</div>");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element div = doc.Select("div").First();
TextNode tn = (TextNode)div.ChildNode(0);
TextNode tail = tn.SplitText(6);
tail.Wrap("<b></b>");
NUnit.Framework.Assert.AreEqual("Hello <b>there</b>", TextUtil.StripNewlines(div.Html()));
}
// not great that we get \n<b>there there... must correct
[NUnit.Framework.Test]
public virtual void TestWithSupplementaryCharacter() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(new String(TSpdf.IO.Util.TextUtil.ToChars(135361)));
TextNode t = doc.Body().TextNodes()[0];
NUnit.Framework.Assert.AreEqual(new String(TSpdf.IO.Util.TextUtil.ToChars(135361)), t.OuterHtml().Trim());
}
[NUnit.Framework.Test]
public virtual void TestLeadNodesHaveNoChildren() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div>Hello there</div>");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element div = doc.Select("div").First();
TextNode tn = (TextNode)div.ChildNode(0);
IList<TSpdf.StyledXmlParser.Jsoup.Nodes.Node> nodes = tn.ChildNodes();
NUnit.Framework.Assert.AreEqual(0, nodes.Count);
}
[NUnit.Framework.Test]
public virtual void TestSpaceNormalise() {
// https://github.com/jhy/jsoup/issues/1309
String whole = "Two spaces";
String norm = "Two spaces";
TextNode tn = new TextNode(whole);
// there are 2 spaces between the words
NUnit.Framework.Assert.AreEqual(whole, tn.GetWholeText());
NUnit.Framework.Assert.AreEqual(norm, tn.Text());
NUnit.Framework.Assert.AreEqual(norm, tn.OuterHtml());
NUnit.Framework.Assert.AreEqual(norm, tn.ToString());
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element("p");
el.AppendChild(tn);
// this used to change the context
//tn.setParentNode(el); // set any parent
NUnit.Framework.Assert.AreEqual(whole, tn.GetWholeText());
NUnit.Framework.Assert.AreEqual(norm, tn.Text());
NUnit.Framework.Assert.AreEqual(norm, tn.OuterHtml());
NUnit.Framework.Assert.AreEqual(norm, tn.ToString());
NUnit.Framework.Assert.AreEqual("<p>" + norm + "</p>", el.OuterHtml());
NUnit.Framework.Assert.AreEqual(norm, el.Html());
NUnit.Framework.Assert.AreEqual(whole, el.WholeText());
}
[NUnit.Framework.Test]
public virtual void TestClone() {
// https://github.com/jhy/jsoup/issues/1176
TextNode x = new TextNode("zzz");
TextNode y = (TextNode)x.Clone();
NUnit.Framework.Assert.AreNotSame(x, y);
NUnit.Framework.Assert.AreEqual(x.OuterHtml(), y.OuterHtml());
y.Text("yyy");
NUnit.Framework.Assert.AreNotEqual(x.OuterHtml(), y.OuterHtml());
NUnit.Framework.Assert.AreEqual("zzz", x.Text());
x.Attributes();
// already cloned so no impact
y.Text("xxx");
NUnit.Framework.Assert.AreEqual("zzz", x.Text());
NUnit.Framework.Assert.AreEqual("xxx", y.Text());
}
[NUnit.Framework.Test]
public virtual void TestCloneAfterAttributesHit() {
// https://github.com/jhy/jsoup/issues/1176
TextNode x = new TextNode("zzz");
x.Attributes();
// moves content from leafnode value to attributes, which were missed in clone
TextNode y = (TextNode)x.Clone();
y.Text("xxx");
NUnit.Framework.Assert.AreEqual("zzz", x.Text());
NUnit.Framework.Assert.AreEqual("xxx", y.Text());
}
[NUnit.Framework.Test]
public virtual void TestHasTextWhenIterating() {
// https://github.com/jhy/jsoup/issues/1170
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div>One <p>Two <p>Three");
bool foundFirst = false;
foreach (TSpdf.StyledXmlParser.Jsoup.Nodes.Element el in doc.GetAllElements()) {
foreach (TSpdf.StyledXmlParser.Jsoup.Nodes.Node node in el.ChildNodes()) {
if (node is TextNode) {
TextNode textNode = (TextNode)node;
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Internal.StringUtil.IsBlank(textNode.Text()));
if (!foundFirst) {
foundFirst = true;
NUnit.Framework.Assert.AreEqual("One ", textNode.Text());
NUnit.Framework.Assert.AreEqual("One ", textNode.GetWholeText());
}
}
}
}
NUnit.Framework.Assert.IsTrue(foundFirst);
}
}
}

View File

@@ -0,0 +1,121 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.StyledXmlParser.Jsoup.Nodes;
using TSpdf.StyledXmlParser.Jsoup.Select;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Parser {
/// <summary>Test suite for attribute parser.</summary>
/// <author>Jonathan Hedley, jonathan@hedley.net</author>
[NUnit.Framework.Category("UnitTest")]
public class AttributeParseTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void ParsesRoughAttributeString() {
String html = "<a id=\"123\" class=\"baz = 'bar'\" style = 'border: 2px'qux zim foo = 12 mux=18 />";
// should be: <id=123>, <class=baz = 'bar'>, <qux=>, <zim=>, <foo=12>, <mux.=18>
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html).GetElementsByTag
("a")[0];
Attributes attr = el.Attributes();
NUnit.Framework.Assert.AreEqual(7, attr.Size());
NUnit.Framework.Assert.AreEqual("123", attr.Get("id"));
NUnit.Framework.Assert.AreEqual("baz = 'bar'", attr.Get("class"));
NUnit.Framework.Assert.AreEqual("border: 2px", attr.Get("style"));
NUnit.Framework.Assert.AreEqual("", attr.Get("qux"));
NUnit.Framework.Assert.AreEqual("", attr.Get("zim"));
NUnit.Framework.Assert.AreEqual("12", attr.Get("foo"));
NUnit.Framework.Assert.AreEqual("18", attr.Get("mux"));
}
[NUnit.Framework.Test]
public virtual void HandlesNewLinesAndReturns() {
String html = "<a\r\nfoo='bar\r\nqux'\r\nbar\r\n=\r\ntwo>One</a>";
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html).Select("a").First
();
NUnit.Framework.Assert.AreEqual(2, el.Attributes().Size());
NUnit.Framework.Assert.AreEqual("bar\r\nqux", el.Attr("foo"));
NUnit.Framework.Assert.AreEqual("two", el.Attr("bar"));
}
[NUnit.Framework.Test]
public virtual void ParsesEmptyString() {
String html = "<a />";
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html).GetElementsByTag
("a")[0];
Attributes attr = el.Attributes();
NUnit.Framework.Assert.AreEqual(0, attr.Size());
}
[NUnit.Framework.Test]
public virtual void CanStartWithEq() {
String html = "<a =empty />";
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html).GetElementsByTag
("a")[0];
Attributes attr = el.Attributes();
NUnit.Framework.Assert.AreEqual(1, attr.Size());
NUnit.Framework.Assert.IsTrue(attr.HasKey("=empty"));
NUnit.Framework.Assert.AreEqual("", attr.Get("=empty"));
}
[NUnit.Framework.Test]
public virtual void StrictAttributeUnescapes() {
String html = "<a id=1 href='?foo=bar&mid&lt=true'>One</a> <a id=2 href='?foo=bar&lt;qux&lg=1'>Two</a>";
Elements els = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html).Select("a");
NUnit.Framework.Assert.AreEqual("?foo=bar&mid&lt=true", els.First().Attr("href"));
NUnit.Framework.Assert.AreEqual("?foo=bar<qux&lg=1", els.Last().Attr("href"));
}
[NUnit.Framework.Test]
public virtual void MoreAttributeUnescapes() {
String html = "<a href='&wr_id=123&mid-size=true&ok=&wr'>Check</a>";
Elements els = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html).Select("a");
NUnit.Framework.Assert.AreEqual("&wr_id=123&mid-size=true&ok=&wr", els.First().Attr("href"));
}
[NUnit.Framework.Test]
public virtual void ParsesBooleanAttributes() {
String html = "<a normal=\"123\" boolean empty=\"\"></a>";
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html).Select("a").First
();
NUnit.Framework.Assert.AreEqual("123", el.Attr("normal"));
NUnit.Framework.Assert.AreEqual("", el.Attr("boolean"));
NUnit.Framework.Assert.AreEqual("", el.Attr("empty"));
IList<TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute> attributes = el.Attributes().AsList();
NUnit.Framework.Assert.AreEqual(3, attributes.Count);
NUnit.Framework.Assert.AreEqual(html, el.OuterHtml());
}
// vets boolean syntax
[NUnit.Framework.Test]
public virtual void DropsSlashFromAttributeName() {
String html = "<img /onerror='doMyJob'/>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
NUnit.Framework.Assert.IsFalse(doc.Select("img[onerror]").IsEmpty());
NUnit.Framework.Assert.AreEqual("<img onerror=\"doMyJob\">", doc.Body().Html());
doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser.XmlParser
());
NUnit.Framework.Assert.AreEqual("<img onerror=\"doMyJob\" />", doc.Html());
}
}
}

View File

@@ -0,0 +1,379 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.IO;
using System.Text;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Parser {
/// <summary>Test suite for character reader.</summary>
/// <author>Jonathan Hedley, jonathan@hedley.net</author>
public class CharacterReaderTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void Consume() {
CharacterReader r = new CharacterReader("one");
NUnit.Framework.Assert.AreEqual(0, r.Pos());
NUnit.Framework.Assert.AreEqual('o', r.Current());
NUnit.Framework.Assert.AreEqual('o', r.Consume());
NUnit.Framework.Assert.AreEqual(1, r.Pos());
NUnit.Framework.Assert.AreEqual('n', r.Current());
NUnit.Framework.Assert.AreEqual(1, r.Pos());
NUnit.Framework.Assert.AreEqual('n', r.Consume());
NUnit.Framework.Assert.AreEqual('e', r.Consume());
NUnit.Framework.Assert.IsTrue(r.IsEmpty());
NUnit.Framework.Assert.AreEqual(CharacterReader.EOF, r.Consume());
NUnit.Framework.Assert.IsTrue(r.IsEmpty());
NUnit.Framework.Assert.AreEqual(CharacterReader.EOF, r.Consume());
}
[NUnit.Framework.Test]
public virtual void Unconsume() {
CharacterReader r = new CharacterReader("one");
NUnit.Framework.Assert.AreEqual('o', r.Consume());
NUnit.Framework.Assert.AreEqual('n', r.Current());
r.Unconsume();
NUnit.Framework.Assert.AreEqual('o', r.Current());
NUnit.Framework.Assert.AreEqual('o', r.Consume());
NUnit.Framework.Assert.AreEqual('n', r.Consume());
NUnit.Framework.Assert.AreEqual('e', r.Consume());
NUnit.Framework.Assert.IsTrue(r.IsEmpty());
r.Unconsume();
NUnit.Framework.Assert.IsFalse(r.IsEmpty());
NUnit.Framework.Assert.AreEqual('e', r.Current());
NUnit.Framework.Assert.AreEqual('e', r.Consume());
NUnit.Framework.Assert.IsTrue(r.IsEmpty());
NUnit.Framework.Assert.AreEqual(CharacterReader.EOF, r.Consume());
r.Unconsume();
// read past, so have to eat again
NUnit.Framework.Assert.IsTrue(r.IsEmpty());
r.Unconsume();
NUnit.Framework.Assert.IsFalse(r.IsEmpty());
NUnit.Framework.Assert.AreEqual('e', r.Consume());
NUnit.Framework.Assert.IsTrue(r.IsEmpty());
NUnit.Framework.Assert.AreEqual(CharacterReader.EOF, r.Consume());
NUnit.Framework.Assert.IsTrue(r.IsEmpty());
}
[NUnit.Framework.Test]
public virtual void Mark() {
CharacterReader r = new CharacterReader("one");
r.Consume();
r.Mark();
NUnit.Framework.Assert.AreEqual(1, r.Pos());
NUnit.Framework.Assert.AreEqual('n', r.Consume());
NUnit.Framework.Assert.AreEqual('e', r.Consume());
NUnit.Framework.Assert.IsTrue(r.IsEmpty());
r.RewindToMark();
NUnit.Framework.Assert.AreEqual(1, r.Pos());
NUnit.Framework.Assert.AreEqual('n', r.Consume());
NUnit.Framework.Assert.IsFalse(r.IsEmpty());
NUnit.Framework.Assert.AreEqual(2, r.Pos());
}
[NUnit.Framework.Test]
public virtual void ConsumeToEnd() {
String @in = "one two three";
CharacterReader r = new CharacterReader(@in);
String toEnd = r.ConsumeToEnd();
NUnit.Framework.Assert.AreEqual(@in, toEnd);
NUnit.Framework.Assert.IsTrue(r.IsEmpty());
}
[NUnit.Framework.Test]
public virtual void NextIndexOfChar() {
String @in = "blah blah";
CharacterReader r = new CharacterReader(@in);
NUnit.Framework.Assert.AreEqual(-1, r.NextIndexOf('x'));
NUnit.Framework.Assert.AreEqual(3, r.NextIndexOf('h'));
String pull = r.ConsumeTo('h');
NUnit.Framework.Assert.AreEqual("bla", pull);
r.Consume();
NUnit.Framework.Assert.AreEqual(2, r.NextIndexOf('l'));
NUnit.Framework.Assert.AreEqual(" blah", r.ConsumeToEnd());
NUnit.Framework.Assert.AreEqual(-1, r.NextIndexOf('x'));
}
[NUnit.Framework.Test]
public virtual void NextIndexOfString() {
String @in = "One Two something Two Three Four";
CharacterReader r = new CharacterReader(@in);
NUnit.Framework.Assert.AreEqual(-1, r.NextIndexOf("Foo"));
NUnit.Framework.Assert.AreEqual(4, r.NextIndexOf("Two"));
NUnit.Framework.Assert.AreEqual("One Two ", r.ConsumeTo("something"));
NUnit.Framework.Assert.AreEqual(10, r.NextIndexOf("Two"));
NUnit.Framework.Assert.AreEqual("something Two Three Four", r.ConsumeToEnd());
NUnit.Framework.Assert.AreEqual(-1, r.NextIndexOf("Two"));
}
[NUnit.Framework.Test]
public virtual void NextIndexOfUnmatched() {
CharacterReader r = new CharacterReader("<[[one]]");
NUnit.Framework.Assert.AreEqual(-1, r.NextIndexOf("]]>"));
}
[NUnit.Framework.Test]
public virtual void ConsumeToChar() {
CharacterReader r = new CharacterReader("One Two Three");
NUnit.Framework.Assert.AreEqual("One ", r.ConsumeTo('T'));
NUnit.Framework.Assert.AreEqual("", r.ConsumeTo('T'));
// on Two
NUnit.Framework.Assert.AreEqual('T', r.Consume());
NUnit.Framework.Assert.AreEqual("wo ", r.ConsumeTo('T'));
NUnit.Framework.Assert.AreEqual('T', r.Consume());
NUnit.Framework.Assert.AreEqual("hree", r.ConsumeTo('T'));
}
// consume to end
[NUnit.Framework.Test]
public virtual void ConsumeToString() {
CharacterReader r = new CharacterReader("One Two Two Four");
NUnit.Framework.Assert.AreEqual("One ", r.ConsumeTo("Two"));
NUnit.Framework.Assert.AreEqual('T', r.Consume());
NUnit.Framework.Assert.AreEqual("wo ", r.ConsumeTo("Two"));
NUnit.Framework.Assert.AreEqual('T', r.Consume());
// To handle strings straddling across buffers, consumeTo() may return the
// data in multiple pieces near EOF.
StringBuilder builder = new StringBuilder();
String part;
do {
part = r.ConsumeTo("Qux");
builder.Append(part);
}
while (!String.IsNullOrEmpty(part));
NUnit.Framework.Assert.AreEqual("wo Four", builder.ToString());
}
[NUnit.Framework.Test]
public virtual void Advance() {
CharacterReader r = new CharacterReader("One Two Three");
NUnit.Framework.Assert.AreEqual('O', r.Consume());
r.Advance();
NUnit.Framework.Assert.AreEqual('e', r.Consume());
}
[NUnit.Framework.Test]
public virtual void ConsumeToAny() {
CharacterReader r = new CharacterReader("One &bar; qux");
NUnit.Framework.Assert.AreEqual("One ", r.ConsumeToAny('&', ';'));
NUnit.Framework.Assert.IsTrue(r.Matches('&'));
NUnit.Framework.Assert.IsTrue(r.Matches("&bar;"));
NUnit.Framework.Assert.AreEqual('&', r.Consume());
NUnit.Framework.Assert.AreEqual("bar", r.ConsumeToAny('&', ';'));
NUnit.Framework.Assert.AreEqual(';', r.Consume());
NUnit.Framework.Assert.AreEqual(" qux", r.ConsumeToAny('&', ';'));
}
[NUnit.Framework.Test]
public virtual void ConsumeLetterSequence() {
CharacterReader r = new CharacterReader("One &bar; qux");
NUnit.Framework.Assert.AreEqual("One", r.ConsumeLetterSequence());
NUnit.Framework.Assert.AreEqual(" &", r.ConsumeTo("bar;"));
NUnit.Framework.Assert.AreEqual("bar", r.ConsumeLetterSequence());
NUnit.Framework.Assert.AreEqual("; qux", r.ConsumeToEnd());
}
[NUnit.Framework.Test]
public virtual void ConsumeLetterThenDigitSequence() {
CharacterReader r = new CharacterReader("One12 Two &bar; qux");
NUnit.Framework.Assert.AreEqual("One12", r.ConsumeLetterThenDigitSequence());
NUnit.Framework.Assert.AreEqual(' ', r.Consume());
NUnit.Framework.Assert.AreEqual("Two", r.ConsumeLetterThenDigitSequence());
NUnit.Framework.Assert.AreEqual(" &bar; qux", r.ConsumeToEnd());
}
[NUnit.Framework.Test]
public virtual void Matches() {
CharacterReader r = new CharacterReader("One Two Three");
NUnit.Framework.Assert.IsTrue(r.Matches('O'));
NUnit.Framework.Assert.IsTrue(r.Matches("One Two Three"));
NUnit.Framework.Assert.IsTrue(r.Matches("One"));
NUnit.Framework.Assert.IsFalse(r.Matches("one"));
NUnit.Framework.Assert.AreEqual('O', r.Consume());
NUnit.Framework.Assert.IsFalse(r.Matches("One"));
NUnit.Framework.Assert.IsTrue(r.Matches("ne Two Three"));
NUnit.Framework.Assert.IsFalse(r.Matches("ne Two Three Four"));
NUnit.Framework.Assert.AreEqual("ne Two Three", r.ConsumeToEnd());
NUnit.Framework.Assert.IsFalse(r.Matches("ne"));
NUnit.Framework.Assert.IsTrue(r.IsEmpty());
}
[NUnit.Framework.Test]
public virtual void MatchesIgnoreCase() {
CharacterReader r = new CharacterReader("One Two Three");
NUnit.Framework.Assert.IsTrue(r.MatchesIgnoreCase("O"));
NUnit.Framework.Assert.IsTrue(r.MatchesIgnoreCase("o"));
NUnit.Framework.Assert.IsTrue(r.Matches('O'));
NUnit.Framework.Assert.IsFalse(r.Matches('o'));
NUnit.Framework.Assert.IsTrue(r.MatchesIgnoreCase("One Two Three"));
NUnit.Framework.Assert.IsTrue(r.MatchesIgnoreCase("ONE two THREE"));
NUnit.Framework.Assert.IsTrue(r.MatchesIgnoreCase("One"));
NUnit.Framework.Assert.IsTrue(r.MatchesIgnoreCase("one"));
NUnit.Framework.Assert.AreEqual('O', r.Consume());
NUnit.Framework.Assert.IsFalse(r.MatchesIgnoreCase("One"));
NUnit.Framework.Assert.IsTrue(r.MatchesIgnoreCase("NE Two Three"));
NUnit.Framework.Assert.IsFalse(r.MatchesIgnoreCase("ne Two Three Four"));
NUnit.Framework.Assert.AreEqual("ne Two Three", r.ConsumeToEnd());
NUnit.Framework.Assert.IsFalse(r.MatchesIgnoreCase("ne"));
}
[NUnit.Framework.Test]
public virtual void ContainsIgnoreCase() {
CharacterReader r = new CharacterReader("One TWO three");
NUnit.Framework.Assert.IsTrue(r.ContainsIgnoreCase("two"));
NUnit.Framework.Assert.IsTrue(r.ContainsIgnoreCase("three"));
// weird one: does not find one, because it scans for consistent case only
NUnit.Framework.Assert.IsFalse(r.ContainsIgnoreCase("one"));
}
[NUnit.Framework.Test]
public virtual void MatchesAny() {
char[] scan = new char[] { ' ', '\n', '\t' };
CharacterReader r = new CharacterReader("One\nTwo\tThree");
NUnit.Framework.Assert.IsFalse(r.MatchesAny(scan));
NUnit.Framework.Assert.AreEqual("One", r.ConsumeToAny(scan));
NUnit.Framework.Assert.IsTrue(r.MatchesAny(scan));
NUnit.Framework.Assert.AreEqual('\n', r.Consume());
NUnit.Framework.Assert.IsFalse(r.MatchesAny(scan));
}
[NUnit.Framework.Test]
public virtual void CachesStrings() {
CharacterReader r = new CharacterReader("Check\tCheck\tCheck\tCHOKE\tA string that is longer than 16 chars"
);
String one = r.ConsumeTo('\t');
r.Consume();
String two = r.ConsumeTo('\t');
r.Consume();
String three = r.ConsumeTo('\t');
r.Consume();
String four = r.ConsumeTo('\t');
r.Consume();
String five = r.ConsumeTo('\t');
NUnit.Framework.Assert.AreEqual("Check", one);
NUnit.Framework.Assert.AreEqual("Check", two);
NUnit.Framework.Assert.AreEqual("Check", three);
NUnit.Framework.Assert.AreEqual("CHOKE", four);
NUnit.Framework.Assert.AreSame(one, two);
NUnit.Framework.Assert.AreSame(two, three);
NUnit.Framework.Assert.AreNotSame(three, four);
NUnit.Framework.Assert.AreNotSame(four, five);
NUnit.Framework.Assert.AreEqual(five, "A string that is longer than 16 chars");
}
[NUnit.Framework.Test]
public virtual void RangeEquals() {
CharacterReader r = new CharacterReader("Check\tCheck\tCheck\tCHOKE");
NUnit.Framework.Assert.IsTrue(r.RangeEquals(0, 5, "Check"));
NUnit.Framework.Assert.IsFalse(r.RangeEquals(0, 5, "CHOKE"));
NUnit.Framework.Assert.IsFalse(r.RangeEquals(0, 5, "Chec"));
NUnit.Framework.Assert.IsTrue(r.RangeEquals(6, 5, "Check"));
NUnit.Framework.Assert.IsFalse(r.RangeEquals(6, 5, "Chuck"));
NUnit.Framework.Assert.IsTrue(r.RangeEquals(12, 5, "Check"));
NUnit.Framework.Assert.IsFalse(r.RangeEquals(12, 5, "Cheeky"));
NUnit.Framework.Assert.IsTrue(r.RangeEquals(18, 5, "CHOKE"));
NUnit.Framework.Assert.IsFalse(r.RangeEquals(18, 5, "CHIKE"));
}
[NUnit.Framework.Test]
public virtual void Empty() {
CharacterReader r = new CharacterReader("One");
NUnit.Framework.Assert.IsTrue(r.MatchConsume("One"));
NUnit.Framework.Assert.IsTrue(r.IsEmpty());
r = new CharacterReader("Two");
String two = r.ConsumeToEnd();
NUnit.Framework.Assert.AreEqual("Two", two);
}
[NUnit.Framework.Test]
public virtual void ConsumeToNonexistentEndWhenAtAnd() {
CharacterReader r = new CharacterReader("<!");
NUnit.Framework.Assert.IsTrue(r.MatchConsume("<!"));
NUnit.Framework.Assert.IsTrue(r.IsEmpty());
String after = r.ConsumeTo('>');
NUnit.Framework.Assert.AreEqual("", after);
NUnit.Framework.Assert.IsTrue(r.IsEmpty());
}
[NUnit.Framework.Test]
public virtual void NotEmptyAtBufferSplitPoint() {
CharacterReader r = new CharacterReader(new StringReader("How about now"), 3);
NUnit.Framework.Assert.AreEqual("How", r.ConsumeTo(' '));
NUnit.Framework.Assert.IsFalse(r.IsEmpty());
NUnit.Framework.Assert.AreEqual(' ', r.Consume());
NUnit.Framework.Assert.IsFalse(r.IsEmpty());
NUnit.Framework.Assert.AreEqual(4, r.Pos());
NUnit.Framework.Assert.AreEqual('a', r.Consume());
NUnit.Framework.Assert.AreEqual(5, r.Pos());
NUnit.Framework.Assert.AreEqual('b', r.Consume());
NUnit.Framework.Assert.AreEqual('o', r.Consume());
NUnit.Framework.Assert.AreEqual('u', r.Consume());
NUnit.Framework.Assert.AreEqual('t', r.Consume());
NUnit.Framework.Assert.AreEqual(' ', r.Consume());
NUnit.Framework.Assert.AreEqual('n', r.Consume());
NUnit.Framework.Assert.AreEqual('o', r.Consume());
NUnit.Framework.Assert.AreEqual('w', r.Consume());
NUnit.Framework.Assert.IsTrue(r.IsEmpty());
}
[NUnit.Framework.Test]
public virtual void BufferUp() {
String note = "HelloThere";
// + ! = 11 chars
int loopCount = 64;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < loopCount; i++) {
sb.Append(note);
sb.Append("!");
}
String s = sb.ToString();
CharacterReader r = new CharacterReader(new StringReader(s));
for (int i = 0; i < loopCount; i++) {
String pull = r.ConsumeTo('!');
NUnit.Framework.Assert.AreEqual(note, pull);
NUnit.Framework.Assert.AreEqual('!', r.Current());
r.Advance();
}
NUnit.Framework.Assert.IsTrue(r.IsEmpty());
}
}
}

View File

@@ -0,0 +1,82 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using TSpdf.Commons.Utils;
using TSpdf.IO.Util;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Parser {
public class HtmlTreeBuilderStateTest : ExtendedTSpdfTest {
internal static IList<Object[]> FindConstantArrays(Type aClass)
{
List<Object[]> array = new List<Object[]>();
FieldInfo[] fields = aClass.GetFields(BindingFlags.NonPublic | BindingFlags.Static);
foreach (FieldInfo field in fields)
{
if (field.IsStatic && !field.IsPrivate && field.FieldType.IsArray)
{
array.Add((Object[]) field.GetValue(null));
}
}
return array;
}
internal static void EnsureSorted(IList<Object[]> constants) {
foreach (Object[] array in constants) {
Object[] copy = JavaUtil.ArraysCopyOf(array, array.Length);
JavaUtil.Sort(array);
NUnit.Framework.Assert.AreEqual(array, copy);
}
}
[NUnit.Framework.Test]
public virtual void EnsureArraysAreSorted() {
IList<Object[]> constants = FindConstantArrays(typeof(HtmlTreeBuilderState.Constants));
EnsureSorted(constants);
NUnit.Framework.Assert.AreEqual(38, constants.Count);
}
[NUnit.Framework.Test]
public virtual void NestedAnchorElements01() {
String html = "<html>\n" + " <body>\n" + " <a href='#1'>\n" + " <div>\n" + " <a href='#2'>child</a>\n"
+ " </div>\n" + " </a>\n" + " </body>\n" + "</html>";
String s = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html).ToString();
NUnit.Framework.Assert.AreEqual("<html> \n" + " <head></head>\n" + " <body> <a href=\"#1\"> </a>\n" + " <div>\n"
+ " <a href=\"#1\"> </a><a href=\"#2\">child</a> \n" + " </div> \n" + " </body>\n" + "</html>",
s);
}
[NUnit.Framework.Test]
public virtual void NestedAnchorElements02() {
String html = "<html>\n" + " <body>\n" + " <a href='#1'>\n" + " <div>\n" + " <div>\n" + " <a href='#2'>child</a>\n"
+ " </div>\n" + " </div>\n" + " </a>\n" + " </body>\n" + "</html>";
String s = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html).ToString();
NUnit.Framework.Assert.AreEqual("<html> \n" + " <head></head>\n" + " <body> <a href=\"#1\"> </a>\n" + " <div>\n"
+ " <a href=\"#1\"> </a>\n" + " <div>\n" + " <a href=\"#1\"> </a><a href=\"#2\">child</a> \n"
+ " </div> \n" + " </div> \n" + " </body>\n" + "</html>", s);
}
}
}

View File

@@ -0,0 +1,106 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using TSpdf.Commons.Utils;
using TSpdf.StyledXmlParser.Jsoup.Nodes;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Parser {
[NUnit.Framework.Category("UnitTest")]
[NUnit.Framework.TestFixtureSource("LocalesTestFixtureData")]
public class MultiLocaleTest : ExtendedTSpdfTest {
private readonly CultureInfo defaultLocale = System.Threading.Thread.CurrentThread.CurrentUICulture;
public static ICollection<CultureInfo> Locales() {
return JavaUtil.ArraysAsList(System.Globalization.CultureInfo.InvariantCulture, new CultureInfo("tr", false
));
}
public static ICollection<NUnit.Framework.TestFixtureData> LocalesTestFixtureData() {
return Locales().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList();
}
[NUnit.Framework.TearDown]
public virtual void SetDefaultLocale() {
System.Threading.Thread.CurrentThread.CurrentUICulture = defaultLocale;
}
private CultureInfo locale;
public MultiLocaleTest(CultureInfo locale) {
this.locale = locale;
}
public MultiLocaleTest(CultureInfo[] array)
: this(array[0]) {
}
[NUnit.Framework.Test]
public virtual void CaseSupport() {
System.Threading.Thread.CurrentThread.CurrentUICulture = locale;
ParseSettings bothOn = new ParseSettings(true, true);
ParseSettings bothOff = new ParseSettings(false, false);
ParseSettings tagOn = new ParseSettings(true, false);
ParseSettings attrOn = new ParseSettings(false, true);
NUnit.Framework.Assert.AreEqual("IMG", bothOn.NormalizeTag("IMG"));
NUnit.Framework.Assert.AreEqual("ID", bothOn.NormalizeAttribute("ID"));
NUnit.Framework.Assert.AreEqual("img", bothOff.NormalizeTag("IMG"));
NUnit.Framework.Assert.AreEqual("id", bothOff.NormalizeAttribute("ID"));
NUnit.Framework.Assert.AreEqual("IMG", tagOn.NormalizeTag("IMG"));
NUnit.Framework.Assert.AreEqual("id", tagOn.NormalizeAttribute("ID"));
NUnit.Framework.Assert.AreEqual("img", attrOn.NormalizeTag("IMG"));
NUnit.Framework.Assert.AreEqual("ID", attrOn.NormalizeAttribute("ID"));
}
[NUnit.Framework.Test]
public virtual void AttributeCaseNormalization() {
System.Threading.Thread.CurrentThread.CurrentUICulture = locale;
ParseSettings parseSettings = new ParseSettings(false, false);
String normalizedAttribute = parseSettings.NormalizeAttribute("HIDDEN");
NUnit.Framework.Assert.AreEqual("hidden", normalizedAttribute);
}
[NUnit.Framework.Test]
public virtual void AttributesCaseNormalization() {
System.Threading.Thread.CurrentThread.CurrentUICulture = locale;
ParseSettings parseSettings = new ParseSettings(false, false);
Attributes attributes = new Attributes();
attributes.Put("ITEM", "1");
Attributes normalizedAttributes = parseSettings.NormalizeAttributes(attributes);
NUnit.Framework.Assert.AreEqual("item", normalizedAttributes.AsList()[0].Key);
}
[NUnit.Framework.Test]
public virtual void CanBeInsensitive() {
System.Threading.Thread.CurrentThread.CurrentUICulture = locale;
TSpdf.StyledXmlParser.Jsoup.Parser.Tag script1 = TSpdf.StyledXmlParser.Jsoup.Parser.Tag.ValueOf("script",
ParseSettings.htmlDefault);
TSpdf.StyledXmlParser.Jsoup.Parser.Tag script2 = TSpdf.StyledXmlParser.Jsoup.Parser.Tag.ValueOf("SCRIPT",
ParseSettings.htmlDefault);
NUnit.Framework.Assert.AreSame(script1, script2);
}
}
}

View File

@@ -0,0 +1,75 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Text;
using NUnit.Framework;
using TSpdf.StyledXmlParser.Jsoup.Nodes;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Parser {
/// <summary>Longer running Parser tests.</summary>
[NUnit.Framework.Category("UnitTest")]
public class ParserItTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void TestIssue1251() {
// https://github.com/jhy/jsoup/issues/1251
String testString = "<a href=\"\"ca";
StringBuilder str = new StringBuilder();
// initial max length of the buffer is 2**15 * 0.75 = 24576
int spacesToReproduceIssue = 24577 - testString.Length;
for (int i = 0; i < spacesToReproduceIssue; i++) {
str.Append(" ");
}
str.Append(testString);
try {
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.HtmlParser().SetTrackErrors(1).ParseInput(str.ToString(), "");
}
catch (Exception e) {
throw new AssertionException("failed at length " + str.Length, e);
}
}
[NUnit.Framework.Test]
public virtual void HandlesDeepStack() {
// inspired by http://sv.stargate.wikia.com/wiki/M2J and https://github.com/jhy/jsoup/issues/955
// I didn't put it in the integration tests, because explorer and intellij kept dieing trying to preview/index it
// Arrange
StringBuilder longBody = new StringBuilder(500000);
for (int i = 0; i < 25000; i++) {
longBody.Append(i).Append("<dl><dd>");
}
for (int i = 0; i < 25000; i++) {
longBody.Append(i).Append("</dd></dl>");
}
// Act
long start = System.DateTime.Now.Ticks;
Document doc = TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseBodyFragment(longBody.ToString(), "");
// Assert
NUnit.Framework.Assert.AreEqual(2, doc.Body().ChildNodeSize());
NUnit.Framework.Assert.AreEqual(25000, doc.Select("dd").Count);
NUnit.Framework.Assert.IsTrue((System.DateTime.Now.Ticks - start) / 1000000 < 20000);
}
// I get ~ 1.5 seconds, but others have reported slower
// was originally much longer, or stack overflow.
}
}

View File

@@ -0,0 +1,48 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Text;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Parser {
[NUnit.Framework.Category("UnitTest")]
public class ParserTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void UnescapeEntities() {
String s = TSpdf.StyledXmlParser.Jsoup.Parser.Parser.UnescapeEntities("One &amp; Two", false);
NUnit.Framework.Assert.AreEqual("One & Two", s);
}
[NUnit.Framework.Test]
public virtual void UnescapeEntitiesHandlesLargeInput() {
StringBuilder longBody = new StringBuilder(500000);
do {
longBody.Append("SomeNonEncodedInput");
}
while (longBody.Length < 64 * 1024);
String body = longBody.ToString();
NUnit.Framework.Assert.AreEqual(body, TSpdf.StyledXmlParser.Jsoup.Parser.Parser.UnescapeEntities(body, false
));
}
}
}

View File

@@ -0,0 +1,103 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Parser {
/// <summary>Tag tests.</summary>
/// <author>Jonathan Hedley, jonathan@hedley.net</author>
[NUnit.Framework.Category("UnitTest")]
public class TagTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void IsCaseSensitive() {
TSpdf.StyledXmlParser.Jsoup.Parser.Tag p1 = TSpdf.StyledXmlParser.Jsoup.Parser.Tag.ValueOf("P");
TSpdf.StyledXmlParser.Jsoup.Parser.Tag p2 = TSpdf.StyledXmlParser.Jsoup.Parser.Tag.ValueOf("p");
NUnit.Framework.Assert.AreNotEqual(p1, p2);
}
[NUnit.Framework.Test]
public virtual void Trims() {
TSpdf.StyledXmlParser.Jsoup.Parser.Tag p1 = TSpdf.StyledXmlParser.Jsoup.Parser.Tag.ValueOf("p");
TSpdf.StyledXmlParser.Jsoup.Parser.Tag p2 = TSpdf.StyledXmlParser.Jsoup.Parser.Tag.ValueOf(" p ");
NUnit.Framework.Assert.AreEqual(p1, p2);
}
[NUnit.Framework.Test]
public virtual void Equality() {
TSpdf.StyledXmlParser.Jsoup.Parser.Tag p1 = TSpdf.StyledXmlParser.Jsoup.Parser.Tag.ValueOf("p");
TSpdf.StyledXmlParser.Jsoup.Parser.Tag p2 = TSpdf.StyledXmlParser.Jsoup.Parser.Tag.ValueOf("p");
NUnit.Framework.Assert.AreEqual(p1, p2);
NUnit.Framework.Assert.AreSame(p1, p2);
}
[NUnit.Framework.Test]
public virtual void DivSemantics() {
TSpdf.StyledXmlParser.Jsoup.Parser.Tag div = TSpdf.StyledXmlParser.Jsoup.Parser.Tag.ValueOf("div");
NUnit.Framework.Assert.IsTrue(div.IsBlock());
NUnit.Framework.Assert.IsTrue(div.FormatAsBlock());
}
[NUnit.Framework.Test]
public virtual void PSemantics() {
TSpdf.StyledXmlParser.Jsoup.Parser.Tag p = TSpdf.StyledXmlParser.Jsoup.Parser.Tag.ValueOf("p");
NUnit.Framework.Assert.IsTrue(p.IsBlock());
NUnit.Framework.Assert.IsFalse(p.FormatAsBlock());
}
[NUnit.Framework.Test]
public virtual void ImgSemantics() {
TSpdf.StyledXmlParser.Jsoup.Parser.Tag img = TSpdf.StyledXmlParser.Jsoup.Parser.Tag.ValueOf("img");
NUnit.Framework.Assert.IsTrue(img.IsInline());
NUnit.Framework.Assert.IsTrue(img.IsSelfClosing());
NUnit.Framework.Assert.IsFalse(img.IsBlock());
}
[NUnit.Framework.Test]
public virtual void DefaultSemantics() {
TSpdf.StyledXmlParser.Jsoup.Parser.Tag foo = TSpdf.StyledXmlParser.Jsoup.Parser.Tag.ValueOf("FOO");
// not defined
TSpdf.StyledXmlParser.Jsoup.Parser.Tag foo2 = TSpdf.StyledXmlParser.Jsoup.Parser.Tag.ValueOf("FOO");
NUnit.Framework.Assert.AreEqual(foo, foo2);
NUnit.Framework.Assert.IsTrue(foo.IsInline());
NUnit.Framework.Assert.IsTrue(foo.FormatAsBlock());
}
[NUnit.Framework.Test]
public virtual void ValueOfChecksNotNull() {
NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => TSpdf.StyledXmlParser.Jsoup.Parser.Tag.ValueOf
(null));
}
[NUnit.Framework.Test]
public virtual void ValueOfChecksNotEmpty() {
NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => TSpdf.StyledXmlParser.Jsoup.Parser.Tag.ValueOf
(" "));
}
[NUnit.Framework.Test]
public virtual void KnownTags() {
NUnit.Framework.Assert.IsTrue(TSpdf.StyledXmlParser.Jsoup.Parser.Tag.IsKnownTag("div"));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Parser.Tag.IsKnownTag("explain"));
}
}
}

View File

@@ -0,0 +1,126 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Parser {
/// <summary>Token queue tests.</summary>
[NUnit.Framework.Category("UnitTest")]
public class TokenQueueTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void ChompBalanced() {
TokenQueue tq = new TokenQueue(":contains(one (two) three) four");
String pre = tq.ConsumeTo("(");
String guts = tq.ChompBalanced('(', ')');
String remainder = tq.Remainder();
NUnit.Framework.Assert.AreEqual(":contains", pre);
NUnit.Framework.Assert.AreEqual("one (two) three", guts);
NUnit.Framework.Assert.AreEqual(" four", remainder);
}
[NUnit.Framework.Test]
public virtual void ChompEscapedBalanced() {
TokenQueue tq = new TokenQueue(":contains(one (two) \\( \\) \\) three) four");
String pre = tq.ConsumeTo("(");
String guts = tq.ChompBalanced('(', ')');
String remainder = tq.Remainder();
NUnit.Framework.Assert.AreEqual(":contains", pre);
NUnit.Framework.Assert.AreEqual("one (two) \\( \\) \\) three", guts);
NUnit.Framework.Assert.AreEqual("one (two) ( ) ) three", TokenQueue.Unescape(guts));
NUnit.Framework.Assert.AreEqual(" four", remainder);
}
[NUnit.Framework.Test]
public virtual void ChompBalancedMatchesAsMuchAsPossible() {
TokenQueue tq = new TokenQueue("unbalanced(something(or another)) else");
tq.ConsumeTo("(");
String match = tq.ChompBalanced('(', ')');
NUnit.Framework.Assert.AreEqual("something(or another)", match);
}
[NUnit.Framework.Test]
public virtual void Unescape() {
NUnit.Framework.Assert.AreEqual("one ( ) \\", TokenQueue.Unescape("one \\( \\) \\\\"));
}
[NUnit.Framework.Test]
public virtual void ChompToIgnoreCase() {
String t = "<textarea>one < two </TEXTarea>";
TokenQueue tq = new TokenQueue(t);
String data = tq.ChompToIgnoreCase("</textarea");
NUnit.Framework.Assert.AreEqual("<textarea>one < two ", data);
tq = new TokenQueue("<textarea> one two < three </oops>");
data = tq.ChompToIgnoreCase("</textarea");
NUnit.Framework.Assert.AreEqual("<textarea> one two < three </oops>", data);
}
[NUnit.Framework.Test]
public virtual void AddFirst() {
TokenQueue tq = new TokenQueue("One Two");
tq.ConsumeWord();
tq.AddFirst("Three");
NUnit.Framework.Assert.AreEqual("Three Two", tq.Remainder());
}
[NUnit.Framework.Test]
public virtual void ConsumeToIgnoreSecondCallTest() {
String t = "<textarea>one < two </TEXTarea> third </TEXTarea>";
TokenQueue tq = new TokenQueue(t);
String data = tq.ChompToIgnoreCase("</textarea>");
NUnit.Framework.Assert.AreEqual("<textarea>one < two ", data);
data = tq.ChompToIgnoreCase("</textarea>");
NUnit.Framework.Assert.AreEqual(" third ", data);
}
[NUnit.Framework.Test]
public virtual void TestNestedQuotes() {
ValidateNestedQuotes("<html><body><a id=\"identifier\" onclick=\"func('arg')\" /></body></html>", "a[onclick*=\"('arg\"]"
);
ValidateNestedQuotes("<html><body><a id=\"identifier\" onclick=func('arg') /></body></html>", "a[onclick*=\"('arg\"]"
);
ValidateNestedQuotes("<html><body><a id=\"identifier\" onclick='func(\"arg\")' /></body></html>", "a[onclick*='(\"arg']"
);
ValidateNestedQuotes("<html><body><a id=\"identifier\" onclick=func(\"arg\") /></body></html>", "a[onclick*='(\"arg']"
);
}
private static void ValidateNestedQuotes(String html, String selector) {
NUnit.Framework.Assert.AreEqual("#identifier", TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html).Select(selector
).First().CssSelector());
}
[NUnit.Framework.Test]
public virtual void ChompBalancedThrowIllegalArgumentException() {
try {
TokenQueue tq = new TokenQueue("unbalanced(something(or another)) else");
tq.ConsumeTo("(");
tq.ChompBalanced('(', '+');
NUnit.Framework.Assert.Fail("should have thrown IllegalArgumentException");
}
catch (ArgumentException expected) {
NUnit.Framework.Assert.AreEqual("Did not find balanced marker at 'something(or another)) else'", expected.
Message);
}
}
}
}

View File

@@ -0,0 +1,727 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Commons.Utils;
using TSpdf.StyledXmlParser.Jsoup;
using TSpdf.StyledXmlParser.Jsoup.Nodes;
using TSpdf.StyledXmlParser.Jsoup.Select;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Parser {
[NUnit.Framework.Category("UnitTest")]
public class TokeniserStateTest : ExtendedTSpdfTest {
internal readonly char[] whiteSpace = new char[] { '\t', '\n', '\r', '\f', ' ' };
internal readonly char[] quote = new char[] { '\'', '"' };
[NUnit.Framework.Test]
public virtual void EnsureSearchArraysAreSorted() {
char[][] arrays = new char[][] { TokeniserState.attributeNameCharsSorted, TokeniserState.attributeValueUnquoted
};
foreach (char[] array in arrays) {
char[] copy = JavaUtil.ArraysCopyOf(array, array.Length);
JavaUtil.Sort(array);
NUnit.Framework.Assert.AreEqual(array, copy);
}
}
[NUnit.Framework.Test]
public virtual void TestCharacterReferenceInRcdata() {
String body = "<textarea>You&I</textarea>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(body);
Elements els = doc.Select("textarea");
NUnit.Framework.Assert.AreEqual("You&I", els.Text());
}
[NUnit.Framework.Test]
public virtual void TestBeforeTagName() {
foreach (char c in whiteSpace) {
String body = MessageFormatUtil.Format("<div{0}>test</div>", c);
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(body);
Elements els = doc.Select("div");
NUnit.Framework.Assert.AreEqual("test", els.Text());
}
}
[NUnit.Framework.Test]
public virtual void TestEndTagOpen() {
String body;
Document doc;
Elements els;
body = "<div>hello world</";
doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(body);
els = doc.Select("div");
NUnit.Framework.Assert.AreEqual("hello world</", els.Text());
body = "<div>hello world</div>";
doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(body);
els = doc.Select("div");
NUnit.Framework.Assert.AreEqual("hello world", els.Text());
body = "<div>fake</></div>";
doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(body);
els = doc.Select("div");
NUnit.Framework.Assert.AreEqual("fake", els.Text());
body = "<div>fake</?</div>";
doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(body);
els = doc.Select("div");
NUnit.Framework.Assert.AreEqual("fake", els.Text());
}
[NUnit.Framework.Test]
public virtual void TestRcdataLessthanSign() {
String body;
Document doc;
Elements els;
body = "<textarea><fake></textarea>";
doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(body);
els = doc.Select("textarea");
NUnit.Framework.Assert.AreEqual("<fake>", els.Text());
body = "<textarea><open";
doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(body);
els = doc.Select("textarea");
NUnit.Framework.Assert.AreEqual("", els.Text());
body = "<textarea>hello world</?fake</textarea>";
doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(body);
els = doc.Select("textarea");
NUnit.Framework.Assert.AreEqual("hello world</?fake", els.Text());
}
[NUnit.Framework.Test]
public virtual void TestRCDATAEndTagName() {
foreach (char c in whiteSpace) {
String body = MessageFormatUtil.Format("<textarea>data</textarea{0}>", c);
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(body);
Elements els = doc.Select("textarea");
NUnit.Framework.Assert.AreEqual("data", els.Text());
}
}
[NUnit.Framework.Test]
public virtual void TestCommentEndCoverage() {
String html = "<html><head></head><body><img src=foo><!-- <table><tr><td></table> --! --- --><p>Hello</p></body></html>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element body = doc.Body();
Comment comment = (Comment)body.ChildNode(1);
NUnit.Framework.Assert.AreEqual(" <table><tr><td></table> --! --- ", comment.GetData());
TSpdf.StyledXmlParser.Jsoup.Nodes.Element p = body.Child(1);
TextNode text = (TextNode)p.ChildNode(0);
NUnit.Framework.Assert.AreEqual("Hello", text.GetWholeText());
}
[NUnit.Framework.Test]
public virtual void TestCommentEndBangCoverage() {
String html = "<html><head></head><body><img src=foo><!-- <table><tr><td></table> --!---!>--><p>Hello</p></body></html>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element body = doc.Body();
Comment comment = (Comment)body.ChildNode(1);
NUnit.Framework.Assert.AreEqual(" <table><tr><td></table> --!-", comment.GetData());
TSpdf.StyledXmlParser.Jsoup.Nodes.Element p = body.Child(1);
TextNode text = (TextNode)p.ChildNode(0);
NUnit.Framework.Assert.AreEqual("Hello", text.GetWholeText());
}
[NUnit.Framework.Test]
public virtual void TestPublicIdentifiersWithWhitespace() {
String expectedOutput = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0//EN\">";
foreach (char q in quote) {
foreach (char ws in whiteSpace) {
String[] htmls = new String[] { MessageFormatUtil.Format("<!DOCTYPE html{0}PUBLIC {1}-//W3C//DTD HTML 4.0//EN{2}>"
, ws, q, q), MessageFormatUtil.Format("<!DOCTYPE html {0}PUBLIC {1}-//W3C//DTD HTML 4.0//EN{2}>", ws,
q, q), MessageFormatUtil.Format("<!DOCTYPE html PUBLIC{0}{1}-//W3C//DTD HTML 4.0//EN{2}>", ws, q, q),
MessageFormatUtil.Format("<!DOCTYPE html PUBLIC {0}{1}-//W3C//DTD HTML 4.0//EN{2}>", ws, q, q), MessageFormatUtil
.Format("<!DOCTYPE html PUBLIC {0}-//W3C//DTD HTML 4.0//EN{1}{2}>", q, q, ws), MessageFormatUtil.Format
("<!DOCTYPE html PUBLIC{0}-//W3C//DTD HTML 4.0//EN{1}{2}>", q, q, ws) };
foreach (String html in htmls) {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
NUnit.Framework.Assert.AreEqual(expectedOutput, doc.ChildNode(0).OuterHtml());
}
}
}
}
[NUnit.Framework.Test]
public virtual void TestSystemIdentifiersWithWhitespace() {
String expectedOutput = "<!DOCTYPE html SYSTEM \"http://www.w3.org/TR/REC-html40/strict.dtd\">";
foreach (char q in quote) {
foreach (char ws in whiteSpace) {
String[] htmls = new String[] { MessageFormatUtil.Format("<!DOCTYPE html{0}SYSTEM {1}http://www.w3.org/TR/REC-html40/strict.dtd{2}>"
, ws, q, q), MessageFormatUtil.Format("<!DOCTYPE html {0}SYSTEM {1}http://www.w3.org/TR/REC-html40/strict.dtd{2}>"
, ws, q, q), MessageFormatUtil.Format("<!DOCTYPE html SYSTEM{0}{1}http://www.w3.org/TR/REC-html40/strict.dtd{2}>"
, ws, q, q), MessageFormatUtil.Format("<!DOCTYPE html SYSTEM {0}{1}http://www.w3.org/TR/REC-html40/strict.dtd{2}>"
, ws, q, q), MessageFormatUtil.Format("<!DOCTYPE html SYSTEM {0}http://www.w3.org/TR/REC-html40/strict.dtd{1}{2}>"
, q, q, ws), MessageFormatUtil.Format("<!DOCTYPE html SYSTEM{0}http://www.w3.org/TR/REC-html40/strict.dtd{1}{2}>"
, q, q, ws) };
foreach (String html in htmls) {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
NUnit.Framework.Assert.AreEqual(expectedOutput, doc.ChildNode(0).OuterHtml());
}
}
}
}
[NUnit.Framework.Test]
public virtual void TestPublicAndSystemIdentifiersWithWhitespace() {
String expectedOutput = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0//EN\"" + " \"http://www.w3.org/TR/REC-html40/strict.dtd\">";
foreach (char q in quote) {
foreach (char ws in whiteSpace) {
String[] htmls = new String[] { MessageFormatUtil.Format("<!DOCTYPE html PUBLIC {0}-//W3C//DTD HTML 4.0//EN{1}"
+ "{2}{3}http://www.w3.org/TR/REC-html40/strict.dtd{4}>", q, q, ws, q, q), MessageFormatUtil.Format("<!DOCTYPE html PUBLIC {0}-//W3C//DTD HTML 4.0//EN{1}"
+ "{2}http://www.w3.org/TR/REC-html40/strict.dtd{3}>", q, q, q, q) };
foreach (String html in htmls) {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
NUnit.Framework.Assert.AreEqual(expectedOutput, doc.ChildNode(0).OuterHtml());
}
}
}
}
[NUnit.Framework.Test]
public virtual void HandlesLessInTagThanAsNewTag() {
// out of spec, but clear author intent
String html = "<p\n<p<div id=one <span>Two";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
NUnit.Framework.Assert.AreEqual("<p></p><p></p><div id=\"one\"><span>Two</span></div>", TextUtil.StripNewlines
(doc.Body().Html()));
}
[NUnit.Framework.Test]
public virtual void TestUnconsumeAtBufferBoundary() {
String triggeringSnippet = "<a href=\"\"foo";
char[] padding = new char[CharacterReader.readAheadLimit - triggeringSnippet.Length + 2];
// The "foo" part must be just at the limit.
JavaUtil.Fill(padding, ' ');
String paddedSnippet = JavaUtil.GetStringForChars(padding) + triggeringSnippet;
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(paddedSnippet, null, "", errorList);
NUnit.Framework.Assert.AreEqual(CharacterReader.readAheadLimit - 1, errorList[0].GetPosition());
}
[NUnit.Framework.Test]
public virtual void TestUnconsumeAfterBufferUp() {
// test for after consume() a bufferUp occurs (look-forward) but then attempts to unconsume. Would throw a "No buffer left to unconsume"
String triggeringSnippet = "<title>One <span>Two";
char[] padding = new char[CharacterReader.readAheadLimit - triggeringSnippet.Length + 8];
// The "<span" part must be just at the limit. The "containsIgnoreCase" scan does a bufferUp, losing the unconsume
JavaUtil.Fill(padding, ' ');
String paddedSnippet = JavaUtil.GetStringForChars(padding) + triggeringSnippet;
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(paddedSnippet, null, "", errorList);
}
[NUnit.Framework.Test]
public virtual void TestOpeningAngleBracketInsteadOfAttribute() {
String triggeringSnippet = "<html <";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(triggeringSnippet, null, "", errorList);
NUnit.Framework.Assert.AreEqual(6, errorList[0].GetPosition());
}
[NUnit.Framework.Test]
public virtual void TestMalformedSelfClosingTag() {
String triggeringSnippet = "<html /ouch";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(triggeringSnippet, null, "", errorList);
NUnit.Framework.Assert.AreEqual(7, errorList[0].GetPosition());
}
[NUnit.Framework.Test]
public virtual void TestOpeningAngleBracketInTagName() {
String triggeringSnippet = "<html<";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(triggeringSnippet, null, "", errorList);
NUnit.Framework.Assert.AreEqual(5, errorList[0].GetPosition());
}
[NUnit.Framework.Test]
public virtual void RcData() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<title>One \x0Two</title>");
NUnit.Framework.Assert.AreEqual("One <20>Two", doc.Title());
}
[NUnit.Framework.Test]
public virtual void Plaintext() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div>One<plaintext><div>Two</plaintext>\x0no < Return"
);
NUnit.Framework.Assert.AreEqual("<html><head></head><body><div>One<plaintext>&lt;div&gt;Two&lt;/plaintext&gt;<3B>no &lt; Return</plaintext></div></body></html>"
, TextUtil.StripNewlines(doc.Html()));
}
[NUnit.Framework.Test]
public virtual void NullInTag() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<di\x0v>One</di\x0v>Two");
NUnit.Framework.Assert.AreEqual("<di<64>v>\n One\n</di<64>v>Two", doc.Body().Html());
}
[NUnit.Framework.Test]
public virtual void AttributeValUnquoted() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p name=foo&lt;bar>");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element p = doc.SelectFirst("p");
NUnit.Framework.Assert.AreEqual("foo<bar", p.Attr("name"));
doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p foo=");
NUnit.Framework.Assert.AreEqual("<p foo></p>", doc.Body().Html());
}
[NUnit.Framework.Test]
public virtual void TestRCDATAEndTagNameDiffTag() {
String body = "<textarea>data</textare >";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpected token"));
}
[NUnit.Framework.Test]
public virtual void TestRCDATAEndTagNameValidSlash() {
String body = "<textarea>data</textarea/>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(body);
Elements els = doc.Select("textarea");
NUnit.Framework.Assert.AreEqual("data", els.Text());
}
[NUnit.Framework.Test]
public virtual void TestRCDATAEndTagNameInvalidSlash() {
String body = "<textarea>data</textare/>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpected token"));
}
[NUnit.Framework.Test]
public virtual void ScriptDataEscapeStartDashValid() {
String body = "<script><!-- text --></script>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(0, errorList.Count);
}
[NUnit.Framework.Test]
public virtual void ScriptDataEscapeStartDashInvalid() {
String body = "<script><!- text --></script>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(0, errorList.Count);
}
[NUnit.Framework.Test]
public virtual void ScriptDataEscapedEmpty() {
String body = "<script><!-- ";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpectedly reached end of file (EOF) in input state"
));
}
[NUnit.Framework.Test]
public virtual void ScriptDataEscapedStartTag() {
String body = "<script><!--<</script>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(0, errorList.Count);
}
[NUnit.Framework.Test]
public virtual void ScriptDataEscapedNullChar() {
String body = "<script><!--a\x0";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpected character"));
}
[NUnit.Framework.Test]
public virtual void ScriptDataEscapedDashEmpty() {
String body = "<script><!-- -";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpectedly reached end of file (EOF) in input state"
));
}
[NUnit.Framework.Test]
public virtual void ScriptDataEscapedDashStTag() {
String body = "<script><!-- -<</script>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(0, errorList.Count);
}
[NUnit.Framework.Test]
public virtual void ScriptDataEscapedDashNullChar() {
String body = "<script><!-- -\x0";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpected character"));
}
[NUnit.Framework.Test]
public virtual void ScriptDataEscapedDashDashEmpty() {
String body = "<script><!-- --";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpectedly reached end of file (EOF) in input state"
));
}
[NUnit.Framework.Test]
public virtual void ScriptDataEscapedDashDashStTag() {
String body = "<script><!-- --<</script>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(0, errorList.Count);
}
[NUnit.Framework.Test]
public virtual void ScriptDataEscapedDashDashNullChar() {
String body = "<script><!-- --\x0";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpected character"));
}
[NUnit.Framework.Test]
public virtual void ScriptDataEscapedEndTagOpen() {
String body = "<script><!-- --</---></script>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(0, errorList.Count);
}
[NUnit.Framework.Test]
public virtual void ScriptDataDoubleEscapedNullChar() {
String body = "<script><!--<script><\x0!-";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpected character"));
}
[NUnit.Framework.Test]
public virtual void ScriptDataDoubleEscapedEof() {
String body = "<script><!--<script><!-";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpectedly reached end of file (EOF) in input state"
));
}
[NUnit.Framework.Test]
public virtual void ScriptDataDoubleEscapedDash() {
String body = "<script><!--<script><!-- --></script>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(0, errorList.Count);
}
[NUnit.Framework.Test]
public virtual void ScriptDataDoubleEscapedDashStTag() {
String body = "<script><!--<script><!-< --></script>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(0, errorList.Count);
}
[NUnit.Framework.Test]
public virtual void ScriptDataDoubleEscapedDashNull() {
String body = "<script><!--<script><!-\x0 --></script>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpected character"));
}
[NUnit.Framework.Test]
public virtual void ScriptDataDoubleEscapedDashEof() {
String body = "<script><!--<script><!-";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpectedly reached end of file (EOF) in input state"
));
}
[NUnit.Framework.Test]
public virtual void ScriptDataDoubleEscapedDashDefault() {
String body = "<script><!--<script><!-aaa --></script>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(0, errorList.Count);
}
[NUnit.Framework.Test]
public virtual void ScriptDataDoubleEscapedDashDash() {
String body = "<script><!--<script><!--- --></script>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(0, errorList.Count);
}
[NUnit.Framework.Test]
public virtual void ScriptDataDoubleEscapedDashDashStTag() {
String body = "<script><!--<script><!--< --></script>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(0, errorList.Count);
}
[NUnit.Framework.Test]
public virtual void ScriptDataDoubleEscapedDashDashNull() {
String body = "<script><!--<script><!--\x0 --></script>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpected character"));
}
[NUnit.Framework.Test]
public virtual void ScriptDataDoubleEscapedDashDashEof() {
String body = "<script><!--<script><!--";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpectedly reached end of file (EOF) in input state"
));
}
[NUnit.Framework.Test]
public virtual void ScriptDataDoubleEscapedDashDashDefault() {
String body = "<script><!--<script><!--aaa --></script>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(0, errorList.Count);
}
[NUnit.Framework.Test]
public virtual void AttributeNameStTag() {
String body = "<p name< />";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpected character"));
}
[NUnit.Framework.Test]
public virtual void AfterAttributeNameEndTag() {
String body = "<p name > />";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(0, errorList.Count);
}
[NUnit.Framework.Test]
public virtual void AfterAttributeNameNull() {
String body = "<p name \x0 />";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpected character"));
}
[NUnit.Framework.Test]
public virtual void AfterAttributeNameEof() {
String body = "<p name ";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpectedly reached end of file (EOF) in input state"
));
}
[NUnit.Framework.Test]
public virtual void AfterAttributeNameStTag() {
String body = "<p name <";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpected character"));
}
[NUnit.Framework.Test]
public virtual void BeforeAttributeNameClTag() {
String body = "<p name=></p>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpected character"));
}
[NUnit.Framework.Test]
public virtual void BeforeAttributeNameStTag() {
String body = "<p name=<</p>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpected character"));
}
[NUnit.Framework.Test]
public virtual void AttributeValueDoubleQuotedNull() {
String body = "<p name=\"\x0\"></p>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpected character"));
}
[NUnit.Framework.Test]
public virtual void AttributeValueSingleQuotedNull() {
String body = "<p name='\x0'></p>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpected character"));
}
[NUnit.Framework.Test]
public virtual void AttributeValueSingleUnquotedAmp() {
String body = "<p name=&a></p>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(0, errorList.Count);
}
[NUnit.Framework.Test]
public virtual void AttributeValueSingleUnquotedNull() {
String body = "<p name=a\x0></p>";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpected character"));
}
[NUnit.Framework.Test]
public virtual void AttributeValueSingleUnquotedEof() {
String body = "<p name=a";
ParseErrorList errorList = ParseErrorList.Tracking(1);
TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseFragment(body, null, "", errorList);
NUnit.Framework.Assert.AreEqual(1, errorList.Count);
NUnit.Framework.Assert.IsTrue(errorList[0].GetErrorMessage().Contains("Unexpectedly reached end of file (EOF) in input state"
));
}
[NUnit.Framework.Test]
public virtual void TokeniserStateToStringTest() {
NUnit.Framework.Assert.AreEqual("Data", TokeniserState.Data.ToString());
NUnit.Framework.Assert.AreEqual("CharacterReferenceInData", TokeniserState.CharacterReferenceInData.ToString
());
NUnit.Framework.Assert.AreEqual("Rcdata", TokeniserState.Rcdata.ToString());
NUnit.Framework.Assert.AreEqual("CharacterReferenceInRcdata", TokeniserState.CharacterReferenceInRcdata.ToString
());
NUnit.Framework.Assert.AreEqual("Rawtext", TokeniserState.Rawtext.ToString());
NUnit.Framework.Assert.AreEqual("ScriptData", TokeniserState.ScriptData.ToString());
NUnit.Framework.Assert.AreEqual("PLAINTEXT", TokeniserState.PLAINTEXT.ToString());
NUnit.Framework.Assert.AreEqual("TagOpen", TokeniserState.TagOpen.ToString());
NUnit.Framework.Assert.AreEqual("EndTagOpen", TokeniserState.EndTagOpen.ToString());
NUnit.Framework.Assert.AreEqual("TagName", TokeniserState.TagName.ToString());
NUnit.Framework.Assert.AreEqual("RcdataLessthanSign", TokeniserState.RcdataLessthanSign.ToString());
NUnit.Framework.Assert.AreEqual("RCDATAEndTagOpen", TokeniserState.RCDATAEndTagOpen.ToString());
NUnit.Framework.Assert.AreEqual("RCDATAEndTagName", TokeniserState.RCDATAEndTagName.ToString());
NUnit.Framework.Assert.AreEqual("RawtextLessthanSign", TokeniserState.RawtextLessthanSign.ToString());
NUnit.Framework.Assert.AreEqual("RawtextEndTagOpen", TokeniserState.RawtextEndTagOpen.ToString());
NUnit.Framework.Assert.AreEqual("RawtextEndTagName", TokeniserState.RawtextEndTagName.ToString());
NUnit.Framework.Assert.AreEqual("ScriptDataLessthanSign", TokeniserState.ScriptDataLessthanSign.ToString()
);
NUnit.Framework.Assert.AreEqual("ScriptDataEndTagOpen", TokeniserState.ScriptDataEndTagOpen.ToString());
NUnit.Framework.Assert.AreEqual("ScriptDataEndTagName", TokeniserState.ScriptDataEndTagName.ToString());
NUnit.Framework.Assert.AreEqual("ScriptDataEscapeStart", TokeniserState.ScriptDataEscapeStart.ToString());
NUnit.Framework.Assert.AreEqual("ScriptDataEscapeStartDash", TokeniserState.ScriptDataEscapeStartDash.ToString
());
NUnit.Framework.Assert.AreEqual("ScriptDataEscaped", TokeniserState.ScriptDataEscaped.ToString());
NUnit.Framework.Assert.AreEqual("ScriptDataEscapedDash", TokeniserState.ScriptDataEscapedDash.ToString());
NUnit.Framework.Assert.AreEqual("ScriptDataEscapedDashDash", TokeniserState.ScriptDataEscapedDashDash.ToString
());
NUnit.Framework.Assert.AreEqual("ScriptDataEscapedLessthanSign", TokeniserState.ScriptDataEscapedLessthanSign
.ToString());
NUnit.Framework.Assert.AreEqual("ScriptDataEscapedEndTagOpen", TokeniserState.ScriptDataEscapedEndTagOpen.
ToString());
NUnit.Framework.Assert.AreEqual("ScriptDataEscapedEndTagName", TokeniserState.ScriptDataEscapedEndTagName.
ToString());
NUnit.Framework.Assert.AreEqual("ScriptDataDoubleEscapeStart", TokeniserState.ScriptDataDoubleEscapeStart.
ToString());
NUnit.Framework.Assert.AreEqual("ScriptDataDoubleEscaped", TokeniserState.ScriptDataDoubleEscaped.ToString
());
NUnit.Framework.Assert.AreEqual("ScriptDataDoubleEscapedDash", TokeniserState.ScriptDataDoubleEscapedDash.
ToString());
NUnit.Framework.Assert.AreEqual("ScriptDataDoubleEscapedDashDash", TokeniserState.ScriptDataDoubleEscapedDashDash
.ToString());
NUnit.Framework.Assert.AreEqual("ScriptDataDoubleEscapedLessthanSign", TokeniserState.ScriptDataDoubleEscapedLessthanSign
.ToString());
NUnit.Framework.Assert.AreEqual("ScriptDataDoubleEscapeEnd", TokeniserState.ScriptDataDoubleEscapeEnd.ToString
());
NUnit.Framework.Assert.AreEqual("BeforeAttributeName", TokeniserState.BeforeAttributeName.ToString());
NUnit.Framework.Assert.AreEqual("AttributeName", TokeniserState.AttributeName.ToString());
NUnit.Framework.Assert.AreEqual("AfterAttributeName", TokeniserState.AfterAttributeName.ToString());
NUnit.Framework.Assert.AreEqual("BeforeAttributeValue", TokeniserState.BeforeAttributeValue.ToString());
NUnit.Framework.Assert.AreEqual("AttributeValue_doubleQuoted", TokeniserState.AttributeValue_doubleQuoted.
ToString());
NUnit.Framework.Assert.AreEqual("AttributeValue_singleQuoted", TokeniserState.AttributeValue_singleQuoted.
ToString());
NUnit.Framework.Assert.AreEqual("AttributeValue_unquoted", TokeniserState.AttributeValue_unquoted.ToString
());
NUnit.Framework.Assert.AreEqual("AfterAttributeValue_quoted", TokeniserState.AfterAttributeValue_quoted.ToString
());
NUnit.Framework.Assert.AreEqual("SelfClosingStartTag", TokeniserState.SelfClosingStartTag.ToString());
NUnit.Framework.Assert.AreEqual("BogusComment", TokeniserState.BogusComment.ToString());
NUnit.Framework.Assert.AreEqual("MarkupDeclarationOpen", TokeniserState.MarkupDeclarationOpen.ToString());
NUnit.Framework.Assert.AreEqual("CommentStart", TokeniserState.CommentStart.ToString());
NUnit.Framework.Assert.AreEqual("CommentStartDash", TokeniserState.CommentStartDash.ToString());
NUnit.Framework.Assert.AreEqual("Comment", TokeniserState.Comment.ToString());
NUnit.Framework.Assert.AreEqual("CommentEndDash", TokeniserState.CommentEndDash.ToString());
NUnit.Framework.Assert.AreEqual("CommentEnd", TokeniserState.CommentEnd.ToString());
NUnit.Framework.Assert.AreEqual("CommentEndBang", TokeniserState.CommentEndBang.ToString());
NUnit.Framework.Assert.AreEqual("Doctype", TokeniserState.Doctype.ToString());
NUnit.Framework.Assert.AreEqual("BeforeDoctypeName", TokeniserState.BeforeDoctypeName.ToString());
NUnit.Framework.Assert.AreEqual("DoctypeName", TokeniserState.DoctypeName.ToString());
NUnit.Framework.Assert.AreEqual("AfterDoctypeName", TokeniserState.AfterDoctypeName.ToString());
NUnit.Framework.Assert.AreEqual("AfterDoctypePublicKeyword", TokeniserState.AfterDoctypePublicKeyword.ToString
());
NUnit.Framework.Assert.AreEqual("BeforeDoctypePublicIdentifier", TokeniserState.BeforeDoctypePublicIdentifier
.ToString());
NUnit.Framework.Assert.AreEqual("DoctypePublicIdentifier_doubleQuoted", TokeniserState.DoctypePublicIdentifier_doubleQuoted
.ToString());
NUnit.Framework.Assert.AreEqual("DoctypePublicIdentifier_singleQuoted", TokeniserState.DoctypePublicIdentifier_singleQuoted
.ToString());
NUnit.Framework.Assert.AreEqual("AfterDoctypePublicIdentifier", TokeniserState.AfterDoctypePublicIdentifier
.ToString());
NUnit.Framework.Assert.AreEqual("BetweenDoctypePublicAndSystemIdentifiers", TokeniserState.BetweenDoctypePublicAndSystemIdentifiers
.ToString());
NUnit.Framework.Assert.AreEqual("AfterDoctypeSystemKeyword", TokeniserState.AfterDoctypeSystemKeyword.ToString
());
NUnit.Framework.Assert.AreEqual("BeforeDoctypeSystemIdentifier", TokeniserState.BeforeDoctypeSystemIdentifier
.ToString());
NUnit.Framework.Assert.AreEqual("DoctypeSystemIdentifier_doubleQuoted", TokeniserState.DoctypeSystemIdentifier_doubleQuoted
.ToString());
NUnit.Framework.Assert.AreEqual("DoctypeSystemIdentifier_singleQuoted", TokeniserState.DoctypeSystemIdentifier_singleQuoted
.ToString());
NUnit.Framework.Assert.AreEqual("AfterDoctypeSystemIdentifier", TokeniserState.AfterDoctypeSystemIdentifier
.ToString());
NUnit.Framework.Assert.AreEqual("BogusDoctype", TokeniserState.BogusDoctype.ToString());
NUnit.Framework.Assert.AreEqual("CdataSection", TokeniserState.CdataSection.ToString());
}
}
}

View File

@@ -0,0 +1,237 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Text;
using TSpdf.Commons.Utils;
using TSpdf.StyledXmlParser.Jsoup.Nodes;
using TSpdf.StyledXmlParser.Jsoup.Select;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Parser {
[NUnit.Framework.Category("UnitTest")]
public class TokeniserTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void BufferUpInAttributeVal() {
// https://github.com/jhy/jsoup/issues/967
// check each double, singlem, unquoted impls
String[] quotes = new String[] { "\"", "'", "" };
foreach (String quote in quotes) {
String preamble = "<img src=" + quote;
String tail = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
StringBuilder sb = new StringBuilder(preamble);
int charsToFillBuffer = CharacterReader.maxBufferLen - preamble.Length;
for (int i = 0; i < charsToFillBuffer; i++) {
sb.Append('a');
}
sb.Append('X');
// First character to cross character buffer boundary
sb.Append(tail).Append(quote).Append(">\n");
String html = sb.ToString();
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
String src = doc.Select("img").Attr("src");
NUnit.Framework.Assert.IsTrue(src.Contains("X"));
NUnit.Framework.Assert.IsTrue(src.Contains(tail));
}
}
[NUnit.Framework.Test]
public virtual void HandleSuperLargeTagNames() {
// unlikely, but valid. so who knows.
StringBuilder sb = new StringBuilder(CharacterReader.maxBufferLen);
do {
sb.Append("LargeTagName");
}
while (sb.Length < CharacterReader.maxBufferLen);
String tag = sb.ToString();
String html = "<" + tag + ">One</" + tag + ">";
Document doc = TSpdf.StyledXmlParser.Jsoup.Parser.Parser.HtmlParser().Settings(ParseSettings.preserveCase)
.ParseInput(html, "");
Elements els = doc.Select(tag);
NUnit.Framework.Assert.AreEqual(1, els.Count);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el = els.First();
NUnit.Framework.Assert.IsNotNull(el);
NUnit.Framework.Assert.AreEqual("One", el.Text());
NUnit.Framework.Assert.AreEqual(tag, el.TagName());
}
[NUnit.Framework.Test]
public virtual void HandleSuperLargeAttributeName() {
StringBuilder sb = new StringBuilder(CharacterReader.maxBufferLen);
do {
sb.Append("LargAttributeName");
}
while (sb.Length < CharacterReader.maxBufferLen);
String attrName = sb.ToString();
String html = "<p " + attrName + "=foo>One</p>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
Elements els = doc.GetElementsByAttribute(attrName);
NUnit.Framework.Assert.AreEqual(1, els.Count);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el = els.First();
NUnit.Framework.Assert.IsNotNull(el);
NUnit.Framework.Assert.AreEqual("One", el.Text());
TSpdf.StyledXmlParser.Jsoup.Nodes.Attribute attribute = el.Attributes().AsList()[0];
NUnit.Framework.Assert.AreEqual(attrName.ToLowerInvariant(), attribute.Key);
NUnit.Framework.Assert.AreEqual("foo", attribute.Value);
}
[NUnit.Framework.Test]
public virtual void HandleLargeText() {
StringBuilder sb = new StringBuilder(CharacterReader.maxBufferLen);
do {
sb.Append("A Large Amount of Text");
}
while (sb.Length < CharacterReader.maxBufferLen);
String text = sb.ToString();
String html = "<p>" + text + "</p>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
Elements els = doc.Select("p");
NUnit.Framework.Assert.AreEqual(1, els.Count);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el = els.First();
NUnit.Framework.Assert.IsNotNull(el);
NUnit.Framework.Assert.AreEqual(text, el.Text());
}
[NUnit.Framework.Test]
public virtual void HandleLargeComment() {
StringBuilder sb = new StringBuilder(CharacterReader.maxBufferLen);
do {
sb.Append("Quite a comment ");
}
while (sb.Length < CharacterReader.maxBufferLen);
String comment = sb.ToString();
String html = "<p><!-- " + comment + " --></p>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
Elements els = doc.Select("p");
NUnit.Framework.Assert.AreEqual(1, els.Count);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el = els.First();
NUnit.Framework.Assert.IsNotNull(el);
Comment child = (Comment)el.ChildNode(0);
NUnit.Framework.Assert.AreEqual(" " + comment + " ", child.GetData());
}
[NUnit.Framework.Test]
public virtual void HandleLargeCdata() {
StringBuilder sb = new StringBuilder(CharacterReader.maxBufferLen);
do {
sb.Append("Quite a lot of CDATA <><><><>");
}
while (sb.Length < CharacterReader.maxBufferLen);
String cdata = sb.ToString();
String html = "<p><![CDATA[" + cdata + "]]></p>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
Elements els = doc.Select("p");
NUnit.Framework.Assert.AreEqual(1, els.Count);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el = els.First();
NUnit.Framework.Assert.IsNotNull(el);
TextNode child = (TextNode)el.ChildNode(0);
NUnit.Framework.Assert.AreEqual(cdata, el.Text());
NUnit.Framework.Assert.AreEqual(cdata, child.GetWholeText());
}
[NUnit.Framework.Test]
public virtual void HandleLargeTitle() {
StringBuilder sb = new StringBuilder(CharacterReader.maxBufferLen);
do {
sb.Append("Quite a long title");
}
while (sb.Length < CharacterReader.maxBufferLen);
String title = sb.ToString();
String html = "<title>" + title + "</title>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
Elements els = doc.Select("title");
NUnit.Framework.Assert.AreEqual(1, els.Count);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el = els.First();
NUnit.Framework.Assert.IsNotNull(el);
TextNode child = (TextNode)el.ChildNode(0);
NUnit.Framework.Assert.AreEqual(title, el.Text());
NUnit.Framework.Assert.AreEqual(title, child.GetWholeText());
NUnit.Framework.Assert.AreEqual(title, doc.Title());
}
[NUnit.Framework.Test]
public virtual void Cp1252Entities() {
NUnit.Framework.Assert.AreEqual("\u20ac", TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("&#0128;").Text());
NUnit.Framework.Assert.AreEqual("\u201a", TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("&#0130;").Text());
NUnit.Framework.Assert.AreEqual("\u20ac", TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("&#x80;").Text());
}
[NUnit.Framework.Test]
public virtual void Cp1252EntitiesProduceError() {
TSpdf.StyledXmlParser.Jsoup.Parser.Parser parser = new TSpdf.StyledXmlParser.Jsoup.Parser.Parser(new HtmlTreeBuilder
());
parser.SetTrackErrors(10);
NUnit.Framework.Assert.AreEqual("\u20ac", parser.ParseInput("<html><body>&#0128;</body></html>", "").Text(
));
NUnit.Framework.Assert.AreEqual(1, parser.GetErrors().Count);
}
[NUnit.Framework.Test]
public virtual void Cp1252SubstitutionTable() {
for (int i = 0; i < Tokeniser.win1252Extensions.Length; i++) {
String s = TSpdf.Commons.Utils.JavaUtil.GetStringForBytes(new byte[] { (byte)(i + Tokeniser.win1252ExtensionsStart
) }, "Windows-1252");
NUnit.Framework.Assert.AreEqual(1, s.Length);
// some of these characters are illegal
if (s[0] == '\ufffd') {
continue;
}
NUnit.Framework.Assert.AreEqual(s[0], Tokeniser.win1252Extensions[i]);
}
}
[NUnit.Framework.Test]
public virtual void CanParseVeryLongBogusComment() {
StringBuilder commentData = new StringBuilder(CharacterReader.maxBufferLen);
do {
commentData.Append("blah blah blah blah ");
}
while (commentData.Length < CharacterReader.maxBufferLen);
String expectedCommentData = commentData.ToString();
String testMarkup = "<html><body><!" + expectedCommentData + "></body></html>";
TSpdf.StyledXmlParser.Jsoup.Parser.Parser parser = new TSpdf.StyledXmlParser.Jsoup.Parser.Parser(new HtmlTreeBuilder
());
Document doc = parser.ParseInput(testMarkup, "");
TSpdf.StyledXmlParser.Jsoup.Nodes.Node commentNode = doc.Body().ChildNode(0);
NUnit.Framework.Assert.IsTrue(commentNode is Comment);
NUnit.Framework.Assert.AreEqual(expectedCommentData, ((Comment)commentNode).GetData());
}
[NUnit.Framework.Test]
public virtual void CanParseCdataEndingAtEdgeOfBuffer() {
String cdataStart = "<![CDATA[";
String cdataEnd = "]]>";
int bufLen = CharacterReader.maxBufferLen - cdataStart.Length - 1;
// also breaks with -2, but not with -3 or 0
char[] cdataContentsArray = new char[bufLen];
JavaUtil.Fill(cdataContentsArray, 'x');
String cdataContents = new String(cdataContentsArray);
String testMarkup = cdataStart + cdataContents + cdataEnd;
TSpdf.StyledXmlParser.Jsoup.Parser.Parser parser = new TSpdf.StyledXmlParser.Jsoup.Parser.Parser(new HtmlTreeBuilder
());
Document doc = parser.ParseInput(testMarkup, "");
TSpdf.StyledXmlParser.Jsoup.Nodes.Node cdataNode = doc.Body().ChildNode(0);
NUnit.Framework.Assert.IsTrue(cdataNode is CDataNode);
NUnit.Framework.Assert.AreEqual(cdataContents, ((CDataNode)cdataNode).Text());
}
}
}

View File

@@ -0,0 +1,310 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.IO;
using TSpdf.StyledXmlParser.Jsoup;
using TSpdf.StyledXmlParser.Jsoup.Integration;
using TSpdf.StyledXmlParser.Jsoup.Nodes;
using TSpdf.StyledXmlParser.Jsoup.Select;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Parser {
/// <summary>Tests XmlTreeBuilder.</summary>
/// <author>Jonathan Hedley</author>
[NUnit.Framework.Category("UnitTest")]
public class XmlTreeBuilderTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void TestSimpleXmlParse() {
String xml = "<doc id=2 href='/bar'>Foo <br /><link>One</link><link>Two</link></doc>";
XmlTreeBuilder tb = new XmlTreeBuilder();
Document doc = tb.Parse(xml, "http://foo.com/");
NUnit.Framework.Assert.AreEqual("<doc id=\"2\" href=\"/bar\">Foo <br /><link>One</link><link>Two</link></doc>"
, TextUtil.StripNewlines(doc.Html()));
NUnit.Framework.Assert.AreEqual(doc.GetElementById("2").AbsUrl("href"), "http://foo.com/bar");
}
[NUnit.Framework.Test]
public virtual void TestPopToClose() {
// test: </val> closes Two, </bar> ignored
String xml = "<doc><val>One<val>Two</val></bar>Three</doc>";
XmlTreeBuilder tb = new XmlTreeBuilder();
Document doc = tb.Parse(xml, "http://foo.com/");
NUnit.Framework.Assert.AreEqual("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.StripNewlines(doc
.Html()));
}
[NUnit.Framework.Test]
public virtual void TestCommentAndDocType() {
String xml = "<!DOCTYPE HTML><!-- a comment -->One <qux />Two";
XmlTreeBuilder tb = new XmlTreeBuilder();
Document doc = tb.Parse(xml, "http://foo.com/");
NUnit.Framework.Assert.AreEqual("<!DOCTYPE HTML><!-- a comment -->One <qux />Two", TextUtil.StripNewlines(
doc.Html()));
}
[NUnit.Framework.Test]
public virtual void TestSupplyParserToJsoupClass() {
String xml = "<doc><val>One<val>Two</val></bar>Three</doc>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(xml, "http://foo.com/", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.XmlParser());
NUnit.Framework.Assert.AreEqual("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.StripNewlines(doc
.Html()));
}
[NUnit.Framework.Test]
public virtual void TestSupplyParserToDataStream() {
FileInfo xmlFile = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/xml-test.xml");
Stream inStream = new FileStream(xmlFile.FullName, FileMode.Open, FileAccess.Read);
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(inStream, null, "http://foo.com", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.XmlParser());
NUnit.Framework.Assert.AreEqual("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.StripNewlines(doc
.Html()));
}
[NUnit.Framework.Test]
public virtual void TestDoesNotForceSelfClosingKnownTags() {
// html will force "<br>one</br>" to logically "<br />One<br />". XML should be stay "<br>one</br> -- don't recognise tag.
Document htmlDoc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<br>one</br>");
NUnit.Framework.Assert.AreEqual("<br>one\n<br>", htmlDoc.Body().Html());
Document xmlDoc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<br>one</br>", "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.XmlParser());
NUnit.Framework.Assert.AreEqual("<br>one</br>", xmlDoc.Html());
}
[NUnit.Framework.Test]
public virtual void HandlesXmlDeclarationAsDeclaration() {
String html = "<?xml encoding='UTF-8' ?><body>One</body><!-- comment -->";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.XmlParser());
NUnit.Framework.Assert.AreEqual("<?xml encoding=\"UTF-8\"?><body>One</body><!-- comment -->", doc.OuterHtml
());
NUnit.Framework.Assert.AreEqual("#declaration", doc.ChildNode(0).NodeName());
NUnit.Framework.Assert.AreEqual("#comment", doc.ChildNode(2).NodeName());
}
[NUnit.Framework.Test]
public virtual void XmlFragment() {
String xml = "<one src='/foo/' />Two<three><four /></three>";
IList<TSpdf.StyledXmlParser.Jsoup.Nodes.Node> nodes = TSpdf.StyledXmlParser.Jsoup.Parser.Parser.ParseXmlFragment
(xml, "http://example.com/");
NUnit.Framework.Assert.AreEqual(3, nodes.Count);
NUnit.Framework.Assert.AreEqual("http://example.com/foo/", nodes[0].AbsUrl("src"));
NUnit.Framework.Assert.AreEqual("one", nodes[0].NodeName());
NUnit.Framework.Assert.AreEqual("Two", ((TextNode)nodes[1]).Text());
}
[NUnit.Framework.Test]
public virtual void XmlParseDefaultsToHtmlOutputSyntax() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("x", "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser.
XmlParser());
NUnit.Framework.Assert.AreEqual(TSpdf.StyledXmlParser.Jsoup.Nodes.Syntax.xml, doc.OutputSettings().Syntax(
));
}
[NUnit.Framework.Test]
public virtual void TestDoesHandleEOFInTag() {
String html = "<img src=asdf onerror=\"alert(1)\" x=";
Document xmlDoc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.XmlParser());
NUnit.Framework.Assert.AreEqual("<img src=\"asdf\" onerror=\"alert(1)\" x=\"\" />", xmlDoc.Html());
}
[NUnit.Framework.Test]
public virtual void TestDetectCharsetEncodingDeclaration() {
FileInfo xmlFile = TSpdf.StyledXmlParser.Jsoup.PortTestUtil.GetFile("/htmltests/xml-charset.xml");
Stream inStream = new FileStream(xmlFile.FullName, FileMode.Open, FileAccess.Read);
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(inStream, null, "http://example.com/", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.XmlParser());
NUnit.Framework.Assert.AreEqual("ISO-8859-1", doc.Charset().Name());
NUnit.Framework.Assert.AreEqual("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><data>äöåéü</data>", TextUtil
.StripNewlines(doc.Html()));
}
[NUnit.Framework.Test]
public virtual void TestParseDeclarationAttributes() {
String xml = "<?xml version='1' encoding='UTF-8' something='else'?><val>One</val>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(xml, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser.
XmlParser());
XmlDeclaration decl = (XmlDeclaration)doc.ChildNode(0);
NUnit.Framework.Assert.AreEqual("1", decl.Attr("version"));
NUnit.Framework.Assert.AreEqual("UTF-8", decl.Attr("encoding"));
NUnit.Framework.Assert.AreEqual("else", decl.Attr("something"));
NUnit.Framework.Assert.AreEqual("version=\"1\" encoding=\"UTF-8\" something=\"else\"", decl.GetWholeDeclaration
());
NUnit.Framework.Assert.AreEqual("<?xml version=\"1\" encoding=\"UTF-8\" something=\"else\"?>", decl.OuterHtml
());
}
[NUnit.Framework.Test]
public virtual void CaseSensitiveDeclaration() {
String xml = "<?XML version='1' encoding='UTF-8' something='else'?>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(xml, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser.
XmlParser());
NUnit.Framework.Assert.AreEqual("<?XML version=\"1\" encoding=\"UTF-8\" something=\"else\"?>", doc.OuterHtml
());
}
[NUnit.Framework.Test]
public virtual void TestCreatesValidProlog() {
Document document = Document.CreateShell("");
document.OutputSettings().Syntax(TSpdf.StyledXmlParser.Jsoup.Nodes.Syntax.xml);
document.Charset(System.Text.Encoding.UTF8);
NUnit.Framework.Assert.AreEqual("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<html>\n" + " <head></head>\n"
+ " <body></body>\n" + "</html>", document.OuterHtml());
}
[NUnit.Framework.Test]
public virtual void PreservesCaseByDefault() {
String xml = "<CHECK>One</CHECK><TEST ID=1>Check</TEST>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(xml, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser.
XmlParser());
NUnit.Framework.Assert.AreEqual("<CHECK>One</CHECK><TEST ID=\"1\">Check</TEST>", TextUtil.StripNewlines(doc
.Html()));
}
[NUnit.Framework.Test]
public virtual void AppendPreservesCaseByDefault() {
String xml = "<One>One</One>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(xml, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser.
XmlParser());
Elements one = doc.Select("One");
one.Append("<Two ID=2>Two</Two>");
NUnit.Framework.Assert.AreEqual("<One>One<Two ID=\"2\">Two</Two></One>", TextUtil.StripNewlines(doc.Html()
));
}
[NUnit.Framework.Test]
public virtual void DisablesPrettyPrintingByDefault() {
String xml = "\n\n<div><one>One</one><one>\n Two</one>\n</div>\n ";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(xml, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser.
XmlParser());
NUnit.Framework.Assert.AreEqual(xml, doc.Html());
}
[NUnit.Framework.Test]
public virtual void CanNormalizeCase() {
String xml = "<TEST ID=1>Check</TEST>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(xml, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser.
XmlParser().Settings(ParseSettings.htmlDefault));
NUnit.Framework.Assert.AreEqual("<test id=\"1\">Check</test>", TextUtil.StripNewlines(doc.Html()));
}
[NUnit.Framework.Test]
public virtual void NormalizesDiscordantTags() {
TSpdf.StyledXmlParser.Jsoup.Parser.Parser parser = TSpdf.StyledXmlParser.Jsoup.Parser.Parser.XmlParser().Settings
(ParseSettings.htmlDefault);
Document document = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div>test</DIV><p></p>", "", parser);
NUnit.Framework.Assert.AreEqual("<div>test</div><p></p>", document.Html());
}
// was failing -> toString() = "<div>\n test\n <p></p>\n</div>"
[NUnit.Framework.Test]
public virtual void RoundTripsCdata() {
String xml = "<div id=1><![CDATA[\n<html>\n <foo><&amp;]]></div>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(xml, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser.
XmlParser());
TSpdf.StyledXmlParser.Jsoup.Nodes.Element div = doc.GetElementById("1");
NUnit.Framework.Assert.AreEqual("<html>\n <foo><&amp;", div.Text());
NUnit.Framework.Assert.AreEqual(0, div.Children().Count);
NUnit.Framework.Assert.AreEqual(1, div.ChildNodeSize());
// no elements, one text node
NUnit.Framework.Assert.AreEqual("<div id=\"1\"><![CDATA[\n<html>\n <foo><&amp;]]></div>", div.OuterHtml());
CDataNode cdata = (CDataNode)div.TextNodes()[0];
NUnit.Framework.Assert.AreEqual("\n<html>\n <foo><&amp;", cdata.Text());
}
[NUnit.Framework.Test]
public virtual void CdataPreservesWhiteSpace() {
String xml = "<script type=\"text/javascript\">//<![CDATA[\n\n foo();\n//]]></script>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(xml, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser.
XmlParser());
NUnit.Framework.Assert.AreEqual(xml, doc.OuterHtml());
NUnit.Framework.Assert.AreEqual("//\n\n foo();\n//", doc.SelectFirst("script").Text());
}
[NUnit.Framework.Test]
public virtual void HandlesDodgyXmlDecl() {
String xml = "<?xml version='1.0'><val>One</val>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(xml, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser.
XmlParser());
NUnit.Framework.Assert.AreEqual("One", doc.Select("val").Text());
}
[NUnit.Framework.Test]
public virtual void HandlesLTinScript() {
// https://github.com/jhy/jsoup/issues/1139
String html = "<script> var a=\"<?\"; var b=\"?>\"; </script>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.XmlParser());
NUnit.Framework.Assert.AreEqual("<script> var a=\"<!--?\"; var b=\"?-->\"; </script>", doc.Html());
}
// converted from pseudo xmldecl to comment
[NUnit.Framework.Test]
public virtual void DropsDuplicateAttributes() {
// case sensitive, so should drop Four and Five
String html = "<p One=One ONE=Two one=Three One=Four ONE=Five two=Six two=Seven Two=Eight>Text</p>";
TSpdf.StyledXmlParser.Jsoup.Parser.Parser parser = TSpdf.StyledXmlParser.Jsoup.Parser.Parser.XmlParser().SetTrackErrors
(10);
Document doc = parser.ParseInput(html, "");
NUnit.Framework.Assert.AreEqual("<p One=\"One\" ONE=\"Two\" one=\"Three\" two=\"Six\" Two=\"Eight\">Text</p>"
, doc.SelectFirst("p").OuterHtml());
}
[NUnit.Framework.Test]
public virtual void ReaderClosedAfterParse() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("Hello", "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.XmlParser());
TreeBuilder treeBuilder = doc.Parser().GetTreeBuilder();
NUnit.Framework.Assert.IsNull(treeBuilder.reader);
NUnit.Framework.Assert.IsNull(treeBuilder.tokeniser);
}
[NUnit.Framework.Test]
public virtual void XmlParserEnablesXmlOutputAndEscapes() {
// Test that when using the XML parser, the output mode and escape mode default to XHTML entities
// https://github.com/jhy/jsoup/issues/1420
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p one='&lt;two&gt;&copy'>Three</p>", "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.XmlParser());
NUnit.Framework.Assert.AreEqual(doc.OutputSettings().Syntax(), TSpdf.StyledXmlParser.Jsoup.Nodes.Syntax.xml
);
NUnit.Framework.Assert.AreEqual(doc.OutputSettings().EscapeMode(), Entities.EscapeMode.xhtml);
NUnit.Framework.Assert.AreEqual("<p one=\"&lt;two>©\">Three</p>", doc.Html());
}
// only the < should be escaped
[NUnit.Framework.Test]
public virtual void XmlSyntaxEscapesLtInAttributes() {
// Regardless of the entity escape mode, make sure < is escaped in attributes when in XML
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p one='&lt;two&gt;&copy'>Three</p>", "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.XmlParser());
doc.OutputSettings().EscapeMode(Entities.EscapeMode.extended);
doc.OutputSettings().Charset("ascii");
// to make sure &copy; is output
NUnit.Framework.Assert.AreEqual(doc.OutputSettings().Syntax(), TSpdf.StyledXmlParser.Jsoup.Nodes.Syntax.xml
);
NUnit.Framework.Assert.AreEqual("<p one=\"&lt;two>&copy;\">Three</p>", doc.Html());
}
}
}

View File

@@ -0,0 +1,372 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.StyledXmlParser.Jsoup;
using TSpdf.StyledXmlParser.Jsoup.Nodes;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Safety {
/// <summary>Tests for the cleaner.</summary>
/// <author>Jonathan Hedley, jonathan@hedley.net</author>
[NUnit.Framework.Category("UnitTest")]
public class CleanerTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void SimpleBehaviourTest() {
String h = "<div><p class=foo><a href='http://evil.com'>Hello <b id=bar>there</b>!</a></div>";
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(h, Safelist.SimpleText());
NUnit.Framework.Assert.AreEqual("Hello <b>there</b>!", TextUtil.StripNewlines(cleanHtml));
}
[NUnit.Framework.Test]
public virtual void SimpleBehaviourTest2() {
String h = "Hello <b>there</b>!";
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(h, Safelist.SimpleText());
NUnit.Framework.Assert.AreEqual("Hello <b>there</b>!", TextUtil.StripNewlines(cleanHtml));
}
[NUnit.Framework.Test]
public virtual void BasicBehaviourTest() {
String h = "<div><p><a href='javascript:sendAllMoney()'>Dodgy</a> <A HREF='HTTP://nice.com/'>Nice</a></p><blockquote>Hello</blockquote>";
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(h, Safelist.Basic());
NUnit.Framework.Assert.AreEqual("<p><a rel=\"nofollow\">Dodgy</a> <a href=\"http://nice.com/\" rel=\"nofollow\">Nice</a></p><blockquote>Hello</blockquote>"
, TextUtil.StripNewlines(cleanHtml));
}
[NUnit.Framework.Test]
public virtual void BasicWithImagesTest() {
String h = "<div><p><img src='http://example.com/' alt=Image></p><p><img src='ftp://ftp.example.com'></p></div>";
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(h, Safelist.BasicWithImages());
NUnit.Framework.Assert.AreEqual("<p><img src=\"http://example.com/\" alt=\"Image\"></p><p><img></p>", TextUtil
.StripNewlines(cleanHtml));
}
[NUnit.Framework.Test]
public virtual void TestRelaxed() {
String h = "<h1>Head</h1><table><tr><td>One<td>Two</td></tr></table>";
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(h, Safelist.Relaxed());
NUnit.Framework.Assert.AreEqual("<h1>Head</h1><table><tbody><tr><td>One</td><td>Two</td></tr></tbody></table>"
, TextUtil.StripNewlines(cleanHtml));
}
[NUnit.Framework.Test]
public virtual void TestRemoveTags() {
String h = "<div><p><A HREF='HTTP://nice.com'>Nice</a></p><blockquote>Hello</blockquote>";
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(h, Safelist.Basic().RemoveTags("a"));
NUnit.Framework.Assert.AreEqual("<p>Nice</p><blockquote>Hello</blockquote>", TextUtil.StripNewlines(cleanHtml
));
}
[NUnit.Framework.Test]
public virtual void TestRemoveAttributes() {
String h = "<div><p>Nice</p><blockquote cite='http://example.com/quotations'>Hello</blockquote>";
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(h, Safelist.Basic().RemoveAttributes("blockquote"
, "cite"));
NUnit.Framework.Assert.AreEqual("<p>Nice</p><blockquote>Hello</blockquote>", TextUtil.StripNewlines(cleanHtml
));
}
[NUnit.Framework.Test]
public virtual void TestRemoveEnforcedAttributes() {
String h = "<div><p><A HREF='HTTP://nice.com/'>Nice</a></p><blockquote>Hello</blockquote>";
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(h, Safelist.Basic().RemoveEnforcedAttribute("a"
, "rel"));
NUnit.Framework.Assert.AreEqual("<p><a href=\"http://nice.com/\">Nice</a></p><blockquote>Hello</blockquote>"
, TextUtil.StripNewlines(cleanHtml));
}
[NUnit.Framework.Test]
public virtual void TestRemoveProtocols() {
String h = "<p>Contact me <a href='mailto:info@example.com'>here</a></p>";
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(h, Safelist.Basic().RemoveProtocols("a", "href"
, "ftp", "mailto"));
NUnit.Framework.Assert.AreEqual("<p>Contact me <a rel=\"nofollow\">here</a></p>", TextUtil.StripNewlines(cleanHtml
));
}
[NUnit.Framework.Test]
public virtual void TestDropComments() {
String h = "<p>Hello<!-- no --></p>";
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(h, Safelist.Relaxed());
NUnit.Framework.Assert.AreEqual("<p>Hello</p>", cleanHtml);
}
[NUnit.Framework.Test]
public virtual void TestDropXmlProc() {
String h = "<?import namespace=\"xss\"><p>Hello</p>";
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(h, Safelist.Relaxed());
NUnit.Framework.Assert.AreEqual("<p>Hello</p>", cleanHtml);
}
[NUnit.Framework.Test]
public virtual void TestDropScript() {
String h = "<SCRIPT SRC=//ha.ckers.org/.j><SCRIPT>alert(/XSS/.source)</SCRIPT>";
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(h, Safelist.Relaxed());
NUnit.Framework.Assert.AreEqual("", cleanHtml);
}
[NUnit.Framework.Test]
public virtual void TestDropImageScript() {
String h = "<IMG SRC=\"javascript:alert('XSS')\">";
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(h, Safelist.Relaxed());
NUnit.Framework.Assert.AreEqual("<img>", cleanHtml);
}
[NUnit.Framework.Test]
public virtual void TestCleanJavascriptHref() {
String h = "<A HREF=\"javascript:document.location='http://www.google.com/'\">XSS</A>";
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(h, Safelist.Relaxed());
NUnit.Framework.Assert.AreEqual("<a>XSS</a>", cleanHtml);
}
[NUnit.Framework.Test]
public virtual void TestCleanAnchorProtocol() {
String validAnchor = "<a href=\"#valid\">Valid anchor</a>";
String invalidAnchor = "<a href=\"#anchor with spaces\">Invalid anchor</a>";
// A Safelist that does not allow anchors will strip them out.
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(validAnchor, Safelist.Relaxed());
NUnit.Framework.Assert.AreEqual("<a>Valid anchor</a>", cleanHtml);
cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(invalidAnchor, Safelist.Relaxed());
NUnit.Framework.Assert.AreEqual("<a>Invalid anchor</a>", cleanHtml);
// A Safelist that allows them will keep them.
Safelist relaxedWithAnchor = Safelist.Relaxed().AddProtocols("a", "href", "#");
cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(validAnchor, relaxedWithAnchor);
NUnit.Framework.Assert.AreEqual(validAnchor, cleanHtml);
// An invalid anchor is never valid.
cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(invalidAnchor, relaxedWithAnchor);
NUnit.Framework.Assert.AreEqual("<a>Invalid anchor</a>", cleanHtml);
}
[NUnit.Framework.Test]
public virtual void TestDropsUnknownTags() {
String h = "<p><custom foo=true>Test</custom></p>";
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(h, Safelist.Relaxed());
NUnit.Framework.Assert.AreEqual("<p>Test</p>", cleanHtml);
}
[NUnit.Framework.Test]
public virtual void TestHandlesEmptyAttributes() {
String h = "<img alt=\"\" src= unknown=''>";
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(h, Safelist.BasicWithImages());
NUnit.Framework.Assert.AreEqual("<img alt=\"\">", cleanHtml);
}
[NUnit.Framework.Test]
public virtual void TestIsValidBodyHtml() {
String ok = "<p>Test <b><a href='http://example.com/' rel='nofollow'>OK</a></b></p>";
String ok1 = "<p>Test <b><a href='http://example.com/'>OK</a></b></p>";
// missing enforced is OK because still needs run thru cleaner
String nok1 = "<p><script></script>Not <b>OK</b></p>";
String nok2 = "<p align=right>Test Not <b>OK</b></p>";
String nok3 = "<!-- comment --><p>Not OK</p>";
// comments and the like will be cleaned
String nok4 = "<html><head>Foo</head><body><b>OK</b></body></html>";
// not body html
String nok5 = "<p>Test <b><a href='http://example.com/' rel='nofollowme'>OK</a></b></p>";
String nok6 = "<p>Test <b><a href='http://example.com/'>OK</b></p>";
// missing close tag
String nok7 = "</div>What";
NUnit.Framework.Assert.IsTrue(TSpdf.StyledXmlParser.Jsoup.Jsoup.IsValid(ok, Safelist.Basic()));
NUnit.Framework.Assert.IsTrue(TSpdf.StyledXmlParser.Jsoup.Jsoup.IsValid(ok1, Safelist.Basic()));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Jsoup.IsValid(nok1, Safelist.Basic()));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Jsoup.IsValid(nok2, Safelist.Basic()));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Jsoup.IsValid(nok3, Safelist.Basic()));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Jsoup.IsValid(nok4, Safelist.Basic()));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Jsoup.IsValid(nok5, Safelist.Basic()));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Jsoup.IsValid(nok6, Safelist.Basic()));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Jsoup.IsValid(ok, Safelist.None()));
NUnit.Framework.Assert.IsFalse(TSpdf.StyledXmlParser.Jsoup.Jsoup.IsValid(nok7, Safelist.Basic()));
}
[NUnit.Framework.Test]
public virtual void TestIsValidDocument() {
String ok = "<html><head></head><body><p>Hello</p></body><html>";
String nok = "<html><head><script>woops</script><title>Hello</title></head><body><p>Hello</p></body><html>";
Safelist relaxed = Safelist.Relaxed();
Cleaner cleaner = new Cleaner(relaxed);
Document okDoc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(ok);
NUnit.Framework.Assert.IsTrue(cleaner.IsValid(okDoc));
NUnit.Framework.Assert.IsFalse(cleaner.IsValid(TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(nok)));
NUnit.Framework.Assert.IsFalse(new Cleaner(Safelist.None()).IsValid(okDoc));
}
[NUnit.Framework.Test]
public virtual void ResolvesRelativeLinks() {
String html = "<a href='/foo'>Link</a><img src='/bar'>";
String clean = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, "http://example.com/", Safelist.BasicWithImages
());
NUnit.Framework.Assert.AreEqual("<a href=\"http://example.com/foo\" rel=\"nofollow\">Link</a>\n<img src=\"http://example.com/bar\">"
, clean);
}
[NUnit.Framework.Test]
public virtual void PreservesRelativeLinksIfConfigured() {
String html = "<a href='/foo'>Link</a><img src='/bar'> <img src='javascript:alert()'>";
String clean = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, "http://example.com/", Safelist.BasicWithImages
().PreserveRelativeLinks(true));
NUnit.Framework.Assert.AreEqual("<a href=\"/foo\" rel=\"nofollow\">Link</a>\n<img src=\"/bar\"> \n<img>",
clean);
}
[NUnit.Framework.Test]
public virtual void DropsUnresolvableRelativeLinks() {
String html = "<a href='/foo'>Link</a>";
String clean = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, Safelist.Basic());
NUnit.Framework.Assert.AreEqual("<a rel=\"nofollow\">Link</a>", clean);
}
[NUnit.Framework.Test]
public virtual void HandlesCustomProtocols() {
String html = "<img src='cid:12345' /> <img src='data:gzzt' />";
String dropped = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, Safelist.BasicWithImages());
NUnit.Framework.Assert.AreEqual("<img> \n<img>", dropped);
String preserved = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, Safelist.BasicWithImages().AddProtocols("img"
, "src", "cid", "data"));
NUnit.Framework.Assert.AreEqual("<img src=\"cid:12345\"> \n<img src=\"data:gzzt\">", preserved);
}
[NUnit.Framework.Test]
public virtual void HandlesAllPseudoTag() {
String html = "<p class='foo' src='bar'><a class='qux'>link</a></p>";
Safelist safelist = new Safelist().AddAttributes(":all", "class").AddAttributes("p", "style").AddTags("p",
"a");
String clean = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, safelist);
NUnit.Framework.Assert.AreEqual("<p class=\"foo\"><a class=\"qux\">link</a></p>", clean);
}
[NUnit.Framework.Test]
public virtual void AddsTagOnAttributesIfNotSet() {
String html = "<p class='foo' src='bar'>One</p>";
Safelist safelist = new Safelist().AddAttributes("p", "class");
// ^^ safelist does not have explicit tag add for p, inferred from add attributes.
String clean = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, safelist);
NUnit.Framework.Assert.AreEqual("<p class=\"foo\">One</p>", clean);
}
[NUnit.Framework.Test]
public virtual void SupplyOutputSettings() {
// test that one can override the default document output settings
OutputSettings os = new OutputSettings();
os.PrettyPrint(false);
os.EscapeMode(Entities.EscapeMode.extended);
os.Charset("ascii");
String html = "<div><p>&bernou;</p></div>";
String customOut = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, "http://foo.com/", Safelist.Relaxed(), os
);
String defaultOut = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, "http://foo.com/", Safelist.Relaxed());
NUnit.Framework.Assert.AreNotSame(defaultOut, customOut);
NUnit.Framework.Assert.AreEqual("<div><p>&Bscr;</p></div>", customOut);
// entities now prefers shorted names if aliased
NUnit.Framework.Assert.AreEqual("<div>\n" + " <p></p>\n" + "</div>", defaultOut);
os.Charset("ASCII");
os.EscapeMode(Entities.EscapeMode.@base);
String customOut2 = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, "http://foo.com/", Safelist.Relaxed(), os
);
NUnit.Framework.Assert.AreEqual("<div><p>&#x212c;</p></div>", customOut2);
}
[NUnit.Framework.Test]
public virtual void HandlesFramesets() {
String dirty = "<html><head><script></script><noscript></noscript></head><frameset><frame src=\"foo\" /><frame src=\"foo\" /></frameset></html>";
String clean = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(dirty, Safelist.Basic());
NUnit.Framework.Assert.AreEqual("", clean);
// nothing good can come out of that
Document dirtyDoc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(dirty);
Document cleanDoc = new Cleaner(Safelist.Basic()).Clean(dirtyDoc);
NUnit.Framework.Assert.IsNotNull(cleanDoc);
NUnit.Framework.Assert.AreEqual(0, cleanDoc.Body().ChildNodeSize());
}
[NUnit.Framework.Test]
public virtual void CleansInternationalText() {
NUnit.Framework.Assert.AreEqual("привет", TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean("привет", Safelist.None(
)));
}
[NUnit.Framework.Test]
public virtual void TestScriptTagInSafeList() {
Safelist safelist = Safelist.Relaxed();
safelist.AddTags("script");
NUnit.Framework.Assert.IsTrue(TSpdf.StyledXmlParser.Jsoup.Jsoup.IsValid("Hello<script>alert('Doh')</script>World !"
, safelist));
}
[NUnit.Framework.Test]
public virtual void BailsIfRemovingProtocolThatsNotSet() {
NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => {
// a case that came up on the email list
Safelist w = Safelist.None();
// note no add tag, and removing protocol without adding first
w.AddAttributes("a", "href");
w.RemoveProtocols("a", "href", "javascript");
}
);
}
// with no protocols enforced, this was a noop. Now validates.
[NUnit.Framework.Test]
public virtual void HandlesControlCharactersAfterTagName() {
String html = "<a/\x6>";
String clean = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, Safelist.Basic());
NUnit.Framework.Assert.AreEqual("<a rel=\"nofollow\"></a>", clean);
}
[NUnit.Framework.Test]
public virtual void HandlesAttributesWithNoValue() {
// https://github.com/jhy/jsoup/issues/973
String clean = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean("<a href>Clean</a>", Safelist.Basic());
NUnit.Framework.Assert.AreEqual("<a rel=\"nofollow\">Clean</a>", clean);
}
[NUnit.Framework.Test]
public virtual void HandlesNoHrefAttribute() {
String dirty = "<a>One</a> <a href>Two</a>";
Safelist relaxedWithAnchor = Safelist.Relaxed().AddProtocols("a", "href", "#");
String clean = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(dirty, relaxedWithAnchor);
NUnit.Framework.Assert.AreEqual("<a>One</a> <a>Two</a>", clean);
}
[NUnit.Framework.Test]
public virtual void HandlesNestedQuotesInAttribute() {
// https://github.com/jhy/jsoup/issues/1243 - no repro
String orig = "<div style=\"font-family: 'Calibri'\">Will (not) fail</div>";
Safelist allow = Safelist.Relaxed().AddAttributes("div", "style");
String clean = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(orig, allow);
bool isValid = TSpdf.StyledXmlParser.Jsoup.Jsoup.IsValid(orig, allow);
NUnit.Framework.Assert.AreEqual(orig, TextUtil.StripNewlines(clean));
// only difference is pretty print wrap & indent
NUnit.Framework.Assert.IsTrue(isValid);
}
[NUnit.Framework.Test]
public virtual void CopiesOutputSettings() {
Document orig = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p>test<br></p>");
orig.OutputSettings().Syntax(TSpdf.StyledXmlParser.Jsoup.Nodes.Syntax.xml);
orig.OutputSettings().EscapeMode(Entities.EscapeMode.xhtml);
Safelist whitelist = Safelist.None().AddTags("p", "br");
Document result = new Cleaner(whitelist).Clean(orig);
NUnit.Framework.Assert.AreEqual(TSpdf.StyledXmlParser.Jsoup.Nodes.Syntax.xml, result.OutputSettings().Syntax
());
NUnit.Framework.Assert.AreEqual("<p>test<br /></p>", result.Body().Html());
}
}
}

View File

@@ -0,0 +1,119 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.StyledXmlParser.Jsoup.Nodes;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Safety {
/// <summary>
/// Tests for the deprecated
/// <see cref="Whitelist"/>
/// class source compatibility.
/// </summary>
/// <remarks>
/// Tests for the deprecated
/// <see cref="Whitelist"/>
/// class source compatibility. Will be removed in
/// <c>v.1.15.1</c>. No net new tests here so safe to blow up.
/// </remarks>
[NUnit.Framework.Category("UnitTest")]
public class CompatibilityTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void ResolvesRelativeLinks() {
String html = "<a href='/foo'>Link</a><img src='/bar'>";
String clean = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, "http://example.com/", ((Whitelist)Whitelist.
BasicWithImages()));
NUnit.Framework.Assert.AreEqual("<a href=\"http://example.com/foo\" rel=\"nofollow\">Link</a>\n<img src=\"http://example.com/bar\">"
, clean);
}
[NUnit.Framework.Test]
public virtual void TestDropsUnknownTags() {
String h = "<p><custom foo=true>Test</custom></p>";
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(h, ((Whitelist)Whitelist.Relaxed()));
NUnit.Framework.Assert.AreEqual("<p>Test</p>", cleanHtml);
}
[NUnit.Framework.Test]
public virtual void PreservesRelativeLinksIfConfigured() {
String html = "<a href='/foo'>Link</a><img src='/bar'> <img src='javascript:alert()'>";
String clean = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, "http://example.com/", ((Whitelist)Whitelist.
BasicWithImages()).PreserveRelativeLinks(true));
NUnit.Framework.Assert.AreEqual("<a href=\"/foo\" rel=\"nofollow\">Link</a>\n<img src=\"/bar\"> \n<img>",
clean);
}
[NUnit.Framework.Test]
public virtual void HandlesCustomProtocols() {
String html = "<img src='cid:12345' /> <img src='data:gzzt' />";
String dropped = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, ((Whitelist)Whitelist.BasicWithImages()));
NUnit.Framework.Assert.AreEqual("<img> \n<img>", dropped);
String preserved = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, ((Whitelist)Whitelist.BasicWithImages()).
AddProtocols("img", "src", "cid", "data"));
NUnit.Framework.Assert.AreEqual("<img src=\"cid:12345\"> \n<img src=\"data:gzzt\">", preserved);
}
[NUnit.Framework.Test]
public virtual void HandlesFramesets() {
String dirty = "<html><head><script></script><noscript></noscript></head><frameset><frame src=\"foo\" /><frame src=\"foo\" /></frameset></html>";
String clean = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(dirty, ((Whitelist)Whitelist.Basic()));
NUnit.Framework.Assert.AreEqual("", clean);
// nothing good can come out of that
Document dirtyDoc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(dirty);
Document cleanDoc = new Cleaner(((Whitelist)Whitelist.Basic())).Clean(dirtyDoc);
NUnit.Framework.Assert.IsNotNull(cleanDoc);
NUnit.Framework.Assert.AreEqual(0, cleanDoc.Body().ChildNodeSize());
}
[NUnit.Framework.Test]
public virtual void HandlesCleanerFromWhitelist() {
Cleaner cleaner = new Cleaner(((Whitelist)Whitelist.Basic()));
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<script>Script</script><p>Text</p>");
Document clean = cleaner.Clean(doc);
NUnit.Framework.Assert.AreEqual("<p>Text</p>", clean.Body().Html());
}
[NUnit.Framework.Test]
public virtual void SupplyOutputSettings() {
// test that one can override the default document output settings
OutputSettings os = new OutputSettings();
os.PrettyPrint(false);
os.EscapeMode(Entities.EscapeMode.extended);
os.Charset("ascii");
String html = "<div><p>&bernou;</p></div>";
String customOut = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, "http://foo.com/", ((Whitelist)Whitelist.
Relaxed()), os);
String defaultOut = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, "http://foo.com/", ((Whitelist)Whitelist
.Relaxed()));
NUnit.Framework.Assert.AreNotSame(defaultOut, customOut);
NUnit.Framework.Assert.AreEqual("<div><p>&Bscr;</p></div>", customOut);
// entities now prefers shorted names if aliased
NUnit.Framework.Assert.AreEqual("<div>\n" + " <p></p>\n" + "</div>", defaultOut);
os.Charset("ASCII");
os.EscapeMode(Entities.EscapeMode.@base);
String customOut2 = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean(html, "http://foo.com/", ((Whitelist)Whitelist
.Relaxed()), os);
NUnit.Framework.Assert.AreEqual("<div><p>&#x212c;</p></div>", customOut2);
}
}
}

View File

@@ -0,0 +1,88 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using TSpdf.Commons.Utils;
using TSpdf.IO.Util;
using TSpdf.StyledXmlParser.Jsoup;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Safety {
[NUnit.Framework.TestFixtureSource("LocalesTestFixtureData")]
public class MultiLocaleTest : ExtendedTSpdfTest {
private readonly CultureInfo defaultLocale = System.Threading.Thread.CurrentThread.CurrentUICulture;
public static ICollection<CultureInfo> Locales() {
return JavaUtil.ArraysAsList(System.Globalization.CultureInfo.InvariantCulture, new CultureInfo("tr", false
));
}
public static ICollection<NUnit.Framework.TestFixtureData> LocalesTestFixtureData() {
return Locales().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList();
}
[NUnit.Framework.TearDown]
public virtual void SetDefaultLocale() {
System.Threading.Thread.CurrentThread.CurrentUICulture = defaultLocale;
}
private CultureInfo locale;
public MultiLocaleTest(CultureInfo locale) {
this.locale = locale;
}
public MultiLocaleTest(CultureInfo[] array)
: this(array[0]) {
}
[NUnit.Framework.Test]
public virtual void SafeListedProtocolShouldBeRetained() {
System.Threading.Thread.CurrentThread.CurrentUICulture = locale;
Whitelist safelist = (Whitelist)((Whitelist)Whitelist.None()).AddTags("a").AddAttributes("a", "href").AddProtocols
("a", "href", "something");
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean("<a href=\"SOMETHING://x\"></a>", safelist);
NUnit.Framework.Assert.AreEqual("<a href=\"something://x/\"></a>", TextUtil.StripNewlines(cleanHtml));
}
[NUnit.Framework.Test]
public virtual void CleanerSafeListedProtocolShouldBeRetained() {
System.Threading.Thread.CurrentThread.CurrentUICulture = locale;
Safelist safelist = Safelist.None().AddTags("a").AddAttributes("a", "href").AddProtocols("a", "href", "something"
);
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean("<a href=\"SOMETHING://x\"></a>", safelist);
NUnit.Framework.Assert.AreEqual("<a href=\"something://x/\"></a>", TextUtil.StripNewlines(cleanHtml));
}
[NUnit.Framework.Test]
public virtual void CompatibilitySafeListedProtocolShouldBeRetained() {
System.Threading.Thread.CurrentThread.CurrentUICulture = locale;
Whitelist safelist = (Whitelist)((Whitelist)Whitelist.None()).AddTags("a").AddAttributes("a", "href").AddProtocols
("a", "href", "something");
String cleanHtml = TSpdf.StyledXmlParser.Jsoup.Jsoup.Clean("<a href=\"SOMETHING://x\"></a>", safelist);
NUnit.Framework.Assert.AreEqual("<a href=\"something://x/\"></a>", TextUtil.StripNewlines(cleanHtml));
}
}
}

View File

@@ -0,0 +1,230 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Text;
using TSpdf.Commons.Utils;
using TSpdf.StyledXmlParser.Jsoup.Nodes;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Select {
[NUnit.Framework.Category("UnitTest")]
public class CssTest : ExtendedTSpdfTest {
private Document html = null;
private static String htmlString;
[NUnit.Framework.OneTimeSetUp]
public static void InitClass() {
StringBuilder sb = new StringBuilder("<html><head></head><body>");
sb.Append("<div id='pseudo'>");
for (int i = 1; i <= 10; i++) {
sb.Append(MessageFormatUtil.Format("<p>{0}</p>", i));
}
sb.Append("</div>");
sb.Append("<div id='type'>");
for (int i = 1; i <= 10; i++) {
sb.Append(MessageFormatUtil.Format("<p>{0}</p>", i));
sb.Append(MessageFormatUtil.Format("<span>{0}</span>", i));
sb.Append(MessageFormatUtil.Format("<em>{0}</em>", i));
sb.Append(MessageFormatUtil.Format("<svg>{0}</svg>", i));
}
sb.Append("</div>");
sb.Append("<span id='onlySpan'><br /></span>");
sb.Append("<p class='empty'><!-- Comment only is still empty! --></p>");
sb.Append("<div id='only'>");
sb.Append("Some text before the <em>only</em> child in this div");
sb.Append("</div>");
sb.Append("</body></html>");
htmlString = sb.ToString();
}
[NUnit.Framework.SetUp]
public virtual void Init() {
html = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(htmlString);
}
[NUnit.Framework.Test]
public virtual void FirstChild() {
Check(html.Select("#pseudo :first-child"), "1");
Check(html.Select("html:first-child"));
}
[NUnit.Framework.Test]
public virtual void LastChild() {
Check(html.Select("#pseudo :last-child"), "10");
Check(html.Select("html:last-child"));
}
[NUnit.Framework.Test]
public virtual void NthChild_simple() {
for (int i = 1; i <= 10; i++) {
Check(html.Select(MessageFormatUtil.Format("#pseudo :nth-child({0})", i)), i.ToString());
}
}
[NUnit.Framework.Test]
public virtual void NthOfType_unknownTag() {
for (int i = 1; i <= 10; i++) {
Check(html.Select(MessageFormatUtil.Format("#type svg:nth-of-type({0})", i)), i.ToString());
}
}
[NUnit.Framework.Test]
public virtual void NthLastChild_simple() {
for (int i = 1; i <= 10; i++) {
Check(html.Select(MessageFormatUtil.Format("#pseudo :nth-last-child({0})", i)), (11 - i).ToString());
}
}
[NUnit.Framework.Test]
public virtual void NthOfType_simple() {
for (int i = 1; i <= 10; i++) {
Check(html.Select(MessageFormatUtil.Format("#type p:nth-of-type({0})", i)), i.ToString());
}
}
[NUnit.Framework.Test]
public virtual void NthLastOfType_simple() {
for (int i = 1; i <= 10; i++) {
Check(html.Select(MessageFormatUtil.Format("#type :nth-last-of-type({0})", i)), (11 - i).ToString(), (11 -
i).ToString(), (11 - i).ToString(), (11 - i).ToString());
}
}
[NUnit.Framework.Test]
public virtual void NthChild_advanced() {
Check(html.Select("#pseudo :nth-child(-5)"));
Check(html.Select("#pseudo :nth-child(odd)"), "1", "3", "5", "7", "9");
Check(html.Select("#pseudo :nth-child(2n-1)"), "1", "3", "5", "7", "9");
Check(html.Select("#pseudo :nth-child(2n+1)"), "1", "3", "5", "7", "9");
Check(html.Select("#pseudo :nth-child(2n+3)"), "3", "5", "7", "9");
Check(html.Select("#pseudo :nth-child(even)"), "2", "4", "6", "8", "10");
Check(html.Select("#pseudo :nth-child(2n)"), "2", "4", "6", "8", "10");
Check(html.Select("#pseudo :nth-child(3n-1)"), "2", "5", "8");
Check(html.Select("#pseudo :nth-child(-2n+5)"), "1", "3", "5");
Check(html.Select("#pseudo :nth-child(+5)"), "5");
}
[NUnit.Framework.Test]
public virtual void NthOfType_advanced() {
Check(html.Select("#type :nth-of-type(-5)"));
Check(html.Select("#type p:nth-of-type(odd)"), "1", "3", "5", "7", "9");
Check(html.Select("#type em:nth-of-type(2n-1)"), "1", "3", "5", "7", "9");
Check(html.Select("#type p:nth-of-type(2n+1)"), "1", "3", "5", "7", "9");
Check(html.Select("#type span:nth-of-type(2n+3)"), "3", "5", "7", "9");
Check(html.Select("#type p:nth-of-type(even)"), "2", "4", "6", "8", "10");
Check(html.Select("#type p:nth-of-type(2n)"), "2", "4", "6", "8", "10");
Check(html.Select("#type p:nth-of-type(3n-1)"), "2", "5", "8");
Check(html.Select("#type p:nth-of-type(-2n+5)"), "1", "3", "5");
Check(html.Select("#type :nth-of-type(+5)"), "5", "5", "5", "5");
}
[NUnit.Framework.Test]
public virtual void NthLastChild_advanced() {
Check(html.Select("#pseudo :nth-last-child(-5)"));
Check(html.Select("#pseudo :nth-last-child(odd)"), "2", "4", "6", "8", "10");
Check(html.Select("#pseudo :nth-last-child(2n-1)"), "2", "4", "6", "8", "10");
Check(html.Select("#pseudo :nth-last-child(2n+1)"), "2", "4", "6", "8", "10");
Check(html.Select("#pseudo :nth-last-child(2n+3)"), "2", "4", "6", "8");
Check(html.Select("#pseudo :nth-last-child(even)"), "1", "3", "5", "7", "9");
Check(html.Select("#pseudo :nth-last-child(2n)"), "1", "3", "5", "7", "9");
Check(html.Select("#pseudo :nth-last-child(3n-1)"), "3", "6", "9");
Check(html.Select("#pseudo :nth-last-child(-2n+5)"), "6", "8", "10");
Check(html.Select("#pseudo :nth-last-child(+5)"), "6");
}
[NUnit.Framework.Test]
public virtual void NthLastOfType_advanced() {
Check(html.Select("#type :nth-last-of-type(-5)"));
Check(html.Select("#type p:nth-last-of-type(odd)"), "2", "4", "6", "8", "10");
Check(html.Select("#type em:nth-last-of-type(2n-1)"), "2", "4", "6", "8", "10");
Check(html.Select("#type p:nth-last-of-type(2n+1)"), "2", "4", "6", "8", "10");
Check(html.Select("#type span:nth-last-of-type(2n+3)"), "2", "4", "6", "8");
Check(html.Select("#type p:nth-last-of-type(even)"), "1", "3", "5", "7", "9");
Check(html.Select("#type p:nth-last-of-type(2n)"), "1", "3", "5", "7", "9");
Check(html.Select("#type p:nth-last-of-type(3n-1)"), "3", "6", "9");
Check(html.Select("#type span:nth-last-of-type(-2n+5)"), "6", "8", "10");
Check(html.Select("#type :nth-last-of-type(+5)"), "6", "6", "6", "6");
}
[NUnit.Framework.Test]
public virtual void FirstOfType() {
Check(html.Select("div:not(#only) :first-of-type"), "1", "1", "1", "1", "1");
}
[NUnit.Framework.Test]
public virtual void LastOfType() {
Check(html.Select("div:not(#only) :last-of-type"), "10", "10", "10", "10", "10");
}
[NUnit.Framework.Test]
public virtual void Empty() {
Elements sel = html.Select(":empty");
NUnit.Framework.Assert.AreEqual(3, sel.Count);
NUnit.Framework.Assert.AreEqual("head", sel[0].TagName());
NUnit.Framework.Assert.AreEqual("br", sel[1].TagName());
NUnit.Framework.Assert.AreEqual("p", sel[2].TagName());
}
[NUnit.Framework.Test]
public virtual void OnlyChild() {
Elements sel = html.Select("span :only-child");
NUnit.Framework.Assert.AreEqual(1, sel.Count);
NUnit.Framework.Assert.AreEqual("br", sel[0].TagName());
Check(html.Select("#only :only-child"), "only");
}
[NUnit.Framework.Test]
public virtual void OnlyOfType() {
Elements sel = html.Select(":only-of-type");
NUnit.Framework.Assert.AreEqual(6, sel.Count);
NUnit.Framework.Assert.AreEqual("head", sel[0].TagName());
NUnit.Framework.Assert.AreEqual("body", sel[1].TagName());
NUnit.Framework.Assert.AreEqual("span", sel[2].TagName());
NUnit.Framework.Assert.AreEqual("br", sel[3].TagName());
NUnit.Framework.Assert.AreEqual("p", sel[4].TagName());
NUnit.Framework.Assert.IsTrue(sel[4].HasClass("empty"));
NUnit.Framework.Assert.AreEqual("em", sel[5].TagName());
}
protected internal virtual void Check(Elements result, params String[] expectedContent) {
NUnit.Framework.Assert.AreEqual(expectedContent.Length, result.Count);
for (int i = 0; i < expectedContent.Length; i++) {
NUnit.Framework.Assert.IsNotNull(result[i]);
NUnit.Framework.Assert.AreEqual(expectedContent[i], result[i].OwnText());
}
}
[NUnit.Framework.Test]
public virtual void Root() {
Elements sel = html.Select(":root");
NUnit.Framework.Assert.AreEqual(1, sel.Count);
NUnit.Framework.Assert.IsNotNull(sel[0]);
NUnit.Framework.Assert.AreEqual(TSpdf.StyledXmlParser.Jsoup.Parser.Tag.ValueOf("html"), sel[0].Tag());
Elements sel2 = html.Select("body").Select(":root");
NUnit.Framework.Assert.AreEqual(1, sel2.Count);
NUnit.Framework.Assert.IsNotNull(sel2[0]);
NUnit.Framework.Assert.AreEqual(TSpdf.StyledXmlParser.Jsoup.Parser.Tag.ValueOf("body"), sel2[0].Tag());
}
}
}

View File

@@ -0,0 +1,503 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using System.Text;
using TSpdf.StyledXmlParser.Jsoup;
using TSpdf.StyledXmlParser.Jsoup.Nodes;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Select {
/// <summary>Tests for ElementList.</summary>
/// <author>Jonathan Hedley, jonathan@hedley.net</author>
public class ElementsTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void Filter() {
String h = "<p>Excl</p><div class=headline><p>Hello</p><p>There</p></div><div class=headline><h1>Headline</h1></div>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
Elements els = doc.Select(".headline").Select("p");
NUnit.Framework.Assert.AreEqual(2, els.Count);
NUnit.Framework.Assert.AreEqual("Hello", els[0].Text());
NUnit.Framework.Assert.AreEqual("There", els[1].Text());
}
[NUnit.Framework.Test]
public virtual void Attributes() {
String h = "<p title=foo><p title=bar><p class=foo><p class=bar>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
Elements withTitle = doc.Select("p[title]");
NUnit.Framework.Assert.AreEqual(2, withTitle.Count);
NUnit.Framework.Assert.IsTrue(withTitle.HasAttr("title"));
NUnit.Framework.Assert.IsFalse(withTitle.HasAttr("class"));
NUnit.Framework.Assert.AreEqual("foo", withTitle.Attr("title"));
withTitle.RemoveAttr("title");
NUnit.Framework.Assert.AreEqual(2, withTitle.Count);
// existing Elements are not reevaluated
NUnit.Framework.Assert.AreEqual(0, doc.Select("p[title]").Count);
Elements ps = doc.Select("p").Attr("style", "classy");
NUnit.Framework.Assert.AreEqual(4, ps.Count);
NUnit.Framework.Assert.AreEqual("classy", ps.Last().Attr("style"));
NUnit.Framework.Assert.AreEqual("bar", ps.Last().Attr("class"));
}
[NUnit.Framework.Test]
public virtual void HasAttr() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p title=foo><p title=bar><p class=foo><p class=bar>"
);
Elements ps = doc.Select("p");
NUnit.Framework.Assert.IsTrue(ps.HasAttr("class"));
NUnit.Framework.Assert.IsFalse(ps.HasAttr("style"));
}
[NUnit.Framework.Test]
public virtual void HasAbsAttr() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<a id=1 href='/foo'>One</a> <a id=2 href='https://jsoup.org'>Two</a>"
);
Elements one = doc.Select("#1");
Elements two = doc.Select("#2");
Elements both = doc.Select("a");
NUnit.Framework.Assert.IsFalse(one.HasAttr("abs:href"));
NUnit.Framework.Assert.IsTrue(two.HasAttr("abs:href"));
NUnit.Framework.Assert.IsTrue(both.HasAttr("abs:href"));
}
// hits on #2
[NUnit.Framework.Test]
public virtual void Attr() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p title=foo><p title=bar><p class=foo><p class=bar>"
);
String classVal = doc.Select("p").Attr("class");
NUnit.Framework.Assert.AreEqual("foo", classVal);
}
[NUnit.Framework.Test]
public virtual void AbsAttr() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<a id=1 href='/foo'>One</a> <a id=2 href='https://jsoup.org/'>Two</a>"
);
Elements one = doc.Select("#1");
Elements two = doc.Select("#2");
Elements both = doc.Select("a");
NUnit.Framework.Assert.AreEqual("", one.Attr("abs:href"));
NUnit.Framework.Assert.AreEqual("https://jsoup.org/", two.Attr("abs:href"));
NUnit.Framework.Assert.AreEqual("https://jsoup.org/", both.Attr("abs:href"));
}
[NUnit.Framework.Test]
public virtual void Classes() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p class='mellow yellow'></p><p class='red green'></p>"
);
Elements els = doc.Select("p");
NUnit.Framework.Assert.IsTrue(els.HasClass("red"));
NUnit.Framework.Assert.IsFalse(els.HasClass("blue"));
els.AddClass("blue");
els.RemoveClass("yellow");
els.ToggleClass("mellow");
NUnit.Framework.Assert.AreEqual("blue", els[0].ClassName());
NUnit.Framework.Assert.AreEqual("red green blue mellow", els[1].ClassName());
}
[NUnit.Framework.Test]
public virtual void HasClassCaseInsensitive() {
Elements els = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p Class=One>One <p class=Two>Two <p CLASS=THREE>THREE"
).Select("p");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element one = els[0];
TSpdf.StyledXmlParser.Jsoup.Nodes.Element two = els[1];
TSpdf.StyledXmlParser.Jsoup.Nodes.Element thr = els[2];
NUnit.Framework.Assert.IsTrue(one.HasClass("One"));
NUnit.Framework.Assert.IsTrue(one.HasClass("ONE"));
NUnit.Framework.Assert.IsTrue(two.HasClass("TWO"));
NUnit.Framework.Assert.IsTrue(two.HasClass("Two"));
NUnit.Framework.Assert.IsTrue(thr.HasClass("ThreE"));
NUnit.Framework.Assert.IsTrue(thr.HasClass("three"));
}
[NUnit.Framework.Test]
public virtual void Text() {
String h = "<div><p>Hello<p>there<p>world</div>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
NUnit.Framework.Assert.AreEqual("Hello there world", doc.Select("div > *").Text());
}
[NUnit.Framework.Test]
public virtual void HasText() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>Hello</p></div><div><p></p></div>");
Elements divs = doc.Select("div");
NUnit.Framework.Assert.IsTrue(divs.HasText());
NUnit.Framework.Assert.IsFalse(doc.Select("div + div").HasText());
}
[NUnit.Framework.Test]
public virtual void Html() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>Hello</p></div><div><p>There</p></div>");
Elements divs = doc.Select("div");
NUnit.Framework.Assert.AreEqual("<p>Hello</p>\n<p>There</p>", divs.Html());
}
[NUnit.Framework.Test]
public virtual void OuterHtml() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>Hello</p></div><div><p>There</p></div>");
Elements divs = doc.Select("div");
NUnit.Framework.Assert.AreEqual("<div><p>Hello</p></div><div><p>There</p></div>", TextUtil.StripNewlines(divs
.OuterHtml()));
}
[NUnit.Framework.Test]
public virtual void SetHtml() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p>One</p><p>Two</p><p>Three</p>");
Elements ps = doc.Select("p");
ps.Prepend("<b>Bold</b>").Append("<i>Ital</i>");
NUnit.Framework.Assert.AreEqual("<p><b>Bold</b>Two<i>Ital</i></p>", TextUtil.StripNewlines(ps[1].OuterHtml
()));
ps.Html("<span>Gone</span>");
NUnit.Framework.Assert.AreEqual("<p><span>Gone</span></p>", TextUtil.StripNewlines(ps[1].OuterHtml()));
}
[NUnit.Framework.Test]
public virtual void Val() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<input value='one' /><textarea>two</textarea>");
Elements els = doc.Select("input, textarea");
NUnit.Framework.Assert.AreEqual(2, els.Count);
NUnit.Framework.Assert.AreEqual("one", els.Val());
NUnit.Framework.Assert.AreEqual("two", els.Last().Val());
els.Val("three");
NUnit.Framework.Assert.AreEqual("three", els.First().Val());
NUnit.Framework.Assert.AreEqual("three", els.Last().Val());
NUnit.Framework.Assert.AreEqual("<textarea>three</textarea>", els.Last().OuterHtml());
}
[NUnit.Framework.Test]
public virtual void Before() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p>This <a>is</a> <a>jsoup</a>.</p>");
doc.Select("a").Before("<span>foo</span>");
NUnit.Framework.Assert.AreEqual("<p>This <span>foo</span><a>is</a> <span>foo</span><a>jsoup</a>.</p>", TextUtil
.StripNewlines(doc.Body().Html()));
}
[NUnit.Framework.Test]
public virtual void After() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p>This <a>is</a> <a>jsoup</a>.</p>");
doc.Select("a").After("<span>foo</span>");
NUnit.Framework.Assert.AreEqual("<p>This <a>is</a><span>foo</span> <a>jsoup</a><span>foo</span>.</p>", TextUtil
.StripNewlines(doc.Body().Html()));
}
[NUnit.Framework.Test]
public virtual void Wrap() {
String h = "<p><b>This</b> is <b>jsoup</b></p>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
doc.Select("b").Wrap("<i></i>");
NUnit.Framework.Assert.AreEqual("<p><i><b>This</b></i> is <i><b>jsoup</b></i></p>", doc.Body().Html());
}
[NUnit.Framework.Test]
public virtual void WrapDiv() {
String h = "<p><b>This</b> is <b>jsoup</b>.</p> <p>How do you like it?</p>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
doc.Select("p").Wrap("<div></div>");
NUnit.Framework.Assert.AreEqual("<div><p><b>This</b> is <b>jsoup</b>.</p></div> <div><p>How do you like it?</p></div>"
, TextUtil.StripNewlines(doc.Body().Html()));
}
[NUnit.Framework.Test]
public virtual void Unwrap() {
String h = "<div><font>One</font> <font><a href=\"/\">Two</a></font></div";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
doc.Select("font").Unwrap();
NUnit.Framework.Assert.AreEqual("<div>One <a href=\"/\">Two</a></div>", TextUtil.StripNewlines(doc.Body().
Html()));
}
[NUnit.Framework.Test]
public virtual void UnwrapP() {
String h = "<p><a>One</a> Two</p> Three <i>Four</i> <p>Fix <i>Six</i></p>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
doc.Select("p").Unwrap();
NUnit.Framework.Assert.AreEqual("<a>One</a> Two Three <i>Four</i> Fix <i>Six</i>", TextUtil.StripNewlines(
doc.Body().Html()));
}
[NUnit.Framework.Test]
public virtual void UnwrapKeepsSpace() {
String h = "<p>One <span>two</span> <span>three</span> four</p>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
doc.Select("span").Unwrap();
NUnit.Framework.Assert.AreEqual("<p>One two three four</p>", doc.Body().Html());
}
[NUnit.Framework.Test]
public virtual void Empty() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>Hello <b>there</b></p> <p>now!</p></div>");
doc.OutputSettings().PrettyPrint(false);
doc.Select("p").Empty();
NUnit.Framework.Assert.AreEqual("<div><p></p> <p></p></div>", doc.Body().Html());
}
[NUnit.Framework.Test]
public virtual void Remove() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>Hello <b>there</b></p> jsoup <p>now!</p></div>"
);
doc.OutputSettings().PrettyPrint(false);
doc.Select("p").Remove();
NUnit.Framework.Assert.AreEqual("<div> jsoup </div>", doc.Body().Html());
}
[NUnit.Framework.Test]
public virtual void Eq() {
String h = "<p>Hello<p>there<p>world";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
NUnit.Framework.Assert.AreEqual("there", doc.Select("p").Eq(1).Text());
NUnit.Framework.Assert.AreEqual("there", doc.Select("p")[1].Text());
}
[NUnit.Framework.Test]
public virtual void Is() {
String h = "<p>Hello<p title=foo>there<p>world";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
Elements ps = doc.Select("p");
NUnit.Framework.Assert.IsTrue(ps.Is("[title=foo]"));
NUnit.Framework.Assert.IsFalse(ps.Is("[title=bar]"));
}
[NUnit.Framework.Test]
public virtual void Parents() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>Hello</p></div><p>There</p>");
Elements parents = doc.Select("p").Parents();
NUnit.Framework.Assert.AreEqual(3, parents.Count);
NUnit.Framework.Assert.AreEqual("div", parents[0].TagName());
NUnit.Framework.Assert.AreEqual("body", parents[1].TagName());
NUnit.Framework.Assert.AreEqual("html", parents[2].TagName());
}
[NUnit.Framework.Test]
public virtual void Not() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div id=1><p>One</p></div> <div id=2><p><span>Two</span></p></div>"
);
Elements div1 = doc.Select("div").Not(":has(p > span)");
NUnit.Framework.Assert.AreEqual(1, div1.Count);
NUnit.Framework.Assert.AreEqual("1", div1.First().Id());
Elements div2 = doc.Select("div").Not("#1");
NUnit.Framework.Assert.AreEqual(1, div2.Count);
NUnit.Framework.Assert.AreEqual("2", div2.First().Id());
}
[NUnit.Framework.Test]
public virtual void TagNameSet() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p>Hello <i>there</i> <i>now</i></p>");
doc.Select("i").TagName("em");
NUnit.Framework.Assert.AreEqual("<p>Hello <em>there</em> <em>now</em></p>", doc.Body().Html());
}
[NUnit.Framework.Test]
public virtual void Traverse() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>Hello</p></div><div>There</div>");
StringBuilder accum = new StringBuilder();
doc.Select("div").Traverse(new _NodeVisitor_278(accum));
NUnit.Framework.Assert.AreEqual("<div><p><#text></#text></p></div><div><#text></#text></div>", accum.ToString
());
}
private sealed class _NodeVisitor_278 : NodeVisitor {
public _NodeVisitor_278(StringBuilder accum) {
this.accum = accum;
}
public void Head(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
accum.Append("<").Append(node.NodeName()).Append(">");
}
public void Tail(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
accum.Append("</").Append(node.NodeName()).Append(">");
}
private readonly StringBuilder accum;
}
[NUnit.Framework.Test]
public virtual void Forms() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<form id=1><input name=q></form><div /><form id=2><input name=f></form>"
);
Elements els = doc.Select("form, div");
NUnit.Framework.Assert.AreEqual(3, els.Count);
IList<FormElement> forms = els.Forms();
NUnit.Framework.Assert.AreEqual(2, forms.Count);
NUnit.Framework.Assert.IsNotNull(forms[0]);
NUnit.Framework.Assert.IsNotNull(forms[1]);
NUnit.Framework.Assert.AreEqual("1", forms[0].Id());
NUnit.Framework.Assert.AreEqual("2", forms[1].Id());
}
[NUnit.Framework.Test]
public virtual void Comments() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<!-- comment1 --><p><!-- comment2 --><p class=two><!-- comment3 -->"
);
IList<Comment> comments = doc.Select("p").Comments();
NUnit.Framework.Assert.AreEqual(2, comments.Count);
NUnit.Framework.Assert.AreEqual(" comment2 ", comments[0].GetData());
NUnit.Framework.Assert.AreEqual(" comment3 ", comments[1].GetData());
IList<Comment> comments1 = doc.Select("p.two").Comments();
NUnit.Framework.Assert.AreEqual(1, comments1.Count);
NUnit.Framework.Assert.AreEqual(" comment3 ", comments1[0].GetData());
}
[NUnit.Framework.Test]
public virtual void TextNodes() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("One<p>Two<a>Three</a><p>Four</p>Five");
IList<TextNode> textNodes = doc.Select("p").TextNodes();
NUnit.Framework.Assert.AreEqual(2, textNodes.Count);
NUnit.Framework.Assert.AreEqual("Two", textNodes[0].Text());
NUnit.Framework.Assert.AreEqual("Four", textNodes[1].Text());
}
[NUnit.Framework.Test]
public virtual void DataNodes() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p>One</p><script>Two</script><style>Three</style>"
);
IList<DataNode> dataNodes = doc.Select("p, script, style").DataNodes();
NUnit.Framework.Assert.AreEqual(2, dataNodes.Count);
NUnit.Framework.Assert.AreEqual("Two", dataNodes[0].GetWholeData());
NUnit.Framework.Assert.AreEqual("Three", dataNodes[1].GetWholeData());
doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<head><script type=application/json><crux></script><script src=foo>Blah</script>"
);
Elements script = doc.Select("script[type=application/json]");
IList<DataNode> scriptNode = script.DataNodes();
NUnit.Framework.Assert.AreEqual(1, scriptNode.Count);
DataNode dataNode = scriptNode[0];
NUnit.Framework.Assert.AreEqual("<crux>", dataNode.GetWholeData());
// check if they're live
dataNode.SetWholeData("<cromulent>");
NUnit.Framework.Assert.AreEqual("<script type=\"application/json\"><cromulent></script>", script.OuterHtml
());
}
[NUnit.Framework.Test]
public virtual void NodesEmpty() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p>");
NUnit.Framework.Assert.AreEqual(0, doc.Select("form").TextNodes().Count);
}
[NUnit.Framework.Test]
public virtual void ClassWithHyphen() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p class='tab-nav'>Check</p>");
Elements els = doc.GetElementsByClass("tab-nav");
NUnit.Framework.Assert.AreEqual(1, els.Count);
NUnit.Framework.Assert.AreEqual("Check", els.Text());
}
[NUnit.Framework.Test]
public virtual void Siblings() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>1<p>2<p>3<p>4<p>5<p>6</div><div><p>7<p>8<p>9<p>10<p>11<p>12</div>"
);
Elements els = doc.Select("p:eq(3)");
// gets p4 and p10
NUnit.Framework.Assert.AreEqual(2, els.Count);
Elements next = els.Next();
NUnit.Framework.Assert.AreEqual(2, next.Count);
NUnit.Framework.Assert.AreEqual("5", next.First().Text());
NUnit.Framework.Assert.AreEqual("11", next.Last().Text());
NUnit.Framework.Assert.AreEqual(0, els.Next("p:contains(6)").Count);
Elements nextF = els.Next("p:contains(5)");
NUnit.Framework.Assert.AreEqual(1, nextF.Count);
NUnit.Framework.Assert.AreEqual("5", nextF.First().Text());
Elements nextA = els.NextAll();
NUnit.Framework.Assert.AreEqual(4, nextA.Count);
NUnit.Framework.Assert.AreEqual("5", nextA.First().Text());
NUnit.Framework.Assert.AreEqual("12", nextA.Last().Text());
Elements nextAF = els.NextAll("p:contains(6)");
NUnit.Framework.Assert.AreEqual(1, nextAF.Count);
NUnit.Framework.Assert.AreEqual("6", nextAF.First().Text());
Elements prev = els.Prev();
NUnit.Framework.Assert.AreEqual(2, prev.Count);
NUnit.Framework.Assert.AreEqual("3", prev.First().Text());
NUnit.Framework.Assert.AreEqual("9", prev.Last().Text());
NUnit.Framework.Assert.AreEqual(0, els.Prev("p:contains(1)").Count);
Elements prevF = els.Prev("p:contains(3)");
NUnit.Framework.Assert.AreEqual(1, prevF.Count);
NUnit.Framework.Assert.AreEqual("3", prevF.First().Text());
Elements prevA = els.PrevAll();
NUnit.Framework.Assert.AreEqual(6, prevA.Count);
NUnit.Framework.Assert.AreEqual("3", prevA.First().Text());
NUnit.Framework.Assert.AreEqual("7", prevA.Last().Text());
Elements prevAF = els.PrevAll("p:contains(1)");
NUnit.Framework.Assert.AreEqual(1, prevAF.Count);
NUnit.Framework.Assert.AreEqual("1", prevAF.First().Text());
}
[NUnit.Framework.Test]
public virtual void EachText() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>1<p>2<p>3<p>4<p>5<p>6</div><div><p>7<p>8<p>9<p>10<p>11<p>12<p></p></div>"
);
IList<String> divText = doc.Select("div").EachText();
NUnit.Framework.Assert.AreEqual(2, divText.Count);
NUnit.Framework.Assert.AreEqual("1 2 3 4 5 6", divText[0]);
NUnit.Framework.Assert.AreEqual("7 8 9 10 11 12", divText[1]);
IList<String> pText = doc.Select("p").EachText();
Elements ps = doc.Select("p");
NUnit.Framework.Assert.AreEqual(13, ps.Count);
NUnit.Framework.Assert.AreEqual(12, pText.Count);
// not 13, as last doesn't have text
NUnit.Framework.Assert.AreEqual("1", pText[0]);
NUnit.Framework.Assert.AreEqual("2", pText[1]);
NUnit.Framework.Assert.AreEqual("5", pText[4]);
NUnit.Framework.Assert.AreEqual("7", pText[6]);
NUnit.Framework.Assert.AreEqual("12", pText[11]);
}
[NUnit.Framework.Test]
public virtual void EachAttr() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><a href='/foo'>1</a><a href='http://example.com/bar'>2</a><a href=''>3</a><a>4</a>"
, "http://example.com");
IList<String> hrefAttrs = doc.Select("a").EachAttr("href");
NUnit.Framework.Assert.AreEqual(3, hrefAttrs.Count);
NUnit.Framework.Assert.AreEqual("/foo", hrefAttrs[0]);
NUnit.Framework.Assert.AreEqual("http://example.com/bar", hrefAttrs[1]);
NUnit.Framework.Assert.AreEqual("", hrefAttrs[2]);
NUnit.Framework.Assert.AreEqual(4, doc.Select("a").Count);
IList<String> absAttrs = doc.Select("a").EachAttr("abs:href");
NUnit.Framework.Assert.AreEqual(3, absAttrs.Count);
NUnit.Framework.Assert.AreEqual(3, absAttrs.Count);
NUnit.Framework.Assert.AreEqual("http://example.com/foo", absAttrs[0]);
NUnit.Framework.Assert.AreEqual("http://example.com/bar", absAttrs[1]);
NUnit.Framework.Assert.AreEqual("http://example.com/", absAttrs[2]);
}
}
}

View File

@@ -0,0 +1,170 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using TSpdf.Commons.Utils;
using TSpdf.StyledXmlParser.Jsoup.Nodes;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Select {
[NUnit.Framework.Category("UnitTest")]
[NUnit.Framework.TestFixtureSource("LocalesTestFixtureData")]
public class MultiLocaleTest : ExtendedTSpdfTest {
private readonly CultureInfo defaultLocale = System.Threading.Thread.CurrentThread.CurrentUICulture;
public static ICollection<CultureInfo> Locales() {
return JavaUtil.ArraysAsList(System.Globalization.CultureInfo.InvariantCulture, new CultureInfo("tr", false
));
}
public static ICollection<NUnit.Framework.TestFixtureData> LocalesTestFixtureData() {
return Locales().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList();
}
[NUnit.Framework.TearDown]
public virtual void SetDefaultLocale() {
System.Threading.Thread.CurrentThread.CurrentUICulture = defaultLocale;
}
private CultureInfo locale;
public MultiLocaleTest(CultureInfo locale) {
this.locale = locale;
}
public MultiLocaleTest(CultureInfo[] array)
: this(array[0]) {
}
[NUnit.Framework.Test]
public virtual void TestByAttribute() {
System.Threading.Thread.CurrentThread.CurrentUICulture = locale;
String h = "<div Title=Foo /><div Title=Bar /><div Style=Qux /><div title=Balim /><div title=SLIM />" + "<div data-name='with spaces'/>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
Elements withTitle = doc.Select("[title]");
NUnit.Framework.Assert.AreEqual(4, withTitle.Count);
Elements foo = doc.Select("[TITLE=foo]");
NUnit.Framework.Assert.AreEqual(1, foo.Count);
Elements foo2 = doc.Select("[title=\"foo\"]");
NUnit.Framework.Assert.AreEqual(1, foo2.Count);
Elements foo3 = doc.Select("[title=\"Foo\"]");
NUnit.Framework.Assert.AreEqual(1, foo3.Count);
Elements dataName = doc.Select("[data-name=\"with spaces\"]");
NUnit.Framework.Assert.AreEqual(1, dataName.Count);
NUnit.Framework.Assert.AreEqual("with spaces", dataName.First().Attr("data-name"));
Elements not = doc.Select("div[title!=bar]");
NUnit.Framework.Assert.AreEqual(5, not.Count);
NUnit.Framework.Assert.AreEqual("Foo", not.First().Attr("title"));
Elements starts = doc.Select("[title^=ba]");
NUnit.Framework.Assert.AreEqual(2, starts.Count);
NUnit.Framework.Assert.AreEqual("Bar", starts.First().Attr("title"));
NUnit.Framework.Assert.AreEqual("Balim", starts.Last().Attr("title"));
Elements ends = doc.Select("[title$=im]");
NUnit.Framework.Assert.AreEqual(2, ends.Count);
NUnit.Framework.Assert.AreEqual("Balim", ends.First().Attr("title"));
NUnit.Framework.Assert.AreEqual("SLIM", ends.Last().Attr("title"));
Elements contains = doc.Select("[title*=i]");
NUnit.Framework.Assert.AreEqual(2, contains.Count);
NUnit.Framework.Assert.AreEqual("Balim", contains.First().Attr("title"));
NUnit.Framework.Assert.AreEqual("SLIM", contains.Last().Attr("title"));
}
[NUnit.Framework.Test]
public virtual void TestPseudoContains() {
System.Threading.Thread.CurrentThread.CurrentUICulture = locale;
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>The Rain.</p> <p class=light>The <i>RAIN</i>.</p> <p>Rain, the.</p></div>"
);
Elements ps1 = doc.Select("p:contains(Rain)");
NUnit.Framework.Assert.AreEqual(3, ps1.Count);
Elements ps2 = doc.Select("p:contains(the rain)");
NUnit.Framework.Assert.AreEqual(2, ps2.Count);
NUnit.Framework.Assert.AreEqual("The Rain.", ps2.First().Html());
NUnit.Framework.Assert.AreEqual("The <i>RAIN</i>.", ps2.Last().Html());
Elements ps3 = doc.Select("p:contains(the Rain):has(i)");
NUnit.Framework.Assert.AreEqual(1, ps3.Count);
NUnit.Framework.Assert.AreEqual("light", ps3.First().ClassName());
Elements ps4 = doc.Select(".light:contains(rain)");
NUnit.Framework.Assert.AreEqual(1, ps4.Count);
NUnit.Framework.Assert.AreEqual("light", ps3.First().ClassName());
Elements ps5 = doc.Select(":contains(rain)");
NUnit.Framework.Assert.AreEqual(8, ps5.Count);
// html, body, div,...
Elements ps6 = doc.Select(":contains(RAIN)");
NUnit.Framework.Assert.AreEqual(8, ps6.Count);
}
[NUnit.Framework.Test]
public virtual void ContainsOwn() {
System.Threading.Thread.CurrentThread.CurrentUICulture = locale;
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p id=1>Hello <b>there</b> igor</p>");
Elements ps = doc.Select("p:containsOwn(Hello IGOR)");
NUnit.Framework.Assert.AreEqual(1, ps.Count);
NUnit.Framework.Assert.AreEqual("1", ps.First().Id());
NUnit.Framework.Assert.AreEqual(0, doc.Select("p:containsOwn(there)").Count);
Document doc2 = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p>Hello <b>there</b> IGOR</p>");
NUnit.Framework.Assert.AreEqual(1, doc2.Select("p:containsOwn(igor)").Count);
}
[NUnit.Framework.Test]
public virtual void ContainsData() {
System.Threading.Thread.CurrentThread.CurrentUICulture = locale;
String html = "<p>function</p><script>FUNCTION</script><style>item</style><span><!-- comments --></span>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element body = doc.Body();
Elements dataEls1 = body.Select(":containsData(function)");
Elements dataEls2 = body.Select("script:containsData(function)");
Elements dataEls3 = body.Select("span:containsData(comments)");
Elements dataEls4 = body.Select(":containsData(o)");
Elements dataEls5 = body.Select("style:containsData(ITEM)");
NUnit.Framework.Assert.AreEqual(2, dataEls1.Count);
// body and script
NUnit.Framework.Assert.AreEqual(1, dataEls2.Count);
NUnit.Framework.Assert.AreEqual(dataEls1.Last(), dataEls2.First());
NUnit.Framework.Assert.AreEqual("<script>FUNCTION</script>", dataEls2.OuterHtml());
NUnit.Framework.Assert.AreEqual(1, dataEls3.Count);
NUnit.Framework.Assert.AreEqual("span", dataEls3.First().TagName());
NUnit.Framework.Assert.AreEqual(3, dataEls4.Count);
NUnit.Framework.Assert.AreEqual("body", dataEls4.First().TagName());
NUnit.Framework.Assert.AreEqual("script", dataEls4[1].TagName());
NUnit.Framework.Assert.AreEqual("span", dataEls4[2].TagName());
NUnit.Framework.Assert.AreEqual(1, dataEls5.Count);
}
[NUnit.Framework.Test]
public virtual void TestByAttributeStarting() {
System.Threading.Thread.CurrentThread.CurrentUICulture = locale;
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div id=1 ATTRIBUTE data-name=jsoup>Hello</div><p data-val=5 id=2>There</p><p id=3>No</p>"
);
Elements withData = doc.Select("[^data-]");
NUnit.Framework.Assert.AreEqual(2, withData.Count);
NUnit.Framework.Assert.AreEqual("1", withData.First().Id());
NUnit.Framework.Assert.AreEqual("2", withData.Last().Id());
withData = doc.Select("p[^data-]");
NUnit.Framework.Assert.AreEqual(1, withData.Count);
NUnit.Framework.Assert.AreEqual("2", withData.First().Id());
NUnit.Framework.Assert.AreEqual(1, doc.Select("[^attrib]").Count);
}
}
}

View File

@@ -0,0 +1,99 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Select {
/// <summary>Tests for the Selector Query Parser.</summary>
/// <author>Jonathan Hedley</author>
[NUnit.Framework.Category("UnitTest")]
public class QueryParserTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void TestOrGetsCorrectPrecedence() {
// tests that a selector "a b, c d, e f" evals to (a AND b) OR (c AND d) OR (e AND f)"
// top level or, three child ands
Evaluator eval = QueryParser.Parse("a b, c d, e f");
NUnit.Framework.Assert.IsTrue(eval is CombiningEvaluator.OR);
CombiningEvaluator.OR or = (CombiningEvaluator.OR)eval;
NUnit.Framework.Assert.AreEqual(3, or.evaluators.Count);
foreach (Evaluator innerEval in or.evaluators) {
NUnit.Framework.Assert.IsTrue(innerEval is CombiningEvaluator.And);
CombiningEvaluator.And and = (CombiningEvaluator.And)innerEval;
NUnit.Framework.Assert.AreEqual(2, and.evaluators.Count);
NUnit.Framework.Assert.IsTrue(and.evaluators[0] is StructuralEvaluator.Parent);
NUnit.Framework.Assert.IsTrue(and.evaluators[1] is Evaluator.Tag);
}
}
[NUnit.Framework.Test]
public virtual void TestParsesMultiCorrectly() {
String query = ".foo > ol, ol > li + li";
Evaluator eval = QueryParser.Parse(query);
NUnit.Framework.Assert.IsTrue(eval is CombiningEvaluator.OR);
CombiningEvaluator.OR or = (CombiningEvaluator.OR)eval;
NUnit.Framework.Assert.AreEqual(2, or.evaluators.Count);
CombiningEvaluator.And andLeft = (CombiningEvaluator.And)or.evaluators[0];
CombiningEvaluator.And andRight = (CombiningEvaluator.And)or.evaluators[1];
NUnit.Framework.Assert.AreEqual(".foo > ol", andLeft.ToString());
NUnit.Framework.Assert.AreEqual(2, andLeft.evaluators.Count);
NUnit.Framework.Assert.AreEqual("ol > li + li", andRight.ToString());
NUnit.Framework.Assert.AreEqual(2, andRight.evaluators.Count);
NUnit.Framework.Assert.AreEqual(query, eval.ToString());
}
[NUnit.Framework.Test]
public virtual void ExceptionOnUncloseAttribute() {
NUnit.Framework.Assert.Catch(typeof(Selector.SelectorParseException), () => QueryParser.Parse("section > a[href=\"]"
));
}
[NUnit.Framework.Test]
public virtual void TestParsesSingleQuoteInContains() {
NUnit.Framework.Assert.Catch(typeof(Selector.SelectorParseException), () => QueryParser.Parse("p:contains(One \" One)"
));
}
[NUnit.Framework.Test]
public virtual void ExceptOnEmptySelector() {
NUnit.Framework.Assert.Catch(typeof(Selector.SelectorParseException), () => QueryParser.Parse(""));
}
[NUnit.Framework.Test]
public virtual void ExceptOnNullSelector() {
NUnit.Framework.Assert.Catch(typeof(Selector.SelectorParseException), () => QueryParser.Parse(null));
}
[NUnit.Framework.Test]
public virtual void OkOnSpacesForeAndAft() {
Evaluator parse = QueryParser.Parse(" span div ");
NUnit.Framework.Assert.AreEqual("span div", parse.ToString());
}
[NUnit.Framework.Test]
public virtual void StructuralEvaluatorsToString() {
String q = "a:not(:has(span.foo)) b d > e + f ~ g";
Evaluator parse = QueryParser.Parse(q);
NUnit.Framework.Assert.AreEqual(q, parse.ToString());
}
}
}

View File

@@ -0,0 +1,901 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using TSpdf.StyledXmlParser.Jsoup.Nodes;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Select {
/// <summary>Tests that the selector selects correctly.</summary>
/// <author>Jonathan Hedley, jonathan@hedley.net</author>
[NUnit.Framework.Category("UnitTest")]
public class SelectorTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void TestByTag() {
// should be case insensitive
Elements els = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div id=1><div id=2><p>Hello</p></div></div><DIV id=3>"
).Select("DIV");
NUnit.Framework.Assert.AreEqual(3, els.Count);
NUnit.Framework.Assert.AreEqual("1", els[0].Id());
NUnit.Framework.Assert.AreEqual("2", els[1].Id());
NUnit.Framework.Assert.AreEqual("3", els[2].Id());
Elements none = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div id=1><div id=2><p>Hello</p></div></div><div id=3>"
).Select("span");
NUnit.Framework.Assert.AreEqual(0, none.Count);
}
[NUnit.Framework.Test]
public virtual void TestById() {
Elements els = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p id=foo>Hello</p><p id=foo>Foo two!</p></div>"
).Select("#foo");
NUnit.Framework.Assert.AreEqual(2, els.Count);
NUnit.Framework.Assert.AreEqual("Hello", els[0].Text());
NUnit.Framework.Assert.AreEqual("Foo two!", els[1].Text());
Elements none = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div id=1></div>").Select("#foo");
NUnit.Framework.Assert.AreEqual(0, none.Count);
}
[NUnit.Framework.Test]
public virtual void TestByClass() {
Elements els = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p id=0 class='ONE two'><p id=1 class='one'><p id=2 class='two'>"
).Select("P.One");
NUnit.Framework.Assert.AreEqual(2, els.Count);
NUnit.Framework.Assert.AreEqual("0", els[0].Id());
NUnit.Framework.Assert.AreEqual("1", els[1].Id());
Elements none = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div class='one'></div>").Select(".foo");
NUnit.Framework.Assert.AreEqual(0, none.Count);
Elements els2 = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div class='One-Two'></div>").Select(".one-two");
NUnit.Framework.Assert.AreEqual(1, els2.Count);
}
[NUnit.Framework.Test]
public virtual void TestByClassCaseInsensitive() {
String html = "<p Class=foo>One <p Class=Foo>Two <p class=FOO>Three <p class=farp>Four";
Elements elsFromClass = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html).Select("P.Foo");
Elements elsFromAttr = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html).Select("p[class=foo]");
NUnit.Framework.Assert.AreEqual(elsFromAttr.Count, elsFromClass.Count);
NUnit.Framework.Assert.AreEqual(3, elsFromClass.Count);
NUnit.Framework.Assert.AreEqual("Two", elsFromClass[1].Text());
}
[NUnit.Framework.Test]
public virtual void TestNamespacedTag() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><abc:def id=1>Hello</abc:def></div> <abc:def class=bold id=2>There</abc:def>"
);
Elements byTag = doc.Select("abc|def");
NUnit.Framework.Assert.AreEqual(2, byTag.Count);
NUnit.Framework.Assert.AreEqual("1", byTag.First().Id());
NUnit.Framework.Assert.AreEqual("2", byTag.Last().Id());
Elements byAttr = doc.Select(".bold");
NUnit.Framework.Assert.AreEqual(1, byAttr.Count);
NUnit.Framework.Assert.AreEqual("2", byAttr.Last().Id());
Elements byTagAttr = doc.Select("abc|def.bold");
NUnit.Framework.Assert.AreEqual(1, byTagAttr.Count);
NUnit.Framework.Assert.AreEqual("2", byTagAttr.Last().Id());
Elements byContains = doc.Select("abc|def:contains(e)");
NUnit.Framework.Assert.AreEqual(2, byContains.Count);
NUnit.Framework.Assert.AreEqual("1", byContains.First().Id());
NUnit.Framework.Assert.AreEqual("2", byContains.Last().Id());
}
[NUnit.Framework.Test]
public virtual void TestWildcardNamespacedTag() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><abc:def id=1>Hello</abc:def></div> <abc:def class=bold id=2>There</abc:def>"
);
Elements byTag = doc.Select("*|def");
NUnit.Framework.Assert.AreEqual(2, byTag.Count);
NUnit.Framework.Assert.AreEqual("1", byTag.First().Id());
NUnit.Framework.Assert.AreEqual("2", byTag.Last().Id());
Elements byAttr = doc.Select(".bold");
NUnit.Framework.Assert.AreEqual(1, byAttr.Count);
NUnit.Framework.Assert.AreEqual("2", byAttr.Last().Id());
Elements byTagAttr = doc.Select("*|def.bold");
NUnit.Framework.Assert.AreEqual(1, byTagAttr.Count);
NUnit.Framework.Assert.AreEqual("2", byTagAttr.Last().Id());
Elements byContains = doc.Select("*|def:contains(e)");
NUnit.Framework.Assert.AreEqual(2, byContains.Count);
NUnit.Framework.Assert.AreEqual("1", byContains.First().Id());
NUnit.Framework.Assert.AreEqual("2", byContains.Last().Id());
}
[NUnit.Framework.Test]
public virtual void TestWildcardNamespacedXmlTag() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><Abc:Def id=1>Hello</Abc:Def></div> <Abc:Def class=bold id=2>There</abc:def>"
, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser.XmlParser());
Elements byTag = doc.Select("*|Def");
NUnit.Framework.Assert.AreEqual(2, byTag.Count);
NUnit.Framework.Assert.AreEqual("1", byTag.First().Id());
NUnit.Framework.Assert.AreEqual("2", byTag.Last().Id());
Elements byAttr = doc.Select(".bold");
NUnit.Framework.Assert.AreEqual(1, byAttr.Count);
NUnit.Framework.Assert.AreEqual("2", byAttr.Last().Id());
Elements byTagAttr = doc.Select("*|Def.bold");
NUnit.Framework.Assert.AreEqual(1, byTagAttr.Count);
NUnit.Framework.Assert.AreEqual("2", byTagAttr.Last().Id());
Elements byContains = doc.Select("*|Def:contains(e)");
NUnit.Framework.Assert.AreEqual(2, byContains.Count);
NUnit.Framework.Assert.AreEqual("1", byContains.First().Id());
NUnit.Framework.Assert.AreEqual("2", byContains.Last().Id());
}
[NUnit.Framework.Test]
public virtual void TestWildCardNamespacedCaseVariations() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<One:Two>One</One:Two><three:four>Two</three:four>"
, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser.XmlParser());
Elements els1 = doc.Select("One|Two");
Elements els2 = doc.Select("one|two");
Elements els3 = doc.Select("Three|Four");
Elements els4 = doc.Select("three|Four");
NUnit.Framework.Assert.AreEqual(els1, els2);
NUnit.Framework.Assert.AreEqual(els3, els4);
NUnit.Framework.Assert.AreEqual("One", els1.Text());
NUnit.Framework.Assert.AreEqual(1, els1.Count);
NUnit.Framework.Assert.AreEqual("Two", els3.Text());
NUnit.Framework.Assert.AreEqual(1, els2.Count);
}
[NUnit.Framework.Test]
public virtual void TestByAttributeRegex() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p><img src=foo.png id=1><img src=bar.jpg id=2><img src=qux.JPEG id=3><img src=old.gif><img></p>"
);
Elements imgs = doc.Select("img[src~=(?i)\\.(png|jpe?g)]");
NUnit.Framework.Assert.AreEqual(3, imgs.Count);
NUnit.Framework.Assert.AreEqual("1", imgs[0].Id());
NUnit.Framework.Assert.AreEqual("2", imgs[1].Id());
NUnit.Framework.Assert.AreEqual("3", imgs[2].Id());
}
[NUnit.Framework.Test]
public virtual void TestByAttributeRegexCharacterClass() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p><img src=foo.png id=1><img src=bar.jpg id=2><img src=qux.JPEG id=3><img src=old.gif id=4></p>"
);
Elements imgs = doc.Select("img[src~=[o]]");
NUnit.Framework.Assert.AreEqual(2, imgs.Count);
NUnit.Framework.Assert.AreEqual("1", imgs[0].Id());
NUnit.Framework.Assert.AreEqual("4", imgs[1].Id());
}
[NUnit.Framework.Test]
public virtual void TestByAttributeRegexCombined() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><table class=x><td>Hello</td></table></div>");
Elements els = doc.Select("div table[class~=x|y]");
NUnit.Framework.Assert.AreEqual(1, els.Count);
NUnit.Framework.Assert.AreEqual("Hello", els.Text());
}
[NUnit.Framework.Test]
public virtual void TestCombinedWithContains() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p id=1>One</p><p>Two +</p><p>Three +</p>");
Elements els = doc.Select("p#1 + :contains(+)");
NUnit.Framework.Assert.AreEqual(1, els.Count);
NUnit.Framework.Assert.AreEqual("Two +", els.Text());
NUnit.Framework.Assert.AreEqual("p", els.First().TagName());
}
[NUnit.Framework.Test]
public virtual void TestAllElements() {
String h = "<div><p>Hello</p><p><b>there</b></p></div>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
Elements allDoc = doc.Select("*");
Elements allUnderDiv = doc.Select("div *");
NUnit.Framework.Assert.AreEqual(8, allDoc.Count);
NUnit.Framework.Assert.AreEqual(3, allUnderDiv.Count);
NUnit.Framework.Assert.AreEqual("p", allUnderDiv.First().TagName());
}
[NUnit.Framework.Test]
public virtual void TestAllWithClass() {
String h = "<p class=first>One<p class=first>Two<p>Three";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
Elements ps = doc.Select("*.first");
NUnit.Framework.Assert.AreEqual(2, ps.Count);
}
[NUnit.Framework.Test]
public virtual void TestGroupOr() {
String h = "<div title=foo /><div title=bar /><div /><p></p><img /><span title=qux>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
Elements els = doc.Select("p,div,[title]");
NUnit.Framework.Assert.AreEqual(5, els.Count);
NUnit.Framework.Assert.AreEqual("div", els[0].TagName());
NUnit.Framework.Assert.AreEqual("foo", els[0].Attr("title"));
NUnit.Framework.Assert.AreEqual("div", els[1].TagName());
NUnit.Framework.Assert.AreEqual("bar", els[1].Attr("title"));
NUnit.Framework.Assert.AreEqual("div", els[2].TagName());
NUnit.Framework.Assert.AreEqual(0, els[2].Attr("title").Length);
// missing attributes come back as empty string
NUnit.Framework.Assert.IsFalse(els[2].HasAttr("title"));
NUnit.Framework.Assert.AreEqual("p", els[3].TagName());
NUnit.Framework.Assert.AreEqual("span", els[4].TagName());
}
[NUnit.Framework.Test]
public virtual void TestGroupOrAttribute() {
String h = "<div id=1 /><div id=2 /><div title=foo /><div title=bar />";
Elements els = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h).Select("[id],[title=foo]");
NUnit.Framework.Assert.AreEqual(3, els.Count);
NUnit.Framework.Assert.AreEqual("1", els[0].Id());
NUnit.Framework.Assert.AreEqual("2", els[1].Id());
NUnit.Framework.Assert.AreEqual("foo", els[2].Attr("title"));
}
[NUnit.Framework.Test]
public virtual void Descendant() {
String h = "<div class=head><p class=first>Hello</p><p>There</p></div><p>None</p>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element root = doc.GetElementsByClass("HEAD").First();
Elements els = root.Select(".head p");
NUnit.Framework.Assert.AreEqual(2, els.Count);
NUnit.Framework.Assert.AreEqual("Hello", els[0].Text());
NUnit.Framework.Assert.AreEqual("There", els[1].Text());
Elements p = root.Select("p.first");
NUnit.Framework.Assert.AreEqual(1, p.Count);
NUnit.Framework.Assert.AreEqual("Hello", p[0].Text());
Elements empty = root.Select("p .first");
// self, not descend, should not match
NUnit.Framework.Assert.AreEqual(0, empty.Count);
Elements aboveRoot = root.Select("body div.head");
NUnit.Framework.Assert.AreEqual(0, aboveRoot.Count);
}
[NUnit.Framework.Test]
public virtual void And() {
String h = "<div id=1 class='foo bar' title=bar name=qux><p class=foo title=bar>Hello</p></div";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
Elements div = doc.Select("div.foo");
NUnit.Framework.Assert.AreEqual(1, div.Count);
NUnit.Framework.Assert.AreEqual("div", div.First().TagName());
Elements p = doc.Select("div .foo");
// space indicates like "div *.foo"
NUnit.Framework.Assert.AreEqual(1, p.Count);
NUnit.Framework.Assert.AreEqual("p", p.First().TagName());
Elements div2 = doc.Select("div#1.foo.bar[title=bar][name=qux]");
// very specific!
NUnit.Framework.Assert.AreEqual(1, div2.Count);
NUnit.Framework.Assert.AreEqual("div", div2.First().TagName());
Elements p2 = doc.Select("div *.foo");
// space indicates like "div *.foo"
NUnit.Framework.Assert.AreEqual(1, p2.Count);
NUnit.Framework.Assert.AreEqual("p", p2.First().TagName());
}
[NUnit.Framework.Test]
public virtual void DeeperDescendant() {
String h = "<div class=head><p><span class=first>Hello</div><div class=head><p class=first><span>Another</span><p>Again</div>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element root = doc.GetElementsByClass("head").First();
Elements els = root.Select("div p .first");
NUnit.Framework.Assert.AreEqual(1, els.Count);
NUnit.Framework.Assert.AreEqual("Hello", els.First().Text());
NUnit.Framework.Assert.AreEqual("span", els.First().TagName());
Elements aboveRoot = root.Select("body p .first");
NUnit.Framework.Assert.AreEqual(0, aboveRoot.Count);
}
[NUnit.Framework.Test]
public virtual void ParentChildElement() {
String h = "<div id=1><div id=2><div id = 3></div></div></div><div id=4></div>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
Elements divs = doc.Select("div > div");
NUnit.Framework.Assert.AreEqual(2, divs.Count);
NUnit.Framework.Assert.AreEqual("2", divs[0].Id());
// 2 is child of 1
NUnit.Framework.Assert.AreEqual("3", divs[1].Id());
// 3 is child of 2
Elements div2 = doc.Select("div#1 > div");
NUnit.Framework.Assert.AreEqual(1, div2.Count);
NUnit.Framework.Assert.AreEqual("2", div2[0].Id());
}
[NUnit.Framework.Test]
public virtual void ParentWithClassChild() {
String h = "<h1 class=foo><a href=1 /></h1><h1 class=foo><a href=2 class=bar /></h1><h1><a href=3 /></h1>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
Elements allAs = doc.Select("h1 > a");
NUnit.Framework.Assert.AreEqual(3, allAs.Count);
NUnit.Framework.Assert.AreEqual("a", allAs.First().TagName());
Elements fooAs = doc.Select("h1.foo > a");
NUnit.Framework.Assert.AreEqual(2, fooAs.Count);
NUnit.Framework.Assert.AreEqual("a", fooAs.First().TagName());
Elements barAs = doc.Select("h1.foo > a.bar");
NUnit.Framework.Assert.AreEqual(1, barAs.Count);
}
[NUnit.Framework.Test]
public virtual void ParentChildStar() {
String h = "<div id=1><p>Hello<p><b>there</b></p></div><div id=2><span>Hi</span></div>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
Elements divChilds = doc.Select("div > *");
NUnit.Framework.Assert.AreEqual(3, divChilds.Count);
NUnit.Framework.Assert.AreEqual("p", divChilds[0].TagName());
NUnit.Framework.Assert.AreEqual("p", divChilds[1].TagName());
NUnit.Framework.Assert.AreEqual("span", divChilds[2].TagName());
}
[NUnit.Framework.Test]
public virtual void MultiChildDescent() {
String h = "<div id=foo><h1 class=bar><a href=http://example.com/>One</a></h1></div>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
Elements els = doc.Select("div#foo > h1.bar > a[href*=example]");
NUnit.Framework.Assert.AreEqual(1, els.Count);
NUnit.Framework.Assert.AreEqual("a", els.First().TagName());
}
[NUnit.Framework.Test]
public virtual void CaseInsensitive() {
String h = "<dIv tItle=bAr><div>";
// mixed case so a simple toLowerCase() on value doesn't catch
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
NUnit.Framework.Assert.AreEqual(2, doc.Select("DiV").Count);
NUnit.Framework.Assert.AreEqual(1, doc.Select("DiV[TiTLE]").Count);
NUnit.Framework.Assert.AreEqual(1, doc.Select("DiV[TiTLE=BAR]").Count);
NUnit.Framework.Assert.AreEqual(0, doc.Select("DiV[TiTLE=BARBARELLA]").Count);
}
[NUnit.Framework.Test]
public virtual void AdjacentSiblings() {
String h = "<ol><li>One<li>Two<li>Three</ol>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
Elements sibs = doc.Select("li + li");
NUnit.Framework.Assert.AreEqual(2, sibs.Count);
NUnit.Framework.Assert.AreEqual("Two", sibs[0].Text());
NUnit.Framework.Assert.AreEqual("Three", sibs[1].Text());
}
[NUnit.Framework.Test]
public virtual void AdjacentSiblingsWithId() {
String h = "<ol><li id=1>One<li id=2>Two<li id=3>Three</ol>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
Elements sibs = doc.Select("li#1 + li#2");
NUnit.Framework.Assert.AreEqual(1, sibs.Count);
NUnit.Framework.Assert.AreEqual("Two", sibs[0].Text());
}
[NUnit.Framework.Test]
public virtual void NotAdjacent() {
String h = "<ol><li id=1>One<li id=2>Two<li id=3>Three</ol>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
Elements sibs = doc.Select("li#1 + li#3");
NUnit.Framework.Assert.AreEqual(0, sibs.Count);
}
[NUnit.Framework.Test]
public virtual void MixCombinator() {
String h = "<div class=foo><ol><li>One<li>Two<li>Three</ol></div>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
Elements sibs = doc.Select("body > div.foo li + li");
NUnit.Framework.Assert.AreEqual(2, sibs.Count);
NUnit.Framework.Assert.AreEqual("Two", sibs[0].Text());
NUnit.Framework.Assert.AreEqual("Three", sibs[1].Text());
}
[NUnit.Framework.Test]
public virtual void MixCombinatorGroup() {
String h = "<div class=foo><ol><li>One<li>Two<li>Three</ol></div>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
Elements els = doc.Select(".foo > ol, ol > li + li");
NUnit.Framework.Assert.AreEqual(3, els.Count);
NUnit.Framework.Assert.AreEqual("ol", els[0].TagName());
NUnit.Framework.Assert.AreEqual("Two", els[1].Text());
NUnit.Framework.Assert.AreEqual("Three", els[2].Text());
}
[NUnit.Framework.Test]
public virtual void GeneralSiblings() {
String h = "<ol><li id=1>One<li id=2>Two<li id=3>Three</ol>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
Elements els = doc.Select("#1 ~ #3");
NUnit.Framework.Assert.AreEqual(1, els.Count);
NUnit.Framework.Assert.AreEqual("Three", els.First().Text());
}
// for http://github.com/jhy/jsoup/issues#issue/10
[NUnit.Framework.Test]
public virtual void TestCharactersInIdAndClass() {
// using CSS spec for identifiers (id and class): a-z0-9, -, _. NOT . (which is OK in html spec, but not css)
String h = "<div><p id='a1-foo_bar'>One</p><p class='b2-qux_bif'>Two</p></div>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el1 = doc.GetElementById("a1-foo_bar");
NUnit.Framework.Assert.AreEqual("One", el1.Text());
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el2 = doc.GetElementsByClass("b2-qux_bif").First();
NUnit.Framework.Assert.AreEqual("Two", el2.Text());
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el3 = doc.Select("#a1-foo_bar").First();
NUnit.Framework.Assert.AreEqual("One", el3.Text());
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el4 = doc.Select(".b2-qux_bif").First();
NUnit.Framework.Assert.AreEqual("Two", el4.Text());
}
// for http://github.com/jhy/jsoup/issues#issue/13
[NUnit.Framework.Test]
public virtual void TestSupportsLeadingCombinator() {
String h = "<div><p><span>One</span><span>Two</span></p></div>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element p = doc.Select("div > p").First();
Elements spans = p.Select("> span");
NUnit.Framework.Assert.AreEqual(2, spans.Count);
NUnit.Framework.Assert.AreEqual("One", spans.First().Text());
// make sure doesn't get nested
h = "<div id=1><div id=2><div id=3></div></div></div>";
doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(h);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element div = doc.Select("div").Select(" > div").First();
NUnit.Framework.Assert.AreEqual("2", div.Id());
}
[NUnit.Framework.Test]
public virtual void TestPseudoLessThan() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>One</p><p>Two</p><p>Three</>p></div><div><p>Four</p>"
);
Elements ps = doc.Select("div p:lt(2)");
NUnit.Framework.Assert.AreEqual(3, ps.Count);
NUnit.Framework.Assert.AreEqual("One", ps[0].Text());
NUnit.Framework.Assert.AreEqual("Two", ps[1].Text());
NUnit.Framework.Assert.AreEqual("Four", ps[2].Text());
}
[NUnit.Framework.Test]
public virtual void TestPseudoGreaterThan() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>One</p><p>Two</p><p>Three</p></div><div><p>Four</p>"
);
Elements ps = doc.Select("div p:gt(0)");
NUnit.Framework.Assert.AreEqual(2, ps.Count);
NUnit.Framework.Assert.AreEqual("Two", ps[0].Text());
NUnit.Framework.Assert.AreEqual("Three", ps[1].Text());
}
[NUnit.Framework.Test]
public virtual void TestPseudoEquals() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>One</p><p>Two</p><p>Three</>p></div><div><p>Four</p>"
);
Elements ps = doc.Select("div p:eq(0)");
NUnit.Framework.Assert.AreEqual(2, ps.Count);
NUnit.Framework.Assert.AreEqual("One", ps[0].Text());
NUnit.Framework.Assert.AreEqual("Four", ps[1].Text());
Elements ps2 = doc.Select("div:eq(0) p:eq(0)");
NUnit.Framework.Assert.AreEqual(1, ps2.Count);
NUnit.Framework.Assert.AreEqual("One", ps2[0].Text());
NUnit.Framework.Assert.AreEqual("p", ps2[0].TagName());
}
[NUnit.Framework.Test]
public virtual void TestPseudoBetween() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>One</p><p>Two</p><p>Three</>p></div><div><p>Four</p>"
);
Elements ps = doc.Select("div p:gt(0):lt(2)");
NUnit.Framework.Assert.AreEqual(1, ps.Count);
NUnit.Framework.Assert.AreEqual("Two", ps[0].Text());
}
[NUnit.Framework.Test]
public virtual void TestPseudoCombined() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div class='foo'><p>One</p><p>Two</p></div><div><p>Three</p><p>Four</p></div>"
);
Elements ps = doc.Select("div.foo p:gt(0)");
NUnit.Framework.Assert.AreEqual(1, ps.Count);
NUnit.Framework.Assert.AreEqual("Two", ps[0].Text());
}
[NUnit.Framework.Test]
public virtual void TestPseudoHas() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div id=0><p><span>Hello</span></p></div> <div id=1><span class=foo>There</span></div> <div id=2><p>Not</p></div>"
);
Elements divs1 = doc.Select("div:has(span)");
NUnit.Framework.Assert.AreEqual(2, divs1.Count);
NUnit.Framework.Assert.AreEqual("0", divs1[0].Id());
NUnit.Framework.Assert.AreEqual("1", divs1[1].Id());
Elements divs2 = doc.Select("div:has([class])");
NUnit.Framework.Assert.AreEqual(1, divs2.Count);
NUnit.Framework.Assert.AreEqual("1", divs2[0].Id());
Elements divs3 = doc.Select("div:has(span, p)");
NUnit.Framework.Assert.AreEqual(3, divs3.Count);
NUnit.Framework.Assert.AreEqual("0", divs3[0].Id());
NUnit.Framework.Assert.AreEqual("1", divs3[1].Id());
NUnit.Framework.Assert.AreEqual("2", divs3[2].Id());
Elements els1 = doc.Body().Select(":has(p)");
NUnit.Framework.Assert.AreEqual(3, els1.Count);
// body, div, dib
NUnit.Framework.Assert.AreEqual("body", els1.First().TagName());
NUnit.Framework.Assert.AreEqual("0", els1[1].Id());
NUnit.Framework.Assert.AreEqual("2", els1[2].Id());
Elements els2 = doc.Body().Select(":has(> span)");
NUnit.Framework.Assert.AreEqual(2, els2.Count);
// p, div
NUnit.Framework.Assert.AreEqual("p", els2.First().TagName());
NUnit.Framework.Assert.AreEqual("1", els2[1].Id());
}
[NUnit.Framework.Test]
public virtual void TestNestedHas() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p><span>One</span></p></div> <div><p>Two</p></div>"
);
Elements divs = doc.Select("div:has(p:has(span))");
NUnit.Framework.Assert.AreEqual(1, divs.Count);
NUnit.Framework.Assert.AreEqual("One", divs.First().Text());
// test matches in has
divs = doc.Select("div:has(p:matches((?i)two))");
NUnit.Framework.Assert.AreEqual(1, divs.Count);
NUnit.Framework.Assert.AreEqual("div", divs.First().TagName());
NUnit.Framework.Assert.AreEqual("Two", divs.First().Text());
// test contains in has
divs = doc.Select("div:has(p:contains(two))");
NUnit.Framework.Assert.AreEqual(1, divs.Count);
NUnit.Framework.Assert.AreEqual("div", divs.First().TagName());
NUnit.Framework.Assert.AreEqual("Two", divs.First().Text());
}
[NUnit.Framework.Test]
public virtual void TestPsuedoContainsWithParentheses() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p id=1>This (is good)</p><p id=2>This is bad)</p>"
);
Elements ps1 = doc.Select("p:contains(this (is good))");
NUnit.Framework.Assert.AreEqual(1, ps1.Count);
NUnit.Framework.Assert.AreEqual("1", ps1.First().Id());
Elements ps2 = doc.Select("p:contains(this is bad\\))");
NUnit.Framework.Assert.AreEqual(1, ps2.Count);
NUnit.Framework.Assert.AreEqual("2", ps2.First().Id());
}
[NUnit.Framework.Test]
public virtual void TestMatches() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p id=1>The <i>Rain</i></p> <p id=2>There are 99 bottles.</p> <p id=3>Harder (this)</p> <p id=4>Rain</p>"
);
Elements p1 = doc.Select("p:matches(The rain)");
// no match, case sensitive
NUnit.Framework.Assert.AreEqual(0, p1.Count);
Elements p2 = doc.Select("p:matches((?i)the rain)");
// case insense. should include root, html, body
NUnit.Framework.Assert.AreEqual(1, p2.Count);
NUnit.Framework.Assert.AreEqual("1", p2.First().Id());
Elements p4 = doc.Select("p:matches((?i)^rain$)");
// bounding
NUnit.Framework.Assert.AreEqual(1, p4.Count);
NUnit.Framework.Assert.AreEqual("4", p4.First().Id());
Elements p5 = doc.Select("p:matches(\\d+)");
NUnit.Framework.Assert.AreEqual(1, p5.Count);
NUnit.Framework.Assert.AreEqual("2", p5.First().Id());
Elements p6 = doc.Select("p:matches(\\w+\\s+\\(\\w+\\))");
// test bracket matching
NUnit.Framework.Assert.AreEqual(1, p6.Count);
NUnit.Framework.Assert.AreEqual("3", p6.First().Id());
Elements p7 = doc.Select("p:matches((?i)the):has(i)");
// multi
NUnit.Framework.Assert.AreEqual(1, p7.Count);
NUnit.Framework.Assert.AreEqual("1", p7.First().Id());
}
[NUnit.Framework.Test]
public virtual void MatchesOwn() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p id=1>Hello <b>there</b> now</p>");
Elements p1 = doc.Select("p:matchesOwn((?i)hello now)");
NUnit.Framework.Assert.AreEqual(1, p1.Count);
NUnit.Framework.Assert.AreEqual("1", p1.First().Id());
NUnit.Framework.Assert.AreEqual(0, doc.Select("p:matchesOwn(there)").Count);
}
[NUnit.Framework.Test]
public virtual void TestRelaxedTags() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<abc_def id=1>Hello</abc_def> <abc-def id=2>There</abc-def>"
);
Elements el1 = doc.Select("abc_def");
NUnit.Framework.Assert.AreEqual(1, el1.Count);
NUnit.Framework.Assert.AreEqual("1", el1.First().Id());
Elements el2 = doc.Select("abc-def");
NUnit.Framework.Assert.AreEqual(1, el2.Count);
NUnit.Framework.Assert.AreEqual("2", el2.First().Id());
}
[NUnit.Framework.Test]
public virtual void NotParas() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p id=1>One</p> <p>Two</p> <p><span>Three</span></p>"
);
Elements el1 = doc.Select("p:not([id=1])");
NUnit.Framework.Assert.AreEqual(2, el1.Count);
NUnit.Framework.Assert.AreEqual("Two", el1.First().Text());
NUnit.Framework.Assert.AreEqual("Three", el1.Last().Text());
Elements el2 = doc.Select("p:not(:has(span))");
NUnit.Framework.Assert.AreEqual(2, el2.Count);
NUnit.Framework.Assert.AreEqual("One", el2.First().Text());
NUnit.Framework.Assert.AreEqual("Two", el2.Last().Text());
}
[NUnit.Framework.Test]
public virtual void NotAll() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p>Two</p> <p><span>Three</span></p>");
Elements el1 = doc.Body().Select(":not(p)");
// should just be the span
NUnit.Framework.Assert.AreEqual(2, el1.Count);
NUnit.Framework.Assert.AreEqual("body", el1.First().TagName());
NUnit.Framework.Assert.AreEqual("span", el1.Last().TagName());
}
[NUnit.Framework.Test]
public virtual void NotClass() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div class=left>One</div><div class=right id=1><p>Two</p></div>"
);
Elements el1 = doc.Select("div:not(.left)");
NUnit.Framework.Assert.AreEqual(1, el1.Count);
NUnit.Framework.Assert.AreEqual("1", el1.First().Id());
}
[NUnit.Framework.Test]
public virtual void HandlesCommasInSelector() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p name='1,2'>One</p><div>Two</div><ol><li>123</li><li>Text</li></ol>"
);
Elements ps = doc.Select("[name=1,2]");
NUnit.Framework.Assert.AreEqual(1, ps.Count);
Elements containers = doc.Select("div, li:matches([0-9,]+)");
NUnit.Framework.Assert.AreEqual(2, containers.Count);
NUnit.Framework.Assert.AreEqual("div", containers[0].TagName());
NUnit.Framework.Assert.AreEqual("li", containers[1].TagName());
NUnit.Framework.Assert.AreEqual("123", containers[1].Text());
}
[NUnit.Framework.Test]
public virtual void SelectSupplementaryCharacter() {
String s = new String(TSpdf.IO.Util.TextUtil.ToChars(135361));
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div k" + s + "='" + s + "'>^" + s + "$/div>");
NUnit.Framework.Assert.AreEqual("div", doc.Select("div[k" + s + "]").First().TagName());
NUnit.Framework.Assert.AreEqual("div", doc.Select("div:containsOwn(" + s + ")").First().TagName());
}
[NUnit.Framework.Test]
public virtual void SelectClassWithSpace() {
String html = "<div class=\"value\">class without space</div>\n" + "<div class=\"value \">class with space</div>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
Elements found = doc.Select("div[class=value ]");
NUnit.Framework.Assert.AreEqual(2, found.Count);
NUnit.Framework.Assert.AreEqual("class without space", found[0].Text());
NUnit.Framework.Assert.AreEqual("class with space", found[1].Text());
found = doc.Select("div[class=\"value \"]");
NUnit.Framework.Assert.AreEqual(2, found.Count);
NUnit.Framework.Assert.AreEqual("class without space", found[0].Text());
NUnit.Framework.Assert.AreEqual("class with space", found[1].Text());
found = doc.Select("div[class=\"value\\ \"]");
NUnit.Framework.Assert.AreEqual(0, found.Count);
}
[NUnit.Framework.Test]
public virtual void SelectSameElements() {
String html = "<div>one</div><div>one</div>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
Elements els = doc.Select("div");
NUnit.Framework.Assert.AreEqual(2, els.Count);
Elements subSelect = els.Select(":contains(one)");
NUnit.Framework.Assert.AreEqual(2, subSelect.Count);
}
[NUnit.Framework.Test]
public virtual void AttributeWithBrackets() {
String html = "<div data='End]'>One</div> <div data='[Another)]]'>Two</div>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
NUnit.Framework.Assert.AreEqual("One", doc.Select("div[data='End]']").First().Text());
NUnit.Framework.Assert.AreEqual("Two", doc.Select("div[data='[Another)]]']").First().Text());
NUnit.Framework.Assert.AreEqual("One", doc.Select("div[data=\"End]\"]").First().Text());
NUnit.Framework.Assert.AreEqual("Two", doc.Select("div[data=\"[Another)]]\"]").First().Text());
}
[NUnit.Framework.Test]
public virtual void ContainsWithQuote() {
String html = "<p>One'One</p><p>One'Two</p>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
Elements els = doc.Select("p:contains(One\\'One)");
NUnit.Framework.Assert.AreEqual(1, els.Count);
NUnit.Framework.Assert.AreEqual("One'One", els.Text());
}
[NUnit.Framework.Test]
public virtual void SelectFirst() {
String html = "<p>One<p>Two<p>Three";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
NUnit.Framework.Assert.AreEqual("One", doc.SelectFirst("p").Text());
}
[NUnit.Framework.Test]
public virtual void SelectFirstWithAnd() {
String html = "<p>One<p class=foo>Two<p>Three";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
NUnit.Framework.Assert.AreEqual("Two", doc.SelectFirst("p.foo").Text());
}
[NUnit.Framework.Test]
public virtual void SelectFirstWithOr() {
String html = "<p>One<p>Two<p>Three<div>Four";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
NUnit.Framework.Assert.AreEqual("One", doc.SelectFirst("p, div").Text());
}
[NUnit.Framework.Test]
public virtual void MatchText() {
String html = "<p>One<br>Two</p>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
String origHtml = doc.Html();
Elements one = doc.Select("p:matchText:first-child");
NUnit.Framework.Assert.AreEqual("One", one.First().Text());
Elements two = doc.Select("p:matchText:last-child");
NUnit.Framework.Assert.AreEqual("Two", two.First().Text());
NUnit.Framework.Assert.AreEqual(origHtml, doc.Html());
NUnit.Framework.Assert.AreEqual("Two", doc.Select("p:matchText + br + *").Text());
}
[NUnit.Framework.Test]
public virtual void NthLastChildWithNoParent() {
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element("p").Text("Orphan"
);
Elements els = el.Select("p:nth-last-child(1)");
NUnit.Framework.Assert.AreEqual(0, els.Count);
}
[NUnit.Framework.Test]
public virtual void SplitOnBr() {
String html = "<div><p>One<br>Two<br>Three</p></div>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
Elements els = doc.Select("p:matchText");
NUnit.Framework.Assert.AreEqual(3, els.Count);
NUnit.Framework.Assert.AreEqual("One", els[0].Text());
NUnit.Framework.Assert.AreEqual("Two", els[1].Text());
NUnit.Framework.Assert.AreEqual("Three", els[2].ToString());
}
[NUnit.Framework.Test]
public virtual void MatchTextAttributes() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p class=one>One<br>Two<p class=two>Three<br>Four"
);
Elements els = doc.Select("p.two:matchText:last-child");
NUnit.Framework.Assert.AreEqual(1, els.Count);
NUnit.Framework.Assert.AreEqual("Four", els.Text());
}
[NUnit.Framework.Test]
public virtual void FindBetweenSpan() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p><span>One</span> Two <span>Three</span>");
Elements els = doc.Select("span ~ p:matchText");
// the Two becomes its own p, sibling of the span
NUnit.Framework.Assert.AreEqual(1, els.Count);
NUnit.Framework.Assert.AreEqual("Two", els.Text());
}
[NUnit.Framework.Test]
public virtual void StartsWithBeginsWithSpace() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<small><a href=\" mailto:abc@def.net\">(abc@def.net)</a></small>"
);
Elements els = doc.Select("a[href^=' mailto']");
NUnit.Framework.Assert.AreEqual(1, els.Count);
}
[NUnit.Framework.Test]
public virtual void EndsWithEndsWithSpaces() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<small><a href=\" mailto:abc@def.net \">(abc@def.net)</a></small>"
);
Elements els = doc.Select("a[href$='.net ']");
NUnit.Framework.Assert.AreEqual(1, els.Count);
}
// https://github.com/jhy/jsoup/issues/1257
private readonly String mixedCase = "<html xmlns:n=\"urn:ns\"><n:mixedCase>text</n:mixedCase></html>";
private readonly String lowercase = "<html xmlns:n=\"urn:ns\"><n:lowercase>text</n:lowercase></html>";
[NUnit.Framework.Test]
public virtual void Html_mixed_case_simple_name() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(mixedCase, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.HtmlParser());
NUnit.Framework.Assert.AreEqual(0, doc.Select("mixedCase").Count);
}
[NUnit.Framework.Test]
public virtual void Html_mixed_case_wildcard_name() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(mixedCase, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.HtmlParser());
NUnit.Framework.Assert.AreEqual(1, doc.Select("*|mixedCase").Count);
}
[NUnit.Framework.Test]
public virtual void Html_lowercase_simple_name() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(lowercase, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.HtmlParser());
NUnit.Framework.Assert.AreEqual(0, doc.Select("lowercase").Count);
}
[NUnit.Framework.Test]
public virtual void Html_lowercase_wildcard_name() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(lowercase, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.HtmlParser());
NUnit.Framework.Assert.AreEqual(1, doc.Select("*|lowercase").Count);
}
[NUnit.Framework.Test]
public virtual void Xml_mixed_case_simple_name() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(mixedCase, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.XmlParser());
NUnit.Framework.Assert.AreEqual(0, doc.Select("mixedCase").Count);
}
[NUnit.Framework.Test]
public virtual void Xml_mixed_case_wildcard_name() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(mixedCase, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.XmlParser());
NUnit.Framework.Assert.AreEqual(1, doc.Select("*|mixedCase").Count);
}
[NUnit.Framework.Test]
public virtual void Xml_lowercase_simple_name() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(lowercase, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.XmlParser());
NUnit.Framework.Assert.AreEqual(0, doc.Select("lowercase").Count);
}
[NUnit.Framework.Test]
public virtual void Xml_lowercase_wildcard_name() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(lowercase, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser
.XmlParser());
NUnit.Framework.Assert.AreEqual(1, doc.Select("*|lowercase").Count);
}
[NUnit.Framework.Test]
public virtual void TrimSelector() {
// https://github.com/jhy/jsoup/issues/1274
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<p><span>Hello");
Elements els = doc.Select(" p span ");
NUnit.Framework.Assert.AreEqual(1, els.Count);
NUnit.Framework.Assert.AreEqual("Hello", els.First().Text());
}
[NUnit.Framework.Test]
public virtual void XmlWildcardNamespaceTest() {
// https://github.com/jhy/jsoup/issues/1208
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<ns1:MyXmlTag>1111</ns1:MyXmlTag><ns2:MyXmlTag>2222</ns2:MyXmlTag>"
, "", TSpdf.StyledXmlParser.Jsoup.Parser.Parser.XmlParser());
Elements select = doc.Select("*|MyXmlTag");
NUnit.Framework.Assert.AreEqual(2, select.Count);
NUnit.Framework.Assert.AreEqual("1111", select[0].Text());
NUnit.Framework.Assert.AreEqual("2222", select[1].Text());
}
[NUnit.Framework.Test]
public virtual void ChildElements() {
// https://github.com/jhy/jsoup/issues/1292
String html = "<body><span id=1>One <span id=2>Two</span></span></body>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element outer = doc.SelectFirst("span");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element span = outer.SelectFirst("span");
TSpdf.StyledXmlParser.Jsoup.Nodes.Element inner = outer.SelectFirst("* span");
NUnit.Framework.Assert.AreEqual("1", outer.Id());
NUnit.Framework.Assert.AreEqual("1", span.Id());
NUnit.Framework.Assert.AreEqual("2", inner.Id());
NUnit.Framework.Assert.AreEqual(outer, span);
NUnit.Framework.Assert.AreNotEqual(outer, inner);
}
[NUnit.Framework.Test]
public virtual void SelectFirstLevelChildrenOnly() {
// testcase for https://github.com/jhy/jsoup/issues/984
String html = "<div><span>One <span>Two</span></span> <span>Three <span>Four</span></span>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element div = doc.SelectFirst("div");
NUnit.Framework.Assert.IsNotNull(div);
// want to select One and Three only - the first level children
Elements spans = div.Select(":root > span");
NUnit.Framework.Assert.AreEqual(2, spans.Count);
NUnit.Framework.Assert.AreEqual("One Two", spans[0].Text());
NUnit.Framework.Assert.AreEqual("Three Four", spans[1].Text());
}
}
}

View File

@@ -0,0 +1,233 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Text;
using TSpdf.StyledXmlParser.Jsoup.Nodes;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Jsoup.Select {
[NUnit.Framework.Category("UnitTest")]
public class TraversorTest : ExtendedTSpdfTest {
// Note: NodeTraversor.traverse(new NodeVisitor) is tested in
// ElementsTest#traverse()
[NUnit.Framework.Test]
public virtual void FilterVisit() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>Hello</p></div><div>There</div>");
StringBuilder accum = new StringBuilder();
NodeTraversor.Filter(new _NodeFilter_44(accum), doc.Select("div"));
NUnit.Framework.Assert.AreEqual("<div><p><#text></#text></p></div><div><#text></#text></div>", accum.ToString
());
}
private sealed class _NodeFilter_44 : NodeFilter {
public _NodeFilter_44(StringBuilder accum) {
this.accum = accum;
}
public override NodeFilter.FilterResult Head(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
accum.Append("<").Append(node.NodeName()).Append(">");
return NodeFilter.FilterResult.CONTINUE;
}
public override NodeFilter.FilterResult Tail(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
accum.Append("</").Append(node.NodeName()).Append(">");
return NodeFilter.FilterResult.CONTINUE;
}
private readonly StringBuilder accum;
}
[NUnit.Framework.Test]
public virtual void FilterSkipChildren() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>Hello</p></div><div>There</div>");
StringBuilder accum = new StringBuilder();
NodeTraversor.Filter(new _NodeFilter_64(accum),
// OMIT contents of p:
doc.Select("div"));
NUnit.Framework.Assert.AreEqual("<div><p></p></div><div><#text></#text></div>", accum.ToString());
}
private sealed class _NodeFilter_64 : NodeFilter {
public _NodeFilter_64(StringBuilder accum) {
this.accum = accum;
}
public override NodeFilter.FilterResult Head(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
accum.Append("<").Append(node.NodeName()).Append(">");
return ("p".Equals(node.NodeName())) ? NodeFilter.FilterResult.SKIP_CHILDREN : NodeFilter.FilterResult.CONTINUE;
}
public override NodeFilter.FilterResult Tail(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
accum.Append("</").Append(node.NodeName()).Append(">");
return NodeFilter.FilterResult.CONTINUE;
}
private readonly StringBuilder accum;
}
[NUnit.Framework.Test]
public virtual void FilterSkipEntirely() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>Hello</p></div><div>There</div>");
StringBuilder accum = new StringBuilder();
NodeTraversor.Filter(new _NodeFilter_85(accum),
// OMIT p:
doc.Select("div"));
NUnit.Framework.Assert.AreEqual("<div></div><div><#text></#text></div>", accum.ToString());
}
private sealed class _NodeFilter_85 : NodeFilter {
public _NodeFilter_85(StringBuilder accum) {
this.accum = accum;
}
public override NodeFilter.FilterResult Head(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
if ("p".Equals(node.NodeName())) {
return NodeFilter.FilterResult.SKIP_ENTIRELY;
}
accum.Append("<").Append(node.NodeName()).Append(">");
return NodeFilter.FilterResult.CONTINUE;
}
public override NodeFilter.FilterResult Tail(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
accum.Append("</").Append(node.NodeName()).Append(">");
return NodeFilter.FilterResult.CONTINUE;
}
private readonly StringBuilder accum;
}
[NUnit.Framework.Test]
public virtual void FilterRemove() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>Hello</p></div><div>There be <b>bold</b></div>"
);
NodeTraversor.Filter(new _NodeFilter_107(),
// Delete "p" in head:
// Delete "b" in tail:
doc.Select("div"));
NUnit.Framework.Assert.AreEqual("<div></div>\n<div>\n There be \n</div>", doc.Select("body").Html());
}
private sealed class _NodeFilter_107 : NodeFilter {
public _NodeFilter_107() {
}
public override NodeFilter.FilterResult Head(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
return ("p".Equals(node.NodeName())) ? NodeFilter.FilterResult.REMOVE : NodeFilter.FilterResult.CONTINUE;
}
public override NodeFilter.FilterResult Tail(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
return ("b".Equals(node.NodeName())) ? NodeFilter.FilterResult.REMOVE : NodeFilter.FilterResult.CONTINUE;
}
}
[NUnit.Framework.Test]
public virtual void FilterStop() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p>Hello</p></div><div>There</div>");
StringBuilder accum = new StringBuilder();
NodeTraversor.Filter(new _NodeFilter_127(accum),
// Stop after p.
doc.Select("div"));
NUnit.Framework.Assert.AreEqual("<div><p><#text></#text></p>", accum.ToString());
}
private sealed class _NodeFilter_127 : NodeFilter {
public _NodeFilter_127(StringBuilder accum) {
this.accum = accum;
}
public override NodeFilter.FilterResult Head(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
accum.Append("<").Append(node.NodeName()).Append(">");
return NodeFilter.FilterResult.CONTINUE;
}
public override NodeFilter.FilterResult Tail(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
accum.Append("</").Append(node.NodeName()).Append(">");
return ("p".Equals(node.NodeName())) ? NodeFilter.FilterResult.STOP : NodeFilter.FilterResult.CONTINUE;
}
private readonly StringBuilder accum;
}
[NUnit.Framework.Test]
public virtual void ReplaceElement() {
// https://github.com/jhy/jsoup/issues/1289
// test we can replace an element during traversal
String html = "<div><p>One <i>two</i> <i>three</i> four.</p></div>";
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse(html);
NodeTraversor.Traverse(new _NodeVisitor_150(), doc);
TSpdf.StyledXmlParser.Jsoup.Nodes.Element p = doc.SelectFirst("p");
NUnit.Framework.Assert.IsNotNull(p);
NUnit.Framework.Assert.AreEqual("<p>One <u>two</u> <u>three</u> four.</p>", p.OuterHtml());
}
private sealed class _NodeVisitor_150 : NodeVisitor {
public _NodeVisitor_150() {
}
public void Head(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
if (node is TSpdf.StyledXmlParser.Jsoup.Nodes.Element) {
TSpdf.StyledXmlParser.Jsoup.Nodes.Element el = (TSpdf.StyledXmlParser.Jsoup.Nodes.Element)node;
if (el.NormalName().Equals("i")) {
TSpdf.StyledXmlParser.Jsoup.Nodes.Element u = new TSpdf.StyledXmlParser.Jsoup.Nodes.Element("u").InsertChildren
(0, el.ChildNodes());
el.ReplaceWith(u);
}
}
}
public void Tail(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
}
}
[NUnit.Framework.Test]
public virtual void CanAddChildren() {
Document doc = TSpdf.StyledXmlParser.Jsoup.Jsoup.Parse("<div><p></p><p></p></div>");
NodeTraversor.Traverse(new _NodeVisitor_174(), doc);
NUnit.Framework.Assert.AreEqual("<div>\n" + " <p><span>0</span><span>1</span></p>\n" + " <p><span>2</span><span>3</span></p>\n"
+ "</div>", doc.Body().Html());
}
private sealed class _NodeVisitor_174 : NodeVisitor {
public _NodeVisitor_174() {
this.i = 0;
}
internal int i;
public void Head(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
if (node.NodeName().Equals("p")) {
TSpdf.StyledXmlParser.Jsoup.Nodes.Element p = (TSpdf.StyledXmlParser.Jsoup.Nodes.Element)node;
p.Append("<span>" + this.i++ + "</span>");
}
}
public void Tail(TSpdf.StyledXmlParser.Jsoup.Nodes.Node node, int depth) {
if (node.NodeName().Equals("p")) {
TSpdf.StyledXmlParser.Jsoup.Nodes.Element p = (TSpdf.StyledXmlParser.Jsoup.Nodes.Element)node;
p.Append("<span>" + this.i++ + "</span>");
}
}
}
}
}

View File

@@ -0,0 +1,221 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.IO;
using TSpdf.IO.Util;
using TSpdf.StyledXmlParser.Exceptions;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Resolver.Resource {
[NUnit.Framework.Category("UnitTest")]
public class LimitedInputStreamTest : ExtendedTSpdfTest {
private readonly String baseUri = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/styledxmlparser/resolver/retrieveStreamTest/";
[NUnit.Framework.Test]
public virtual void ReadingByteAfterFileReadingTest() {
UriResolver uriResolver = new UriResolver(baseUri);
Uri url = uriResolver.ResolveAgainstBaseUri("retrieveStyleSheetTest.css.dat");
// retrieveStyleSheetTest.css.dat size is 89 bytes
Stream stream = new LimitedInputStream(UrlUtil.OpenStream(url), 100);
// The user can call the reading methods as many times as he want, and if the
// stream has been read, then should not throw an ReadingByteLimitException exception
for (int i = 0; i < 101; i++) {
stream.Read();
}
}
[NUnit.Framework.Test]
public virtual void ReadingByteArrayAfterFileReadingTest() {
UriResolver uriResolver = new UriResolver(baseUri);
Uri url = uriResolver.ResolveAgainstBaseUri("retrieveStyleSheetTest.css.dat");
// retrieveStyleSheetTest.css.dat size is 89 bytes
Stream stream = new LimitedInputStream(UrlUtil.OpenStream(url), 100);
// The user can call the reading methods as many times as he want, and if the
// stream has been read, then should not throw an ReadingByteLimitException exception
stream.Read(new byte[100]);
stream.Read(new byte[1]);
}
[NUnit.Framework.Test]
public virtual void ReadingByteArrayWithOffsetAfterFileReadingTest() {
UriResolver uriResolver = new UriResolver(baseUri);
Uri url = uriResolver.ResolveAgainstBaseUri("retrieveStyleSheetTest.css.dat");
// retrieveStyleSheetTest.css.dat size is 89 bytes
Stream stream = new LimitedInputStream(UrlUtil.OpenStream(url), 100);
// The user can call the reading methods as many times as he want, and if the
// stream has been read, then should not throw an ReadingByteLimitException exception
stream.JRead(new byte[100], 0, 100);
stream.JRead(new byte[1], 0, 1);
}
[NUnit.Framework.Test]
public virtual void ReadingByteWithLimitOfOneLessThenFileSizeTest() {
UriResolver uriResolver = new UriResolver(baseUri);
Uri url = uriResolver.ResolveAgainstBaseUri("retrieveStyleSheetTest.css.dat");
// retrieveStyleSheetTest.css.dat size is 89 bytes
Stream stream = new LimitedInputStream(UrlUtil.OpenStream(url), 88);
for (int i = 0; i < 88; i++) {
NUnit.Framework.Assert.AreNotEqual(-1, stream.Read());
}
NUnit.Framework.Assert.Catch(typeof(ReadingByteLimitException), () => stream.Read());
}
[NUnit.Framework.Test]
public virtual void ReadingByteArrayWithLimitOfOneLessThenFileSizeTest() {
UriResolver uriResolver = new UriResolver(baseUri);
Uri url = uriResolver.ResolveAgainstBaseUri("retrieveStyleSheetTest.css.dat");
// retrieveStyleSheetTest.css.dat size is 89 bytes
Stream stream = new LimitedInputStream(UrlUtil.OpenStream(url), 88);
byte[] bytes = new byte[100];
int numOfReadBytes = stream.Read(bytes);
NUnit.Framework.Assert.AreEqual(88, numOfReadBytes);
NUnit.Framework.Assert.AreEqual(10, bytes[87]);
NUnit.Framework.Assert.AreEqual(0, bytes[88]);
NUnit.Framework.Assert.Catch(typeof(ReadingByteLimitException), () => stream.Read(new byte[1]));
}
[NUnit.Framework.Test]
public virtual void ReadingByteArrayWithOffsetAndLimitOfOneLessThenFileSizeTest() {
UriResolver uriResolver = new UriResolver(baseUri);
Uri url = uriResolver.ResolveAgainstBaseUri("retrieveStyleSheetTest.css.dat");
// retrieveStyleSheetTest.css.dat size is 89 bytes
Stream stream = new LimitedInputStream(UrlUtil.OpenStream(url), 88);
byte[] bytes = new byte[100];
int numOfReadBytes = stream.JRead(bytes, 0, 88);
NUnit.Framework.Assert.AreEqual(88, numOfReadBytes);
NUnit.Framework.Assert.AreEqual(10, bytes[87]);
NUnit.Framework.Assert.AreEqual(0, bytes[88]);
NUnit.Framework.Assert.Catch(typeof(ReadingByteLimitException), () => stream.JRead(bytes, 88, 1));
}
[NUnit.Framework.Test]
public virtual void ReadingByteArrayWithSmallBufferTest() {
UriResolver uriResolver = new UriResolver(baseUri);
Uri url = uriResolver.ResolveAgainstBaseUri("retrieveStyleSheetTest.css.dat");
// retrieveStyleSheetTest.css.dat size is 89 bytes
Stream stream = new LimitedInputStream(UrlUtil.OpenStream(url), 89);
byte[] bytes = new byte[20];
MemoryStream output = new MemoryStream();
while (true) {
int read = stream.Read(bytes);
if (read < 1) {
break;
}
output.Write(bytes, 0, read);
}
NUnit.Framework.Assert.AreEqual(89, output.Length);
output.Dispose();
}
[NUnit.Framework.Test]
public virtual void ReadingByteArrayWithBigBufferTest() {
UriResolver uriResolver = new UriResolver(baseUri);
Uri url = uriResolver.ResolveAgainstBaseUri("retrieveStyleSheetTest.css.dat");
// retrieveStyleSheetTest.css.dat size is 89 bytes
Stream stream = new LimitedInputStream(UrlUtil.OpenStream(url), 89);
byte[] bytes = new byte[100];
NUnit.Framework.Assert.AreEqual(89, stream.Read(bytes));
byte[] tempBytes = (byte[])bytes.Clone();
NUnit.Framework.Assert.AreEqual(-1, stream.Read(bytes));
// Check that the array has not changed when we have read the entire LimitedInputStream
NUnit.Framework.Assert.AreEqual(tempBytes, bytes);
}
[NUnit.Framework.Test]
public virtual void ReadingByteArrayWithOffsetAndBigBufferTest() {
UriResolver uriResolver = new UriResolver(baseUri);
Uri url = uriResolver.ResolveAgainstBaseUri("retrieveStyleSheetTest.css.dat");
// retrieveStyleSheetTest.css.dat size is 89 bytes
Stream stream = new LimitedInputStream(UrlUtil.OpenStream(url), 89);
byte[] bytes = new byte[100];
NUnit.Framework.Assert.AreEqual(89, stream.JRead(bytes, 0, 100));
byte[] tempBytes = (byte[])bytes.Clone();
NUnit.Framework.Assert.AreEqual(-1, stream.JRead(bytes, 0, 100));
// Check that the array has not changed when we have read the entire LimitedInputStream
NUnit.Framework.Assert.AreEqual(tempBytes, bytes);
}
[NUnit.Framework.Test]
public virtual void ByteArrayOverwritingTest() {
UriResolver uriResolver = new UriResolver(baseUri);
Uri url = uriResolver.ResolveAgainstBaseUri("retrieveStyleSheetTest.css.dat");
// retrieveStyleSheetTest.css.dat size is 89 bytes
Stream stream = new LimitedInputStream(UrlUtil.OpenStream(url), 90);
byte[] bytes = new byte[100];
bytes[89] = 13;
NUnit.Framework.Assert.AreEqual(89, stream.Read(bytes));
// Check that when calling the read(byte[]) method, as many bytes were copied into
// the original array as were read, and not all bytes from the auxiliary array.
NUnit.Framework.Assert.AreEqual(13, bytes[89]);
}
[NUnit.Framework.Test]
public virtual void ReadingByteWithZeroLimitTest() {
LimitedInputStream stream = new LimitedInputStream(new MemoryStream(new byte[1]), 0);
NUnit.Framework.Assert.Catch(typeof(ReadingByteLimitException), () => stream.Read());
}
[NUnit.Framework.Test]
public virtual void ReadingByteArrayWithZeroLimitTest() {
LimitedInputStream stream = new LimitedInputStream(new MemoryStream(new byte[1]), 0);
byte[] bytes = new byte[100];
NUnit.Framework.Assert.Catch(typeof(ReadingByteLimitException), () => stream.Read(bytes));
}
[NUnit.Framework.Test]
public virtual void ReadingByteArrayWithOffsetAndZeroLimitTest() {
LimitedInputStream stream = new LimitedInputStream(new MemoryStream(new byte[1]), 0);
byte[] bytes = new byte[100];
NUnit.Framework.Assert.Catch(typeof(ReadingByteLimitException), () => stream.JRead(bytes, 0, 100));
}
[NUnit.Framework.Test]
public virtual void ReadingEmptyByteWithZeroLimitTest() {
LimitedInputStream stream = new LimitedInputStream(new MemoryStream(new byte[0]), 0);
NUnit.Framework.Assert.AreEqual(-1, stream.Read());
}
[NUnit.Framework.Test]
public virtual void ReadingEmptyByteArrayWithZeroLimitTest() {
LimitedInputStream stream = new LimitedInputStream(new MemoryStream(new byte[0]), 0);
byte[] bytes = new byte[100];
NUnit.Framework.Assert.AreEqual(-1, stream.Read(bytes));
}
[NUnit.Framework.Test]
public virtual void ReadingEmptyByteArrayWithOffsetAndZeroLimitTest() {
LimitedInputStream stream = new LimitedInputStream(new MemoryStream(new byte[0]), 0);
byte[] bytes = new byte[100];
NUnit.Framework.Assert.AreEqual(-1, stream.JRead(bytes, 0, 100));
}
[NUnit.Framework.Test]
public virtual void IllegalReadingByteLimitValueTest() {
Exception e = NUnit.Framework.Assert.Catch(typeof(ArgumentException), () => new LimitedInputStream(new MemoryStream
(new byte[0]), -1));
NUnit.Framework.Assert.AreEqual(StyledXmlParserExceptionMessage.READING_BYTE_LIMIT_MUST_NOT_BE_LESS_ZERO,
e.Message);
}
}
}

View File

@@ -0,0 +1,499 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: Bruno Lowagie, Paulo Soares, et al.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.IO;
using TSpdf.IO.Util;
using TSpdf.Kernel.Pdf.Xobject;
using TSpdf.StyledXmlParser.Exceptions;
using TSpdf.StyledXmlParser.Logs;
using TSpdf.Test;
using TSpdf.Test.Attributes;
using NUnit.Framework;
namespace TSpdf.StyledXmlParser.Resolver.Resource {
class ResourceResolverTest : ExtendedTSpdfTest {
private static readonly String baseUri = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework
.TestContext
.CurrentContext.TestDirectory) +
"/resources/TSpdf/styledxmlparser/resolver/retrieveStreamTest/";
private static readonly String bLogoIncorrect =
"data:image/png;base,iVBORw0KGgoAAAANSUhEUgAAAVoAAAAxCAMAAACsy5FpAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAqUExURQAAAPicJAdJdQdJdQdJdficJjBUbPicJgdJdQdJdficJficJQdJdficJlrFe50AAAAMdFJOUwCBe8I/Phe+65/saIJg0K4AAAMOSURBVHja7ZvbmqsgDIU5Bo/v/7q7/WZXsQYNuGy1muuZFH7DIiSglFLU6pZUbGQQNvXpNcC4caoNRvNxOuDUdf80HXk3VYewKp516DHWxuOc/0ye/U00duAwU+/qkWzfh9F9hzIHJxuzNa+fsa4I7Ihx+H+qUFN/sKVhzP7lH+a+qwY1gJHtmwFDPBHK1wLLjLOGTb2jIWhHScAF7RgOGod2CAGTFB8J2JodJ3Dq5kNow95oH3BdtsjGHE6LVu+P9iG5UlVwNjXOndGeRWuZEBBJLtWcMMK11nFoDfDL4TOEMUu0K/leIpNNpUrYFVsrDi2Mbb1DXqv5PV4quWzKHikJKq99utTsoI1dsMjBkr2dctoAMO3XQS2ogrNrJ5vH1OvtU6/ddIPR0k1g9K++bcSKo6Htf8wbdxpK2rnRigJRqAU3WiEylzzVlubCF0TLb/pTyZXH9o1WoKLVoKK8yBbUHS6IdjksZYpxo82WXIzIXhptYtmDRPbQaDXiPBZaaQl26ZBI6pfQ+gZ00A3CxkH6COo2rIwjom12KM/IJRehBUdF2wLrtUWS+56P/Q7aPUrheYnYRpE9LtrwSbSp7cxuJnv1qCWzk9AeEy3t0MAp2ccq93NogWHry3QWowqHPDK0mPSr8aXZAWQzO+hB17ebb9P5ZbDCu2obJPeiNQQWbAUse10VbbKqSLm9yRutQGT/8wO0G6+LdvV2Aaq0eDW0kmI3SHKvhZZkESnoTd5o5SIr+gb0A2g9wGQi67KUw5wdLajNEHymyCqo5B4RLawWHp10XcEC528suBOjJVwDZ2iOca9lBNsSl4jZE6Ntd6jXmtKVzeiIOy/aDzwTydmPZpJrzov2A89EsrKod8mVoq1y0LbsE02Zf/sVQSAObXa5ZSq5UkGoZw9LlqwRNkai5ZT7rRXyHkJgQqioSBipgjhGHPdMYy3hbLx8UDbDPTatndyeeW1HpaXtodxYyUO+zmoDUWjeUnHRB7d5E/KQnazRs0VdbWjI/EluloPnb26+KXIGI+e+7CBt/wAetDeCKwxY6QAAAABJRU5ErkJggg==";
private static readonly String bLogoCorruptedData =
"data:image/png;base64,,,iVBORw0KGgoAAAANSUhEUgAAAVoAAAAxCAMAAACsy5FpAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAqUExURQAAAPicJAdJdQdJdQdJdficJjBUbPicJgdJdQdJdficJficJQdJdficJlrFe50AAAAMdFJOUwCBe8I/Phe+65/saIJg0K4AAAMOSURBVHja7ZvbmqsgDIU5Bo/v/7q7/WZXsQYNuGy1muuZFH7DIiSglFLU6pZUbGQQNvXpNcC4caoNRvNxOuDUdf80HXk3VYewKp516DHWxuOc/0ye/U00duAwU+/qkWzfh9F9hzIHJxuzNa+fsa4I7Ihx+H+qUFN/sKVhzP7lH+a+qwY1gJHtmwFDPBHK1wLLjLOGTb2jIWhHScAF7RgOGod2CAGTFB8J2JodJ3Dq5kNow95oH3BdtsjGHE6LVu+P9iG5UlVwNjXOndGeRWuZEBBJLtWcMMK11nFoDfDL4TOEMUu0K/leIpNNpUrYFVsrDi2Mbb1DXqv5PV4quWzKHikJKq99utTsoI1dsMjBkr2dctoAMO3XQS2ogrNrJ5vH1OvtU6/ddIPR0k1g9K++bcSKo6Htf8wbdxpK2rnRigJRqAU3WiEylzzVlubCF0TLb/pTyZXH9o1WoKLVoKK8yBbUHS6IdjksZYpxo82WXIzIXhptYtmDRPbQaDXiPBZaaQl26ZBI6pfQ+gZ00A3CxkH6COo2rIwjom12KM/IJRehBUdF2wLrtUWS+56P/Q7aPUrheYnYRpE9LtrwSbSp7cxuJnv1qCWzk9AeEy3t0MAp2ccq93NogWHry3QWowqHPDK0mPSr8aXZAWQzO+hB17ebb9P5ZbDCu2obJPeiNQQWbAUse10VbbKqSLm9yRutQGT/8wO0G6+LdvV2Aaq0eDW0kmI3SHKvhZZkESnoTd5o5SIr+gb0A2g9wGQi67KUw5wdLajNEHymyCqo5B4RLawWHp10XcEC528suBOjJVwDZ2iOca9lBNsSl4jZE6Ntd6jXmtKVzeiIOy/aDzwTydmPZpJrzov2A89EsrKod8mVoq1y0LbsE02Zf/sVQSAObXa5ZSq5UkGoZw9LlqwRNkai5ZT7rRXyHkJgQqioSBipgjhGHPdMYy3hbLx8UDbDPTatndyeeW1HpaXtodxYyUO+zmoDUWjeUnHRB7d5E/KQnazRs0VdbWjI/EluloPnb26+KXIGI+e+7CBt/wAetDeCKwxY6QAAAABJRU5ErkJggg==";
private static readonly String bLogo =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAVoAAAAxCAMAAACsy5FpAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAqUExURQAAAPicJAdJdQdJdQdJdficJjBUbPicJgdJdQdJdficJficJQdJdficJlrFe50AAAAMdFJOUwCBe8I/Phe+65/saIJg0K4AAAMOSURBVHja7ZvbmqsgDIU5Bo/v/7q7/WZXsQYNuGy1muuZFH7DIiSglFLU6pZUbGQQNvXpNcC4caoNRvNxOuDUdf80HXk3VYewKp516DHWxuOc/0ye/U00duAwU+/qkWzfh9F9hzIHJxuzNa+fsa4I7Ihx+H+qUFN/sKVhzP7lH+a+qwY1gJHtmwFDPBHK1wLLjLOGTb2jIWhHScAF7RgOGod2CAGTFB8J2JodJ3Dq5kNow95oH3BdtsjGHE6LVu+P9iG5UlVwNjXOndGeRWuZEBBJLtWcMMK11nFoDfDL4TOEMUu0K/leIpNNpUrYFVsrDi2Mbb1DXqv5PV4quWzKHikJKq99utTsoI1dsMjBkr2dctoAMO3XQS2ogrNrJ5vH1OvtU6/ddIPR0k1g9K++bcSKo6Htf8wbdxpK2rnRigJRqAU3WiEylzzVlubCF0TLb/pTyZXH9o1WoKLVoKK8yBbUHS6IdjksZYpxo82WXIzIXhptYtmDRPbQaDXiPBZaaQl26ZBI6pfQ+gZ00A3CxkH6COo2rIwjom12KM/IJRehBUdF2wLrtUWS+56P/Q7aPUrheYnYRpE9LtrwSbSp7cxuJnv1qCWzk9AeEy3t0MAp2ccq93NogWHry3QWowqHPDK0mPSr8aXZAWQzO+hB17ebb9P5ZbDCu2obJPeiNQQWbAUse10VbbKqSLm9yRutQGT/8wO0G6+LdvV2Aaq0eDW0kmI3SHKvhZZkESnoTd5o5SIr+gb0A2g9wGQi67KUw5wdLajNEHymyCqo5B4RLawWHp10XcEC528suBOjJVwDZ2iOca9lBNsSl4jZE6Ntd6jXmtKVzeiIOy/aDzwTydmPZpJrzov2A89EsrKod8mVoq1y0LbsE02Zf/sVQSAObXa5ZSq5UkGoZw9LlqwRNkai5ZT7rRXyHkJgQqioSBipgjhGHPdMYy3hbLx8UDbDPTatndyeeW1HpaXtodxYyUO+zmoDUWjeUnHRB7d5E/KQnazRs0VdbWjI/EluloPnb26+KXIGI+e+7CBt/wAetDeCKwxY6QAAAABJRU5ErkJggg==";
// Constructor tests block
[Test]
public virtual void ConstructorWithBaseUriTest() {
ResourceResolver resolver = new ResourceResolver(null);
UriResolver uriResolver = new UriResolver("");
String resolveUrl = resolver.ResolveAgainstBaseUri("").ToString();
String expectedUrl = uriResolver.ResolveAgainstBaseUri("").ToString();
Assert.AreEqual(resolveUrl, expectedUrl);
Assert.AreEqual(typeof(DefaultResourceRetriever), resolver.GetRetriever().GetType());
}
[Test]
public virtual void ConstructorWithBaseUriAndResourceRetrieverTest() {
ResourceResolver resolver = new ResourceResolver("folder", new CustomResourceRetriever());
UriResolver uriResolver = new UriResolver("folder");
String resolveUrl = resolver.ResolveAgainstBaseUri("").ToString();
String expectedUrl = uriResolver.ResolveAgainstBaseUri("").ToString();
Assert.AreEqual(resolveUrl, expectedUrl);
Assert.AreEqual(typeof(CustomResourceRetriever), resolver.GetRetriever().GetType());
}
class CustomResourceRetriever : DefaultResourceRetriever {
}
// Malformed resource name tests block
[Test]
[LogMessage(StyledXmlParserLogMessageConstant.UNABLE_TO_RETRIEVE_STREAM_WITH_GIVEN_BASE_URI,
LogLevel = LogLevelConstants.ERROR)]
public virtual void RetrieveStreamByMalformedResourceNameTest() {
String fileName = "resourceResolverTest .png";
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
byte[] bytes = resourceResolver.RetrieveBytesFromResource(fileName);
Assert.Null(bytes);
}
[Test]
[LogMessage(StyledXmlParserLogMessageConstant.UNABLE_TO_RETRIEVE_STREAM_WITH_GIVEN_BASE_URI,
LogLevel = LogLevelConstants.ERROR)]
public virtual void RetrieveStyleSheetByMalformedResourceNameTest() {
String fileName = "retrieveStyl eSheetTest.css";
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
resourceResolver.RetrieveResourceAsInputStream(fileName);
}
[Test]
[LogMessage(StyledXmlParserLogMessageConstant.UNABLE_TO_RETRIEVE_STREAM_WITH_GIVEN_BASE_URI,
LogLevel = LogLevelConstants.ERROR)]
public virtual void RetrieveResourceAsInputStreamByMalformedResourceNameTest() {
String fileName = "retrieveStyl eSheetTest.css";
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
Stream stream = resourceResolver.RetrieveResourceAsInputStream(fileName);
Assert.Null(stream);
}
[Test]
[LogMessage(StyledXmlParserLogMessageConstant.UNABLE_TO_RETRIEVE_STREAM_WITH_GIVEN_BASE_URI,
LogLevel = LogLevelConstants.ERROR)]
public virtual void RetrieveBytesFromResourceByMalformedResourceNameTest() {
String fileName = "retrieveStyl eSheetTest.css";
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
byte[] bytes = resourceResolver.RetrieveBytesFromResource(fileName);
Assert.Null(bytes);
}
[Test]
[LogMessage(StyledXmlParserLogMessageConstant.UNABLE_TO_RETRIEVE_IMAGE_WITH_GIVEN_BASE_URI,
LogLevel = LogLevelConstants.ERROR)]
public virtual void RetrieveImageExtendedByMalformedResourceNameTest() {
String fileName = "retrieveStyl eSheetTest.css";
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
PdfXObject pdfXObject = resourceResolver.RetrieveImage(fileName);
Assert.Null(pdfXObject);
}
[Test]
public virtual void MalformedResourceNameTest07() {
String fileName = "%23%5B%5D@!$&'()+,;=._~-/styles09.css";
Stream expected = new FileStream(baseUri + "#[]@!$&'()+,;=._~-/styles09.css", FileMode.Open, FileAccess.Read);
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
Stream stream = resourceResolver.RetrieveResourceAsInputStream(fileName);
Assert.NotNull(stream);
Assert.AreEqual(expected.Read(), stream.Read());
}
// Boolean method tests block
[Test]
public virtual void IsDataSrcTest() {
Assert.True(ResourceResolver.IsDataSrc(bLogo));
Assert.True(ResourceResolver.IsDataSrc(bLogoCorruptedData));
Assert.True(ResourceResolver.IsDataSrc(bLogoIncorrect));
Assert.False(ResourceResolver.IsDataSrc("https://data.com/data"));
}
// Retrieve pdfXObject tests block
[Test]
public virtual void RetrieveImageBase64Test() {
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
PdfXObject image = resourceResolver.RetrieveImage(bLogo);
Assert.NotNull(image);
}
[Test]
[LogMessage(StyledXmlParserLogMessageConstant.UNABLE_TO_RETRIEVE_IMAGE_WITH_GIVEN_DATA_URI)]
public virtual void RetrieveImageIncorrectBase64Test() {
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
PdfXObject image = resourceResolver.RetrieveImage(bLogoCorruptedData);
Assert.Null(image);
}
[Test]
[LogMessage(StyledXmlParserLogMessageConstant.UNABLE_TO_RETRIEVE_IMAGE_WITH_GIVEN_DATA_URI,
LogLevel = LogLevelConstants.ERROR)]
public virtual void RetrieveImageCorruptedDataBase64Test() {
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
PdfXObject image = resourceResolver.RetrieveImage(bLogoCorruptedData);
Assert.Null(image);
}
[Test]
[LogMessage(StyledXmlParserLogMessageConstant.UNABLE_TO_RETRIEVE_IMAGE_WITH_GIVEN_BASE_URI,
LogLevel = LogLevelConstants.ERROR)]
public virtual void RetrieveImageNullTest() {
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
PdfXObject image = resourceResolver.RetrieveImage(null);
Assert.Null(image);
}
[Test]
public virtual void RetrieveImageTest() {
String fileName = "resourceResolverTest.png";
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
PdfXObject image = resourceResolver.RetrieveImage(fileName);
Assert.NotNull(image);
}
// Retrieve byte array tests block
[Test]
public virtual void RetrieveBytesFromResourceBase64Test() {
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
byte[] bytes = resourceResolver.RetrieveBytesFromResource(bLogo);
Assert.NotNull(bytes);
}
[Test]
[LogMessage(StyledXmlParserLogMessageConstant.UNABLE_TO_RETRIEVE_STREAM_WITH_GIVEN_BASE_URI,
LogLevel = LogLevelConstants.ERROR)]
public virtual void RetrieveBytesFromResourceIncorrectBase64Test() {
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
byte[] bytes = resourceResolver.RetrieveBytesFromResource(bLogoIncorrect);
Assert.Null(bytes);
}
[Test]
[LogMessage(StyledXmlParserLogMessageConstant.UNABLE_TO_RETRIEVE_STREAM_WITH_GIVEN_BASE_URI,
LogLevel = LogLevelConstants.ERROR)]
public virtual void RetrieveBytesFromResourceCorruptedDataBase64Test() {
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
byte[] bytes = resourceResolver.RetrieveBytesFromResource(bLogoCorruptedData);
Assert.Null(bytes);
}
[Test]
public virtual void RetrieveBytesFromResourcePngImageTest() {
String fileName = "resourceResolverTest.png";
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
byte[] expected = File.ReadAllBytes(baseUri + fileName);
byte[] bytes = resourceResolver.RetrieveBytesFromResource(fileName);
Assert.NotNull(bytes);
Assert.AreEqual(expected.Length, bytes.Length);
}
[Test]
public virtual void RetrieveStreamPngImageTest() {
String fileName = "resourceResolverTest.png";
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
byte[] expected = File.ReadAllBytes(baseUri + fileName);
byte[] stream = resourceResolver.RetrieveBytesFromResource(fileName);
Assert.NotNull(resourceResolver.RetrieveBytesFromResource(fileName));
Assert.AreEqual(expected.Length, stream.Length);
}
[Test]
public virtual void RetrieveBytesFromResourceStyleSheetTest() {
String fileName = "retrieveStyleSheetTest.css";
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
byte[] expected = File.ReadAllBytes(baseUri + fileName);
byte[] bytes = resourceResolver.RetrieveBytesFromResource(fileName);
Assert.NotNull(bytes);
Assert.AreEqual(expected.Length, bytes.Length);
}
[Test]
[LogMessage(StyledXmlParserLogMessageConstant.RESOURCE_WITH_GIVEN_URL_WAS_FILTERED_OUT, LogLevel = LogLevelConstants.WARN)]
public virtual void AttemptToRetrieveBytesFromResourceStyleSheetWithFilterRetrieverTest() {
String fileName = "retrieveStyleSheetTest.css";
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
resourceResolver.SetRetriever(new FilterResourceRetriever());
byte[] bytes = resourceResolver.RetrieveBytesFromResource(fileName);
Assert.Null(bytes);
}
[Test]
[LogMessage(StyledXmlParserLogMessageConstant.UNABLE_TO_RETRIEVE_IMAGE_WITH_GIVEN_BASE_URI)]
public virtual void RetrieveImageWrongPathTest() {
String fileName = "/TSpdfpdf.com/itis.jpg";
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
PdfXObject image = resourceResolver.RetrieveImage(fileName);
Assert.Null(image);
}
[Test]
public virtual void RetrieveImageRightPathTest() {
String fileName = "TSpdfpdf.com/itis.jpg";
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
PdfXObject image = resourceResolver.RetrieveImage(fileName);
Assert.NotNull(image);
}
[Test]
public virtual void RetrieveImagePathWithSpacesTest() {
String fileName = "retrieveImagePathWithSpaces.jpg";
ResourceResolver resourceResolver = new ResourceResolver(baseUri + "path with spaces/");
PdfXObject image = resourceResolver.RetrieveImage(fileName);
Assert.NotNull(image);
}
[Test]
[LogMessage(StyledXmlParserLogMessageConstant.UNABLE_TO_RETRIEVE_STREAM_WITH_GIVEN_BASE_URI)]
public virtual void RetrieveBytesMalformedResourceNameTest() {
String fileName = "resourceResolverTest .png";
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
byte[] bytes =resourceResolver.RetrieveBytesFromResource(fileName);
Assert.Null(bytes);
}
[Test]
public virtual void RetrieveBytesFromResourceWithRetryRetrieverTest() {
String fileName = "!invalid! StyleSheetName.css";
ResourceResolver resourceResolver = new ResourceResolver(baseUri, new RetryResourceRetriever(baseUri));
byte[] expected = File.ReadAllBytes(baseUri + "retrieveStyleSheetTest.css");
byte[] bytes = resourceResolver.RetrieveBytesFromResource(fileName);
Assert.NotNull(bytes);
Assert.AreEqual(expected.Length, bytes.Length);
}
[Test]
[LogMessage(StyledXmlParserLogMessageConstant.UNABLE_TO_RETRIEVE_RESOURCE_WITH_GIVEN_RESOURCE_SIZE_BYTE_LIMIT,
LogLevel = LogLevelConstants.WARN)]
public virtual void AttemptToRetrieveBytesFromLocalWithResourceSizeByteLimitTest() {
String fileName = "retrieveStyleSheetTest.css";
// retrieveStyleSheetTest.css size is 89 bytes
IResourceRetriever retriever = new DefaultResourceRetriever().SetResourceSizeByteLimit(88);
ResourceResolver resourceResolver = new ResourceResolver(baseUri, retriever);
byte[] bytes = resourceResolver.RetrieveBytesFromResource(fileName);
Assert.Null(bytes);
}
[Test]
public virtual void RetrieveBytesFromLocalWithResourceSizeByteLimitTest() {
String fileName = "retrieveStyleSheetTest.css.dat";
// retrieveStyleSheetTest.css.dat size is 89 bytes
IResourceRetriever retriever = new DefaultResourceRetriever().SetResourceSizeByteLimit(89);
ResourceResolver resourceResolver = new ResourceResolver(baseUri, retriever);
byte[] bytes = resourceResolver.RetrieveBytesFromResource(fileName);
Assert.NotNull(bytes);
Assert.AreEqual(((DefaultResourceRetriever) retriever).GetResourceSizeByteLimit(), bytes.Length);
}
// Retrieve input stream tests block
[Test]
public virtual void AttemptToReadBytesFromLimitedInputStreamTest() {
String fileName = "retrieveStyleSheetTest.css";
// retrieveStyleSheetTest.css size is 89 bytes
IResourceRetriever retriever = new DefaultResourceRetriever().SetResourceSizeByteLimit(40);
ResourceResolver resourceResolver = new ResourceResolver(baseUri, retriever);
Stream stream = resourceResolver.RetrieveResourceAsInputStream(fileName);
for (int i = 0; i < 40; i++) {
stream.Read();
}
Assert.Catch(typeof(ReadingByteLimitException), () => stream.Read());
}
[Test]
public virtual void RetrieveResourceAsInputStreamBase64Test() {
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
Stream stream = resourceResolver.RetrieveResourceAsInputStream(bLogo);
Assert.NotNull(stream);
}
[Test]
public virtual void RetrieveStyleSheetTest() {
String fileName = "retrieveStyleSheetTest.css";
Stream expected = new FileStream(baseUri + fileName, FileMode.Open, FileAccess.Read);
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
Stream stream = resourceResolver.RetrieveResourceAsInputStream(fileName);
Assert.NotNull(stream);
Assert.AreEqual(expected.Read(), stream.Read());
}
[Test]
public virtual void RetrieveResourceAsInputStreamStyleSheetTest() {
String fileName = "retrieveStyleSheetTest.css";
Stream expected = new FileStream(baseUri + fileName, FileMode.Open, FileAccess.Read);
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
Stream stream = resourceResolver.RetrieveResourceAsInputStream(fileName);
Assert.NotNull(stream);
Assert.AreEqual(expected.Read(), stream.Read());
}
[Test]
[LogMessage(StyledXmlParserLogMessageConstant.RESOURCE_WITH_GIVEN_URL_WAS_FILTERED_OUT, LogLevel = LogLevelConstants.WARN)]
public virtual void AttemptToRetrieveInputStreamWithFilterRetrieverTest() {
String fileName = "retrieveStyleSheetTest.css";
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
resourceResolver.SetRetriever(new FilterResourceRetriever());
Stream stream = resourceResolver.RetrieveResourceAsInputStream(fileName);
Assert.Null(stream);
}
class FilterResourceRetriever : DefaultResourceRetriever {
protected internal override bool UrlFilter(Uri url) {
return url.AbsolutePath.StartsWith("/MyFolderWithUniqName");
}
}
[Test]
public virtual void RetrieveInputStreamWithRetryRetrieverTest() {
String fileName = "!invalid! StyleSheetName.css";
ResourceResolver resourceResolver = new ResourceResolver(baseUri, new RetryResourceRetriever(baseUri));
Stream expected = new FileStream(baseUri + "retrieveStyleSheetTest.css", FileMode.Open, FileAccess.Read);
Stream stream = resourceResolver.RetrieveResourceAsInputStream(fileName);
Assert.NotNull(stream);
Assert.AreEqual(expected.Read(), stream.Read());
}
class RetryResourceRetriever : DefaultResourceRetriever {
private String baseUri;
public RetryResourceRetriever(String baseUri) {
this.baseUri = baseUri;
}
public override Stream GetInputStreamByUrl(Uri url) {
Stream stream = null;
try {
stream = base.GetInputStreamByUrl(url);
}
catch (Exception ignored) {
}
if (stream == null) {
Uri newUrl = new UriResolver(this.baseUri).ResolveAgainstBaseUri("retrieveStyleSheetTest.css");
stream = base.GetInputStreamByUrl(newUrl);
}
return stream;
}
}
// Absolute path tests block
[Test]
public virtual void RetrieveStyleSheetAbsolutePathTest() {
String fileName = "retrieveStyleSheetTest.css";
String absolutePath = Path.Combine(baseUri, fileName).ToFile().FullName;
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
using (Stream stream = resourceResolver.RetrieveResourceAsInputStream(absolutePath),
expected = new FileStream(absolutePath, FileMode.Open, FileAccess.Read)) {
Assert.NotNull(stream);
Assert.AreEqual(expected.Read(), stream.Read());
}
}
[Test]
public virtual void RetrieveResourceAsInputStreamAbsolutePathTest() {
String fileName = "retrieveStyleSheetTest.css";
String absolutePath = Path.Combine(baseUri, fileName).ToFile().FullName;
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
using (Stream stream = resourceResolver.RetrieveResourceAsInputStream(absolutePath),
expected = new FileStream(absolutePath, FileMode.Open, FileAccess.Read)) {
Assert.NotNull(stream);
Assert.AreEqual(expected.Read(), stream.Read());
}
}
[Test]
public virtual void RetrieveStyleSheetFileUrlTest() {
String fileName = "retrieveStyleSheetTest.css";
Uri url = Path.Combine(baseUri, fileName).ToUri().ToUrl();
String fileUrlString = url.ToExternalForm();
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
using (Stream stream = resourceResolver.RetrieveResourceAsInputStream(fileUrlString),
expected = UrlUtil.OpenStream(url)) {
Assert.NotNull(stream);
Assert.AreEqual(expected.Read(), stream.Read());
}
}
[Test]
public virtual void RetrieveResourceAsInputStreamFileUrlTest() {
String fileName = "retrieveStyleSheetTest.css";
Uri url = Path.Combine(baseUri, fileName).ToUri().ToUrl();
String fileUrlString = url.ToExternalForm();
ResourceResolver resourceResolver = new ResourceResolver(baseUri);
using (Stream stream = resourceResolver.RetrieveResourceAsInputStream(fileUrlString),
expected = UrlUtil.OpenStream(url)) {
Assert.NotNull(stream);
Assert.AreEqual(expected.Read(), stream.Read());
}
}
}
}

View File

@@ -0,0 +1,157 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using TSpdf.Kernel.Pdf;
using TSpdf.Kernel.Pdf.Xobject;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Resolver.Resource {
[NUnit.Framework.Category("UnitTest")]
public class SimpleImageCacheTest : ExtendedTSpdfTest {
[NUnit.Framework.SetUp]
public virtual void Before() {
SimpleImageCacheTest.ImageXObjectStub.ResetNumbering();
}
[NUnit.Framework.Test]
public virtual void SimpleImageCacheTest01() {
SimpleImageCache cache = new SimpleImageCache();
String imgSrc = "src1.jpg";
SimpleImageCacheTest.ImageXObjectStub imageData = new SimpleImageCacheTest.ImageXObjectStub();
NUnit.Framework.Assert.AreEqual(0, cache.Size());
cache.PutImage(imgSrc, imageData);
NUnit.Framework.Assert.AreEqual(1, cache.Size());
NUnit.Framework.Assert.AreEqual(imageData, cache.GetImage(imgSrc));
}
[NUnit.Framework.Test]
public virtual void SimpleImageCacheTest02() {
String[] imgSrc = new String[] { "src0.jpg", "src1.jpg", "src2.jpg", "src3.jpg", "src4.jpg", "src5.jpg" };
SimpleImageCacheTest.ImageXObjectStub[] imgData = new SimpleImageCacheTest.ImageXObjectStub[] { new SimpleImageCacheTest.ImageXObjectStub
(), new SimpleImageCacheTest.ImageXObjectStub(), new SimpleImageCacheTest.ImageXObjectStub(), new SimpleImageCacheTest.ImageXObjectStub
(), new SimpleImageCacheTest.ImageXObjectStub(), new SimpleImageCacheTest.ImageXObjectStub() };
SimpleImageCache cache = new SimpleImageCache(4);
// imgs frequency is increased on getImage call
cache.GetImage(imgSrc[1]);
cache.GetImage(imgSrc[2]);
cache.PutImage(imgSrc[0], imgData[0]);
cache.PutImage(imgSrc[1], imgData[1]);
cache.PutImage(imgSrc[2], imgData[2]);
NUnit.Framework.Assert.AreEqual(3, cache.Size());
cache.GetImage(imgSrc[0]);
cache.GetImage(imgSrc[1]);
cache.GetImage(imgSrc[2]);
cache.PutImage(imgSrc[3], imgData[3]);
NUnit.Framework.Assert.AreEqual(4, cache.Size());
cache.PutImage(imgSrc[4], imgData[4]);
NUnit.Framework.Assert.AreEqual(4, cache.Size());
NUnit.Framework.Assert.IsNull(cache.GetImage(imgSrc[3]));
NUnit.Framework.Assert.AreEqual(imgData[0], cache.GetImage(imgSrc[0]));
NUnit.Framework.Assert.AreEqual(imgData[1], cache.GetImage(imgSrc[1]));
NUnit.Framework.Assert.AreEqual(imgData[2], cache.GetImage(imgSrc[2]));
NUnit.Framework.Assert.AreEqual(imgData[4], cache.GetImage(imgSrc[4]));
cache.GetImage(imgSrc[0]);
cache.GetImage(imgSrc[1]);
cache.GetImage(imgSrc[2]);
cache.GetImage(imgSrc[4]);
cache.PutImage(imgSrc[5], imgData[5]);
NUnit.Framework.Assert.AreEqual(4, cache.Size());
NUnit.Framework.Assert.IsNull(cache.GetImage(imgSrc[4]));
NUnit.Framework.Assert.AreEqual(imgData[0], cache.GetImage(imgSrc[0]));
NUnit.Framework.Assert.AreEqual(imgData[1], cache.GetImage(imgSrc[1]));
NUnit.Framework.Assert.AreEqual(imgData[2], cache.GetImage(imgSrc[2]));
NUnit.Framework.Assert.AreEqual(imgData[5], cache.GetImage(imgSrc[5]));
cache.PutImage(imgSrc[3], imgData[3]);
NUnit.Framework.Assert.AreEqual(4, cache.Size());
NUnit.Framework.Assert.AreEqual(imgData[3], cache.GetImage(imgSrc[3]));
NUnit.Framework.Assert.IsNull(cache.GetImage(imgSrc[5]));
cache.PutImage(imgSrc[5], imgData[5]);
NUnit.Framework.Assert.AreEqual(4, cache.Size());
NUnit.Framework.Assert.AreEqual(imgData[5], cache.GetImage(imgSrc[5]));
NUnit.Framework.Assert.IsNull(cache.GetImage(imgSrc[3]));
cache.PutImage(imgSrc[3], imgData[3]);
NUnit.Framework.Assert.AreEqual(4, cache.Size());
NUnit.Framework.Assert.AreEqual(imgData[3], cache.GetImage(imgSrc[3]));
NUnit.Framework.Assert.IsNull(cache.GetImage(imgSrc[5]));
cache.PutImage(imgSrc[5], imgData[5]);
NUnit.Framework.Assert.AreEqual(4, cache.Size());
NUnit.Framework.Assert.AreEqual(imgData[5], cache.GetImage(imgSrc[5]));
NUnit.Framework.Assert.AreEqual(imgData[3], cache.GetImage(imgSrc[3]));
NUnit.Framework.Assert.AreEqual(imgData[1], cache.GetImage(imgSrc[1]));
NUnit.Framework.Assert.AreEqual(imgData[2], cache.GetImage(imgSrc[2]));
NUnit.Framework.Assert.IsNull(cache.GetImage(imgSrc[0]));
NUnit.Framework.Assert.IsNull(cache.GetImage(imgSrc[4]));
}
[NUnit.Framework.Test]
public virtual void OrderRemovingFromCacheTest() {
SimpleImageCache cache = new SimpleImageCache(10);
for (int j = 0; j <= 9; j++) {
cache.PutImage("src" + j + ".jpg", new SimpleImageCacheTest.ImageXObjectStub());
}
for (int i = 0; i <= 9; i++) {
cache.PutImage("src" + i + 10 + ".jpg", new SimpleImageCacheTest.ImageXObjectStub());
NUnit.Framework.Assert.IsNull(cache.GetImage("src" + i + ".jpg"));
}
}
private class ImageXObjectStub : PdfImageXObject {
private static int totalNum = 0;
private int num = 0;
internal ImageXObjectStub()
: base(new PdfStream()) {
num = totalNum++;
}
public static void ResetNumbering() {
totalNum = 0;
}
public override String ToString() {
return "ImageXObjectStub_" + num.ToString();
}
}
}
}

View File

@@ -0,0 +1,468 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: Bruno Lowagie, Paulo Soares, et al.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.IO;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Resolver.Resource {
public class UriResolverTest : ExtendedTSpdfTest {
public static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/com/TSpdfpdfstyledxmlparser/resolver/resource/UriResolverTest/";
[NUnit.Framework.Test]
public virtual void UriResolverTest01() {
String absolutePathRoot = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToExternalForm();
String absoluteBaseUri = absolutePathRoot + "test/folder/index.html";
UriResolver resolver = new UriResolver(absoluteBaseUri);
TestPaths(absolutePathRoot, resolver);
}
[NUnit.Framework.Test]
public virtual void UriResolverTest01A() {
String absolutePathRoot = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToExternalForm();
String absoluteBaseUri = absolutePathRoot + "test/folder/index.html";
UriResolver resolver = new UriResolver(absoluteBaseUri);
TestPaths(absolutePathRoot, resolver);
}
[NUnit.Framework.Test]
public virtual void UriResolverTest02() {
UriResolver resolver = new UriResolver("test/folder/index.html");
String runFolder = new Uri(Path.GetFullPath(Directory.GetCurrentDirectory() + "/")).ToExternalForm();
TestPaths(runFolder, resolver);
}
[NUnit.Framework.Test]
public virtual void UriResolverTest03() {
UriResolver resolver = new UriResolver("/test/folder/index.html");
String rootFolder = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToExternalForm();
TestPaths(rootFolder, resolver);
}
[NUnit.Framework.Test]
public virtual void UriResolverTest04() {
UriResolver resolver = new UriResolver("index.html");
String runFolder = new Uri(Path.GetFullPath(Directory.GetCurrentDirectory() + "/")).ToExternalForm();
NUnit.Framework.Assert.AreEqual(runFolder + "index.html", resolver.GetBaseUri());
NUnit.Framework.Assert.AreEqual(runFolder + "innerTest", resolver.ResolveAgainstBaseUri("innerTest").ToExternalForm
());
// Look to commentary below in TestPaths() method
// NUnit.Framework.Assert.AreEqual(runFolder + "folder2/innerTest2", resolver.ResolveAgainstBaseUri("/folder2/innerTest2"
// ).ToExternalForm());
// NUnit.Framework.Assert.AreEqual(runFolder + "folder2/innerTest2", resolver.ResolveAgainstBaseUri("//folder2/innerTest2"
// ).ToExternalForm());
}
[NUnit.Framework.Test]
public virtual void UriResolverTest05() {
UriResolver resolver = new UriResolver("/../test/folder/index.html");
String rootFolder = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToExternalForm();
TestPaths(rootFolder, resolver);
}
[NUnit.Framework.Test]
public virtual void UriResolverTest06() {
UriResolver resolver = new UriResolver("../test/folder/index.html");
String parentFolder = new Uri(Directory.GetParent(Directory.GetCurrentDirectory()).FullName).ToExternalForm() + "/";
TestPaths(parentFolder, resolver);
}
[NUnit.Framework.Test]
public virtual void ResolveAgainstBaseUriTest() {
String baseUrl = "https://test";
UriResolver resolver = new UriResolver(SOURCE_FOLDER);
resolver.ResolveAgainstBaseUri(baseUrl);
NUnit.Framework.Assert.IsTrue(resolver.IsLocalBaseUri());
NUnit.Framework.Assert.IsTrue(resolver.GetBaseUri().StartsWith("file:"));
}
[NUnit.Framework.Test]
public virtual void UriResolverTest07() {
UriResolver resolver = new UriResolver("http://TSpdfpdf.com/TSpdf7");
NUnit.Framework.Assert.AreEqual("http://TSpdfpdf.com/TSpdf7", resolver.GetBaseUri());
NUnit.Framework.Assert.AreEqual("http://TSpdfpdf.com/innerTest", resolver.ResolveAgainstBaseUri("innerTest"
).ToExternalForm());
NUnit.Framework.Assert.AreEqual("http://TSpdfpdf.com/folder2/innerTest2", resolver.ResolveAgainstBaseUri("/folder2/innerTest2"
).ToExternalForm());
NUnit.Framework.Assert.AreEqual("http://folder2.com/innerTest2", resolver.ResolveAgainstBaseUri("//folder2.com/innerTest2"
).ToExternalForm());
}
[NUnit.Framework.Test]
public virtual void UriResolverTest07A() {
String absolutePathRoot = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToExternalForm();
UriResolver resolver = new UriResolver(absolutePathRoot + "%23r%e%2525s@o%25urces/test/folder/index.html");
String malformedPath = absolutePathRoot + "%23r%25e%2525s@o%25urces/";
NUnit.Framework.Assert.AreEqual(malformedPath + "test/folder/innerTest", resolver.ResolveAgainstBaseUri
("innerTest").ToExternalForm());
NUnit.Framework.Assert.AreEqual(malformedPath + "test/folder2/innerTest2", resolver.ResolveAgainstBaseUri
("../folder2/innerTest2").ToExternalForm());
// Look to commentary below in TestPaths() method
// NUnit.Framework.Assert.AreEqual(malformedPath + "test/folder/folder2/innerTest2", resolver.ResolveAgainstBaseUri
// ("/folder2/innerTest2").ToExternalForm());
// NUnit.Framework.Assert.AreEqual(malformedPath + "test/folder/folder2/innerTest2", resolver.ResolveAgainstBaseUri
// ("//folder2/innerTest2").ToExternalForm());
}
[NUnit.Framework.Test]
public virtual void UriResolverTest07B() {
String absolutePathRoot = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToExternalForm();
UriResolver resolver = new UriResolver(absolutePathRoot + "#r%e%25s@o%urces/folder/index.html");
String malformedPath = absolutePathRoot;
NUnit.Framework.Assert.AreEqual(malformedPath + "#r%25e%25s@o%25urces/folder/index.html", resolver.GetBaseUri());
NUnit.Framework.Assert.AreEqual(malformedPath + "test/folder/innerTest", resolver.ResolveAgainstBaseUri
("test/folder/innerTest").ToExternalForm());
// Look to commentary below in TestPaths() method
// NUnit.Framework.Assert.AreEqual(malformedPath + "folder2/innerTest2", resolver.ResolveAgainstBaseUri
// ("/folder2/innerTest2").ToExternalForm());
// NUnit.Framework.Assert.AreEqual(malformedPath + "folder2/innerTest2", resolver.ResolveAgainstBaseUri
// ("//folder2/innerTest2").ToExternalForm());
}
[NUnit.Framework.Test]
public virtual void UriResolverTest08() {
UriResolver resolver = new UriResolver("http://TSpdfpdf.com/TSpdf7/");
NUnit.Framework.Assert.AreEqual("http://TSpdfpdf.com/TSpdf7/", resolver.GetBaseUri());
NUnit.Framework.Assert.AreEqual("http://TSpdfpdf.com/TSpdf7/innerTest", resolver.ResolveAgainstBaseUri("innerTest"
).ToExternalForm());
NUnit.Framework.Assert.AreEqual("http://TSpdfpdf.com/folder2/innerTest2", resolver.ResolveAgainstBaseUri("/folder2/innerTest2"
).ToExternalForm());
NUnit.Framework.Assert.AreEqual("http://folder2.com/innerTest2", resolver.ResolveAgainstBaseUri("//folder2.com/innerTest2"
).ToExternalForm());
}
[NUnit.Framework.Test]
public virtual void UriResolverTest09() {
Uri absoluteBaseUri = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory()) + "test/folder/index.html");
String absoluteBaseUriString = absoluteBaseUri.ToString();
UriResolver resolver = new UriResolver(absoluteBaseUriString);
String uriRoot = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToExternalForm();
TestPaths(uriRoot, resolver);
}
[NUnit.Framework.Test]
public virtual void UriResolverTest10A() {
String absolutePathRoot = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToExternalForm();
UriResolver resolver = new UriResolver(absolutePathRoot + "path%with%spaces/test/folder/index.html");
String malformedPath = absolutePathRoot + "path%25with%25spaces/";
TestPaths(malformedPath, resolver);
}
[NUnit.Framework.Test]
public virtual void UriResolverTest10B() {
String absolutePathRoot = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToExternalForm();
UriResolver resolver = new UriResolver(absolutePathRoot + "path%25with%25spaces/test/folder/index.html");
String malformedPath = absolutePathRoot + "path%25with%25spaces/";
TestPaths(malformedPath, resolver);
}
[NUnit.Framework.Test]
public virtual void UriResolverTest10C() {
String absolutePathRoot = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToExternalForm();
UriResolver resolver = new UriResolver(absolutePathRoot +"path%2525with%2525spaces/test/folder/index.html");
String malformedPath = absolutePathRoot + "path%2525with%2525spaces/";
TestPaths(malformedPath, resolver);
}
[NUnit.Framework.Test]
public virtual void UriResolverTest10D() {
String absolutePathRoot = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToExternalForm();
UriResolver resolver = new UriResolver(absolutePathRoot + "path with spaces/test/folder/index.html");
String malformedPath = absolutePathRoot + "path%20with%20spaces/";
TestPaths(malformedPath, resolver);
}
[NUnit.Framework.Test]
public virtual void UriResolverTest10E() {
String absolutePathRoot = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToExternalForm();
UriResolver resolver = new UriResolver(absolutePathRoot + "path%20with%20spaces/test/folder/index.html");
String malformedPath = absolutePathRoot + "path%20with%20spaces/";
TestPaths(malformedPath, resolver);
}
[NUnit.Framework.Test]
public virtual void UriResolverTest10F() {
String absolutePathRoot = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToExternalForm();
UriResolver resolver = new UriResolver(absolutePathRoot + "path%2520with%2520spaces/test/folder/index.html");
String malformedPath = absolutePathRoot + "path%2520with%2520spaces/";
TestPaths(malformedPath, resolver);
}
[NUnit.Framework.Test]
public virtual void UriResolverTest13() {
UriResolver resolver = new UriResolver("");
String runFolder = new Uri(Path.GetFullPath(Directory.GetCurrentDirectory() + "/")).ToExternalForm();
NUnit.Framework.Assert.AreEqual(runFolder, resolver.GetBaseUri());
NUnit.Framework.Assert.AreEqual(runFolder + "innerTest", resolver.ResolveAgainstBaseUri("innerTest").ToExternalForm
());
String parentToRunFolder = new Uri(Directory.GetParent(Directory.GetCurrentDirectory()).FullName + "/").ToExternalForm();
NUnit.Framework.Assert.AreEqual(parentToRunFolder + "folder2/innerTest2", resolver.ResolveAgainstBaseUri("../folder2/innerTest2"
).ToExternalForm());
// Look to commentary in TestPaths() method
// NUnit.Framework.Assert.AreEqual(runFolder + "folder2/innerTest2", resolver.ResolveAgainstBaseUri("/folder2/innerTest2"
// ).ToExternalForm());
// NUnit.Framework.Assert.AreEqual(runFolder + "folder2/innerTest2", resolver.ResolveAgainstBaseUri("//folder2/innerTest2"
// ).ToExternalForm());
}
[NUnit.Framework.Test]
public virtual void UriResolverTest14() {
UriResolver resolver = new UriResolver("base/uri/index.html");
String runFolder = new Uri(Path.GetFullPath(Directory.GetCurrentDirectory() )).ToExternalForm() + "/";
NUnit.Framework.Assert.AreEqual(runFolder + "base/uri/index.html", resolver.GetBaseUri());
String firstUriResolvingResult = resolver.ResolveAgainstBaseUri("file:/c:/test/folder/img.txt")
.ToExternalForm();
String expectedUriWithSingleSlash = "file:/c:/test/folder/img.txt";
String expectedUriWithTripleSlash = "file:///c:/test/folder/img.txt";
NUnit.Framework.Assert.True(expectedUriWithSingleSlash.Equals(firstUriResolvingResult)
|| expectedUriWithTripleSlash.Equals(firstUriResolvingResult));
NUnit.Framework.Assert.AreEqual("file:///c:/test/folder/img.txt", resolver.ResolveAgainstBaseUri("file://c:/test/folder/img.txt"
).ToExternalForm());
String thirdUriResolvingResult = resolver.ResolveAgainstBaseUri("file:///c:/test/folder/img.txt")
.ToExternalForm();
// Result of resolving uri with triple slash should be the same as if it contained single slash.
NUnit.Framework.Assert.AreEqual(firstUriResolvingResult, thirdUriResolvingResult);
}
// It is windows specific to assume this to work. On unix it shall fail, as it will assume that it is
// an absolute URI with scheme 'c', and will not recognize this scheme.
// Assert.assertEquals("file:/c:/test/folder/data.jpg", resolver.resolveAgainstBaseUri("c:/test/folder/data.jpg").toExternalForm());
[NUnit.Framework.Test]
public virtual void UriResolverTest15() {
String absolutePathRoot = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToString();
String absoluteBaseUri = new Uri(absolutePathRoot + "test/folder/index.html").ToString();
UriResolver resolver = new UriResolver(absoluteBaseUri);
TestPaths(absolutePathRoot, resolver);
}
[NUnit.Framework.Test]
public virtual void UriResolverTest16() {
String absolutePathRoot = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToString();
String absoluteBaseUri = new Uri(absolutePathRoot + "test/folder/index.html").ToString();
UriResolver resolver = new UriResolver(absoluteBaseUri);
String singleSlashRootPath = absolutePathRoot;
TestPaths(singleSlashRootPath, resolver);
}
[NUnit.Framework.Test]
public virtual void UriResolverTest16A() {
String absolutePathRoot = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToString();
UriResolver resolver = new UriResolver(absolutePathRoot + "path/with/spaces/test/folder/index.html");
String uriRoot = absolutePathRoot + "path/with/spaces/";
NUnit.Framework.Assert.AreEqual(uriRoot + "test/folder/innerTest", resolver.ResolveAgainstBaseUri
("innerTest").ToExternalForm());
NUnit.Framework.Assert.AreEqual(uriRoot + "test/folder2/innerTest2", resolver.ResolveAgainstBaseUri
("../folder2/innerTest2").ToExternalForm());
// Look to commentary in TestPaths() method
// NUnit.Framework.Assert.AreEqual(uriRoot + "test/folder/folder2/innerTest2", resolver.ResolveAgainstBaseUri
// ("/folder2/innerTest2").ToExternalForm());
// NUnit.Framework.Assert.AreEqual(uriRoot + "test/folder/folder2/innerTest2", resolver.ResolveAgainstBaseUri
// ("//folder2/innerTest2").ToExternalForm());
}
[NUnit.Framework.Test]
public virtual void UriResolverTest16B() {
String absolutePathRoot = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToString();
UriResolver resolver = new UriResolver(absolutePathRoot + "path%2Fwith%2Fspaces/test/folder/index.html");
String rootFolder = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToExternalForm();
String uriRoot = rootFolder + "path%2Fwith%2Fspaces/";
NUnit.Framework.Assert.AreNotEqual(uriRoot + "test/folder/innerTest", resolver.ResolveAgainstBaseUri
("innerTest").ToExternalForm());
NUnit.Framework.Assert.AreNotEqual(uriRoot + "test/folder2/innerTest2", resolver.ResolveAgainstBaseUri
("../folder2/innerTest2").ToExternalForm());
// Look to commentary in TestPaths() method
// NUnit.Framework.Assert.AreNotEqual(uriRoot + "test/folder/folder2/innerTest2", resolver.ResolveAgainstBaseUri
// ("/folder2/innerTest2").ToExternalForm());
// NUnit.Framework.Assert.AreNotEqual(uriRoot + "test/folder/folder2/innerTest2", resolver.ResolveAgainstBaseUri
// ("//folder2/innerTest2").ToExternalForm());
}
[NUnit.Framework.Test]
public virtual void UriResolverTest16C() {
String absolutePathRoot = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToString();
UriResolver resolver = new UriResolver(absolutePathRoot + "path%2Fwith%2Fspaces/test/folder/index.html");
String rootFolder = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToExternalForm();
String uriRoot = rootFolder + "path%2Fwith%2Fspaces/";
NUnit.Framework.Assert.AreNotEqual(uriRoot + "test/folder/innerTest", resolver.ResolveAgainstBaseUri
("innerTest").ToExternalForm());
NUnit.Framework.Assert.AreNotEqual(uriRoot + "test/folder2/innerTest2", resolver.ResolveAgainstBaseUri
("../folder2/innerTest2").ToExternalForm());
// Look to commentary in TestPaths() method
// NUnit.Framework.Assert.AreNotEqual(uriRoot + "test/folder/folder2/innerTest2", resolver.ResolveAgainstBaseUri
// ("/folder2/innerTest2").ToExternalForm());
// NUnit.Framework.Assert.AreNotEqual(uriRoot + "test/folder/folder2/innerTest2", resolver.ResolveAgainstBaseUri
// ("//folder2/innerTest2").ToExternalForm());
}
[NUnit.Framework.Test]
public virtual void UriResolverTest16D() {
String absolutePathRoot = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToExternalForm();
UriResolver resolver = new UriResolver(absolutePathRoot + "path%25252Fwith%25252Fspaces/test/folder/index.html");
String malformedPath = absolutePathRoot + "path%25252Fwith%25252Fspaces/";
NUnit.Framework.Assert.AreEqual(malformedPath + "test/folder/innerTest", resolver.ResolveAgainstBaseUri
("innerTest").ToExternalForm());
NUnit.Framework.Assert.AreEqual(malformedPath + "test/folder2/innerTest2", resolver.ResolveAgainstBaseUri
("../folder2/innerTest2").ToExternalForm());
// Look to commentary in TestPaths() method
// NUnit.Framework.Assert.AreEqual(malformedPath + "test/folder/folder2/innerTest2", resolver.ResolveAgainstBaseUri
// ("/folder2/innerTest2").ToExternalForm());
// NUnit.Framework.Assert.AreEqual(malformedPath + "test/folder/folder2/innerTest2", resolver.ResolveAgainstBaseUri
// ("//folder2/innerTest2").ToExternalForm());
}
// the whitespace characters are
[NUnit.Framework.Test]
public virtual void UriResolverTest17()
{
String absolutePathRoot = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToString();
String absoluteBaseUri = absolutePathRoot + "test/fol ders/wi@th/diffe#rent/$characters/test/folder/index.html\t\t\t\t\t\t";
UriResolver resolver = new UriResolver(absoluteBaseUri);
String malformedPath = absolutePathRoot + "test/fol%20ders/wi@th/diffe#rent/$characters/";
NUnit.Framework.Assert.AreNotEqual(malformedPath + "test/folder/innerTest", resolver.ResolveAgainstBaseUri
("innerTest").ToExternalForm());
NUnit.Framework.Assert.AreNotEqual(malformedPath + "test/folder2/innerTest2", resolver.ResolveAgainstBaseUri
("../folder2/innerTest2").ToExternalForm());
// Look to commentary in TestPaths() method
// NUnit.Framework.Assert.AreNotEqual(malformedPath + "test/folder/folder2/innerTest2", resolver.ResolveAgainstBaseUri
// ("/folder2/innerTest2").ToExternalForm());
// NUnit.Framework.Assert.AreNotEqual(malformedPath + "test/folder/folder2/innerTest2", resolver.ResolveAgainstBaseUri
// ("//folder2/innerTest2").ToExternalForm());
}
[NUnit.Framework.Test]
public virtual void UriResolverTest18() {
String absolutePathRoot = "http://";
String absoluteBaseUri = absolutePathRoot + "test/fol ders/wi@th/diffe#rent/$characters/index.html\t\t\t\t\t\t";
UriResolver resolver = new UriResolver(absoluteBaseUri);
NUnit.Framework.Assert.IsFalse(resolver.IsLocalBaseUri());
}
[NUnit.Framework.Test]
public void SingleQuoteRelativePath() {
String expectedUrl = "https://he.wikipedia.org/wiki/%D7%90%D7%91%D7%92'%D7%93";
String baseUri = "https://he.wikipedia.org/wiki/";
String relativePath = "%D7%90%D7%91%D7%92'%D7%93";
UriResolver resolver = new UriResolver(baseUri);
NUnit.Framework.Assert.AreEqual(expectedUrl, resolver.ResolveAgainstBaseUri(relativePath).ToExternalForm());
}
[NUnit.Framework.Test]
[NUnit.Framework.Ignore("DEVSIX-2880: single quote character isn't encoded in Java and .NET 4.0, but it's encoded in .NETCoreApp 1.0" +
" from single quote to %27")]
public void quoteInPercentsRelativePath() {
String expectedUrl = "https://he.wikipedia.org/wiki/%D7%90%D7%91%D7%92%27%D7%93";
String baseUri = "https://he.wikipedia.org/wiki/";
String relativePath = "%D7%90%D7%91%D7%92%27%D7%93";
UriResolver resolver = new UriResolver(baseUri);
NUnit.Framework.Assert.AreEqual(expectedUrl, resolver.ResolveAgainstBaseUri(relativePath).ToExternalForm());
}
[NUnit.Framework.Test]
public void singleQuoteBasePath() {
String expectedUrl = "https://he.wikipedia.org/wiki'/%D7%90%D7%91%D7%92%D7%93";
String baseUri = "https://he.wikipedia.org/wiki'/";
String relativePath = "%D7%90%D7%91%D7%92%D7%93";
UriResolver resolver = new UriResolver(baseUri);
NUnit.Framework.Assert.AreEqual(expectedUrl, resolver.ResolveAgainstBaseUri(relativePath).ToExternalForm());
}
[NUnit.Framework.Test]
[NUnit.Framework.Ignore("DEVSIX-2880: single quote character isn't encoded in Java and .NET 4.0, but it's encoded in .NETCoreApp 1.0" +
" from single quote to %27")]
public void quoteInPercentsBasePath() {
String expectedUrl = "https://he.wikipedia.org/wiki%27/%D7%90%D7%91%D7%92%D7%93";
String baseUri = "https://he.wikipedia.org/wiki%27/";
String relativePath = "%D7%90%D7%91%D7%92%D7%93";
UriResolver resolver = new UriResolver(baseUri);
NUnit.Framework.Assert.AreEqual(expectedUrl, resolver.ResolveAgainstBaseUri(relativePath).ToExternalForm());
}
[NUnit.Framework.Test]
public void UriResolverPercentSignTest() {
String absolutePathRoot = new Uri(new Uri("file://"), Path.GetPathRoot(Directory.GetCurrentDirectory())).ToString();
UriResolver resolver = new UriResolver(absolutePathRoot + "%homepath%");
NUnit.Framework.Assert.AreEqual(absolutePathRoot + "%25homepath%25", resolver.GetBaseUri());
}
private void TestPaths(String absolutePathRoot, UriResolver resolver)
{
NUnit.Framework.Assert.AreEqual(absolutePathRoot + "test/folder/index.html", resolver.GetBaseUri());
NUnit.Framework.Assert.AreEqual(absolutePathRoot + "test/folder/innerTest", resolver.ResolveAgainstBaseUri
("innerTest").ToExternalForm());
NUnit.Framework.Assert.AreEqual(absolutePathRoot + "test/folder2/innerTest2", resolver.ResolveAgainstBaseUri
("../folder2/innerTest2").ToExternalForm());
/*
Resolving relative paths like "/folder" works correct on Linux and .NET, but fails on Java because of strong
corresponding with URI standard RFC3986.
Look to this memo for specifying "file" URI scheme:
https://tools.ietf.org/id/draft-ietf-appsawg-file-scheme-12.html
Expected results after resolving "/folder2/innerTest2":
- .NET: "file:///C:/folder2/innerTest2"
- Java (Windows): "file:/folder2/innerTest2" - incorrect
- Java (Linux): "file:/folder2/innerTest2" - correct
*/
// NUnit.Framework.Assert.AreEqual(absolutePathRoot + "test/folder/folder2/innerTest2", resolver.ResolveAgainstBaseUri
// ("/folder2/innerTest2").ToExternalForm());
// NUnit.Framework.Assert.AreEqual(absolutePathRoot + "test/folder/folder2/innerTest2", resolver.ResolveAgainstBaseUri
// ("//folder2/innerTest2").ToExternalForm());
}
}
}

View File

@@ -0,0 +1,77 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using System.Collections.Generic;
using System.Text;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Util {
[NUnit.Framework.Category("UnitTest")]
public class FontFamilySplitterTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void FontFamilySplitter() {
String fontFamilies = "'Puritan'\n" + "Puritan\n" + "'Pur itan'\n" + "Pur itan\n" + "'Pur it an'\n" + "Pur it an\n"
+ " \"Puritan\"\n" + "Puritan\n" + " \"Pur itan\"\n" + "Pur itan\n" + "\"Pur it an\"\n" + "Pur it an\n"
+ "FreeSans\n" + "FreeSans\n" + "'Puritan', FreeSans\n" + "Puritan; FreeSans\n" + "'Pur itan' , FreeSans\n"
+ "Pur itan; FreeSans\n" + " 'Pur it an' , FreeSans \n" + "Pur it an; FreeSans\n" + "\"Puritan\", FreeSans\n"
+ "Puritan; FreeSans\n" + "\"Pur itan\", FreeSans\n" + "Pur itan; FreeSans\n" + "\"Pur it an\", FreeSans\n"
+ "Pur it an; FreeSans\n" + "\"Puritan\"\n" + "Puritan\n" + "'Free Sans',\n" + "Free Sans\n" + "'Free-Sans',\n"
+ "Free-Sans\n" + " 'Free-Sans' , Puritan\n" + "Free-Sans; Puritan\n" + " \"Free-Sans\" , Puritan\n"
+ "Free-Sans; Puritan\n" + " Free-Sans , Puritan\n" + "Free-Sans; Puritan\n" + " Free-Sans\n" + "Free-Sans\n"
+ "\"Puritan\", Free Sans\n" + "Puritan\n" + "\"Puritan 2.0\"\n" + "-\n" + "'Puritan' FreeSans\n" + "-\n"
+ "Pur itan\n" + "-\n" + "Pur it an\"\n" + "-\n" + "\"Free Sans\n" + "-\n" + "Pur it an'\n" + "-\n" +
"'Free Sans\n" + "-";
String[] splitFontFamilies = TSpdf.Commons.Utils.StringUtil.Split(fontFamilies, "\n");
StringBuilder result = new StringBuilder();
for (int i = 0; i < splitFontFamilies.Length; i += 2) {
IList<String> fontFamily = FontFamilySplitterUtil.SplitFontFamily(splitFontFamilies[i]);
result.Length = 0;
foreach (String ff in fontFamily) {
result.Append(ff).Append("; ");
}
NUnit.Framework.Assert.AreEqual(splitFontFamilies[i + 1], result.Length > 2 ? result.JSubstring(0, result.
Length - 2) : "-");
}
}
}
}

View File

@@ -0,0 +1,91 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://TSpdfpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using TSpdf.StyledXmlParser.Css.Resolve;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Util {
[NUnit.Framework.Category("UnitTest")]
public class StyleUtilUnitTest : ExtendedTSpdfTest {
private static ICollection<IStyleInheritance> inheritanceRules;
[NUnit.Framework.OneTimeSetUp]
public static void Before() {
inheritanceRules = new HashSet<IStyleInheritance>();
inheritanceRules.Add(new CssInheritance());
}
[NUnit.Framework.Test]
public virtual void MergeParentDeclarationsMeasurementDoNotInheritTest() {
IDictionary<String, String> styles = new Dictionary<String, String>();
String styleProperty = "font-size";
styles.Put(styleProperty, "12px");
String parentPropValue = "16cm";
String parentFontSize = "0";
IDictionary<String, String> expectedStyles = new Dictionary<String, String>();
expectedStyles.Put(styleProperty, "12px");
styles = StyleUtil.MergeParentStyleDeclaration(styles, styleProperty, parentPropValue, parentFontSize, inheritanceRules
);
bool equal = styles.Count == expectedStyles.Count;
foreach (KeyValuePair<String, String> kvp in expectedStyles) {
equal &= kvp.Value.Equals(styles.Get(kvp.Key));
}
NUnit.Framework.Assert.IsTrue(equal);
}
[NUnit.Framework.Test]
public virtual void MergeParentDeclarationsMeasurementInheritTest() {
IDictionary<String, String> styles = new Dictionary<String, String>();
String styleProperty = "font-size";
String parentPropValue = "16cm";
String parentFontSize = "0";
IDictionary<String, String> expectedStyles = new Dictionary<String, String>();
expectedStyles.Put(styleProperty, parentPropValue);
styles = StyleUtil.MergeParentStyleDeclaration(styles, styleProperty, parentPropValue, parentFontSize, inheritanceRules
);
bool equal = styles.Count == expectedStyles.Count;
foreach (KeyValuePair<String, String> kvp in expectedStyles) {
equal &= kvp.Value.Equals(styles.Get(kvp.Key));
}
NUnit.Framework.Assert.IsTrue(equal);
}
[NUnit.Framework.Test]
public virtual void MergeParentDeclarationsRelativeMeasurementInheritTest() {
IDictionary<String, String> styles = new Dictionary<String, String>();
String styleProperty = "font-size";
String parentPropValue = "80%";
String parentFontSize = "16";
IDictionary<String, String> expectedStyles = new Dictionary<String, String>();
expectedStyles.Put(styleProperty, "9.6pt");
styles = StyleUtil.MergeParentStyleDeclaration(styles, styleProperty, parentPropValue, parentFontSize, inheritanceRules
);
bool equal = styles.Count == expectedStyles.Count;
foreach (KeyValuePair<String, String> kvp in expectedStyles) {
equal &= kvp.Value.Equals(styles.Get(kvp.Key));
}
NUnit.Framework.Assert.IsTrue(equal);
}
}
}

View File

@@ -0,0 +1,97 @@
/*
This file is part of the TSpdf (R) project.
Copyright (c) 1987-2023 TSpdf
Authors: TSpdf Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
TSpdf GROUP. TSpdf GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://TSpdfpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using TSpdf.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the TSpdf software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping TSpdf with a closed
source product.
For more information, please contact TSpdf Software Corp. at this
address: sales@TSpdfpdf.com
*/
using System;
using TSpdf.Test;
namespace TSpdf.StyledXmlParser.Util {
[NUnit.Framework.Category("UnitTest")]
public class WhiteSpaceUtilUnitTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void CollapseConsecutiveWhiteSpacesTest() {
String toCollapse = "A B";
String actual = WhiteSpaceUtil.CollapseConsecutiveSpaces(toCollapse);
String expected = "A B";
NUnit.Framework.Assert.AreEqual(expected, actual);
}
[NUnit.Framework.Test]
public virtual void CollapseConsecutiveWhiteSpacesTrailingWhiteSpaceTest() {
String toCollapse = "A B ";
String actual = WhiteSpaceUtil.CollapseConsecutiveSpaces(toCollapse);
String expected = "A B ";
NUnit.Framework.Assert.AreEqual(expected, actual);
}
[NUnit.Framework.Test]
public virtual void CollapseConsecutiveWhiteSpacesPrecedingWhiteSpaceTest() {
String toCollapse = " A B";
String actual = WhiteSpaceUtil.CollapseConsecutiveSpaces(toCollapse);
String expected = " A B";
NUnit.Framework.Assert.AreEqual(expected, actual);
}
[NUnit.Framework.Test]
public virtual void CollapseConsecutiveWhiteSpacesPrecedingAndTrailingWhiteSpaceTest() {
String toCollapse = " A B ";
String actual = WhiteSpaceUtil.CollapseConsecutiveSpaces(toCollapse);
String expected = " A B ";
NUnit.Framework.Assert.AreEqual(expected, actual);
}
[NUnit.Framework.Test]
public virtual void CollapseConsecutiveWhiteSpacesNewLineWhiteSpaceTest() {
String toCollapse = "\n A B \n";
String actual = WhiteSpaceUtil.CollapseConsecutiveSpaces(toCollapse);
String expected = " A B ";
NUnit.Framework.Assert.AreEqual(expected, actual);
}
[NUnit.Framework.Test]
public virtual void CollapseConsecutiveWhiteSpacesTabWhiteSpaceTest() {
String toCollapse = "\t A B \t";
String actual = WhiteSpaceUtil.CollapseConsecutiveSpaces(toCollapse);
String expected = " A B ";
NUnit.Framework.Assert.AreEqual(expected, actual);
}
}
}

View File

@@ -0,0 +1,30 @@
@font-face {
src:
url('web-fonts/droid-serif-invalid.ttf') format('truetype'),
url('web-fonts/droid-serif-invalid.ttf') format('opentype'),
url('web-fonts/droid-serif-invalid.ttf') format('opentype'),
url("web-fonts/droid-serif-invalid.ttf") format('opentype'),
url("web-fonts/droid-serif-invalid.ttf") format('opentype'),
url("web-fonts/droid-serif-invalid.ttf") format(opentype),
url(web-fonts/droid-serif-invalid.ttf) format('opentype'),
url("web-fonts/droid-serif-invalid.ttc#1") format(opentype),
url('web-fonts/droid-serif-invalid.ttc#1') format(opentype),
url(web-fonts/droid-serif-invalid.ttc#1) format('opentype'),
url("web-fonts/droid-serif-invalid.svg#id1") format(svg),
url('web-fonts/droid-serif-invalid.svg#id1') format(svg),
url(web-fonts/droid-serif-invalid.svg#id1) format('svg'),
url("web-fonts/droid-serif-invalid.ttc#1"),
url('web-fonts/droid-serif-invalid.ttc#1'),
url(web-fonts/droid-serif-invalid.ttc#1),
url("web-fonts/droid-serif-invalid.svg#id1"),
url('web-fonts/droid-serif-invalid.svg#id1'),
url(web-fonts/droid-serif-invalid.svg#id1),
local("web-fonts/droid-serif-invalid.ttf") format('opentype'),
local("web-fonts/droid-serif-invalid.ttf") format('opentype'),
local("web-fonts/droid-serif-invalid.ttf") format(opentype),
local(web-fonts/droid-serif-invalid.ttf) format(opentype),
local(web-fonts/droid-serif-invalid.ttf) format('opentype'),
local(web-fonts/droid-serif-invalid.ttf),
local('web-fonts/droid-serif-invalid.ttf'),
local("web-fonts/droid-serif-invalid.ttf");
}

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More