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,33 @@
/*
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.Commons.Utils.Collections {
public class EmptySetTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void RemoveValueFromEmptySetTest() {
EmptySet<string> emptySet = new EmptySet<string>();
NUnit.Framework.Assert.False(emptySet.Remove("any value"));
}
}
}

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 TSpdf.Test;
using NUnit.Framework;
namespace TSpdf.Commons.Utils {
public class DateTimeUtilTest : ExtendedTSpdfTest {
private const double ZERO_DELTA = 1e-6;
private const double ONE_SECOND_DELTA = 1000.0;
[Test]
public virtual void GetCurrentTest() {
DateTime date = DateTime.Now;
Assert.AreEqual(date.ToString(), DateTimeUtil.GetCurrentTime().ToString());
}
[Test]
public virtual void IsInPastTest() {
DateTime date = new DateTime(1);
Assert.IsTrue(DateTimeUtil.IsInPast(date));
}
[Test]
public void ParseDateAndGetUtcMillisFromEpochTest()
{
DateTime date = DateTimeUtil.ParseWithDefaultPattern("2020-05-05");
DateTime parsedDate = DateTimeUtil.GetCalendar(date);
double millisFromEpochTo2020_05_05 = DateTimeUtil.GetUtcMillisFromEpoch(parsedDate);
long offset = DateTimeUtil.GetCurrentTimeZoneOffset(date);
Assert.AreEqual(1588636800000d - offset, millisFromEpochTo2020_05_05, ZERO_DELTA);
}
[Test]
public void CompareUtcMillisFromEpochWithNullParamAndCurrentTimeTest() {
double getUtcMillisFromEpochWithNullParam = DateTimeUtil.GetUtcMillisFromEpoch(null);
double millisFromEpochToCurrentTime = DateTimeUtil.GetUtcMillisFromEpoch(DateTimeUtil.GetCurrentUtcTime());
Assert.AreEqual(millisFromEpochToCurrentTime, getUtcMillisFromEpochWithNullParam, ONE_SECOND_DELTA);
}
[Test]
public void ParseDateAndGetRelativeTimeTest()
{
DateTime date = DateTimeUtil.ParseWithDefaultPattern("2020-05-05");
long relativeTime = DateTimeUtil.GetRelativeTime(date);
long offset = DateTimeUtil.GetCurrentTimeZoneOffset(date);
Assert.AreEqual(1588636800000d - offset, relativeTime, ZERO_DELTA);
}
}
}

View File

@@ -0,0 +1,232 @@
/*
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.Globalization;
using System.IO;
using System.Threading;
using TSpdf.Test;
namespace TSpdf.Commons.Utils
{
public class FormattingStreamWriterUnitTest : ExtendedTSpdfTest {
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CultureInfo culture = (CultureInfo) new System.Globalization.CultureInfo("ru-RU");
culture.NumberFormat.NegativeSign = "--";
Thread.CurrentThread.CurrentCulture = culture;
}
[NUnit.Framework.Test]
public virtual void BooleanTest() {
Boolean value = true;
Stream stream = new MemoryStream();
FormattingStreamWriter writer = new FormattingStreamWriter(stream);
writer.Write(value);
writer.Flush();
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
NUnit.Framework.Assert.AreEqual("True", result);
}
[NUnit.Framework.Test]
public virtual void PositiveDoubleTest() {
Double value = 123.579;
Stream stream = new MemoryStream();
FormattingStreamWriter writer = new FormattingStreamWriter(stream);
writer.Write(value);
writer.Flush();
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
NUnit.Framework.Assert.AreEqual("123.579", result);
}
[NUnit.Framework.Test]
public virtual void NegativeDoubleTest() {
Double value = -123.579;
Stream stream = new MemoryStream();
FormattingStreamWriter writer = new FormattingStreamWriter(stream);
writer.Write(value);
writer.Flush();
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
NUnit.Framework.Assert.AreEqual("-123.579", result);
}
[NUnit.Framework.Test]
public virtual void PositiveSingleTest() {
Single value = 123.5f;
Stream stream = new MemoryStream();
FormattingStreamWriter writer = new FormattingStreamWriter(stream);
writer.Write(value);
writer.Flush();
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
NUnit.Framework.Assert.AreEqual("123.5", result);
}
[NUnit.Framework.Test]
public virtual void NegativeSingleTest() {
Single value = -123.5f;
Stream stream = new MemoryStream();
FormattingStreamWriter writer = new FormattingStreamWriter(stream);
writer.Write(value);
writer.Flush();
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
String result = reader.ReadToEnd();
NUnit.Framework.Assert.AreEqual("-123.5", result);
}
[NUnit.Framework.Test]
public virtual void PositiveDecimalTest() {
decimal value = 2478;
Stream stream = new MemoryStream();
FormattingStreamWriter writer = new FormattingStreamWriter(stream);
writer.Write(value);
writer.Flush();
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
String result = reader.ReadToEnd();
NUnit.Framework.Assert.AreEqual("2478", result);
}
[NUnit.Framework.Test]
public virtual void NegativeDecimalTest() {
decimal value = -2478;
Stream stream = new MemoryStream();
FormattingStreamWriter writer = new FormattingStreamWriter(stream);
writer.Write(value);
writer.Flush();
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
String result = reader.ReadToEnd();
NUnit.Framework.Assert.AreEqual("-2478", result);
}
[NUnit.Framework.Test]
public virtual void PositiveInt32Test() {
Int32 value = 2478;
Stream stream = new MemoryStream();
FormattingStreamWriter writer = new FormattingStreamWriter(stream);
writer.Write(value);
writer.Flush();
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
String result = reader.ReadToEnd();
NUnit.Framework.Assert.AreEqual("2478", result);
}
[NUnit.Framework.Test]
public virtual void NegativeInt32Test() {
Int32 value = -2478;
Stream stream = new MemoryStream();
FormattingStreamWriter writer = new FormattingStreamWriter(stream);
writer.Write(value);
writer.Flush();
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
String result = reader.ReadToEnd();
NUnit.Framework.Assert.AreEqual("-2478", result);
}
[NUnit.Framework.Test]
public virtual void PositiveInt64Test() {
Int64 value = 2478;
Stream stream = new MemoryStream();
FormattingStreamWriter writer = new FormattingStreamWriter(stream);
writer.Write(value);
writer.Flush();
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
String result = reader.ReadToEnd();
NUnit.Framework.Assert.AreEqual("2478", result);
}
[NUnit.Framework.Test]
public virtual void NegativeInt64Test() {
Int64 value = -2478;
Stream stream = new MemoryStream();
FormattingStreamWriter writer = new FormattingStreamWriter(stream);
writer.Write(value);
writer.Flush();
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
String result = reader.ReadToEnd();
NUnit.Framework.Assert.AreEqual("-2478", result);
}
[NUnit.Framework.Test]
public virtual void UInt32Test() {
UInt32 value = 2478;
Stream stream = new MemoryStream();
FormattingStreamWriter writer = new FormattingStreamWriter(stream);
writer.Write(value);
writer.Flush();
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
String result = reader.ReadToEnd();
NUnit.Framework.Assert.AreEqual("2478", result);
}
}
}

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 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.Linq;
using NUnit.Framework;
namespace TSpdf.Commons.Utils {
public class JavaUtilTest {
[Test]
public virtual void LinkedHashSetTest() {
LinkedHashSet<int> set1 = new LinkedHashSet<int>();
set1.Add(5);
set1.Add(2);
set1.Add(3);
set1.Add(5);
Assert.AreEqual(5, set1.First());
Assert.AreEqual(3, set1.Last());
Assert.AreEqual(3, set1.Count);
LinkedHashSet<int> set2 = new LinkedHashSet<int>();
set2.Add(2);
set2.Add(5);
Assert.True(set1.IsSupersetOf(set2));
Assert.True(set1.IsProperSupersetOf(set2));
Assert.True(set2.IsSubsetOf(set1));
Assert.True(set2.IsProperSubsetOf(set1));
Assert.False(set2.IsSupersetOf(set1));
LinkedHashSet<int> set3 = new LinkedHashSet<int>();
set3.Add(5);
set3.Add(2);
Assert.True(set3.SetEquals(set2));
}
[Test]
public virtual void JavaCollectionsUtilTest() {
IList<int> emptyList = JavaCollectionsUtil.EmptyList<int>();
Assert.IsEmpty(emptyList);
Assert.Throws<NotSupportedException>(() => emptyList.Add(10));
IDictionary<int, int> emptyMap = JavaCollectionsUtil.EmptyMap<int, int>();
Assert.IsEmpty(emptyMap);
Assert.Throws<NotSupportedException>(() => { emptyMap[5] = 10; });
IEnumerator<int> emptyIterator = JavaCollectionsUtil.EmptyIterator<int>();
Assert.False(emptyIterator.MoveNext());
IList<int> unmodifiableList =
JavaCollectionsUtil.UnmodifiableList<int>(new int[] {10, 20, 30, 20}.ToList());
Assert.Throws<NotSupportedException>(() => unmodifiableList.Insert(0, 20));
Assert.Throws<NotSupportedException>(() => { unmodifiableList[2] = 50; });
int test = unmodifiableList[3];
Assert.Throws<NotSupportedException>(() => JavaCollectionsUtil.Sort(unmodifiableList));
IDictionary<int, int> unodifiableMap = JavaCollectionsUtil.UnmodifiableMap(new Dictionary<int, int>() {
{1, 20},
{2, 40},
{70, 80},
});
test = unodifiableMap[2];
Assert.Throws<KeyNotFoundException>(() => {
int temp = unodifiableMap[3];
});
Assert.Throws<NotSupportedException>(() => { unodifiableMap[11] = 11; });
IList<int> singletonList = JavaCollectionsUtil.SingletonList(4);
Assert.AreEqual(4, singletonList[0]);
Assert.Throws<NotSupportedException>(() => singletonList.Add(9));
List<int> x = new int[] {60, 50, 20}.ToList();
JavaCollectionsUtil.Sort(x);
Assert.AreEqual(20, x[0]);
Assert.AreEqual(60, x[2]);
x = new int[] {-1, 0, 1}.ToList();
JavaCollectionsUtil.Reverse(x);
Assert.AreEqual(1, x[0]);
Assert.AreEqual(0, x[1]);
}
[Test]
public virtual void JavaUtilFillBytesTest() {
byte[] bytes = new byte[5];
byte fillVal = 1;
JavaUtil.Fill(bytes, fillVal);
foreach (byte b in bytes) {
Assert.AreEqual(fillVal, b);
}
}
[Test]
public virtual void JavaUtilFillCharsTest() {
char[] chars = new char[5];
char fillVal = 'a';
JavaUtil.Fill(chars, fillVal);
foreach (char c in chars) {
Assert.AreEqual(fillVal, c);
}
}
[Test]
public virtual void JavaUtilFillBoolTest() {
bool[] bools = new bool[5];
bool fillVal = true;
JavaUtil.Fill(bools, fillVal);
foreach (bool b in bools) {
Assert.AreEqual(fillVal, b);
}
}
[Test]
public virtual void JavaUtilFillShortTest() {
short[] shorts = new short[5];
short fillVal = 1;
JavaUtil.Fill(shorts, fillVal);
foreach (short b in shorts) {
Assert.AreEqual(fillVal, b);
}
}
[Test]
public virtual void JavaUtilFillIntTest() {
int[] ints = new int[5];
int fillVal = 1;
JavaUtil.Fill(ints, fillVal);
foreach (int b in ints) {
Assert.AreEqual(fillVal, b);
}
}
[Test]
public virtual void JavaUtilFillLongTest() {
long[] longs = new long[5];
long fillVal = 1;
JavaUtil.Fill(longs, fillVal);
foreach (long b in longs) {
Assert.AreEqual(fillVal, b);
}
}
[Test]
public virtual void JavaUtilFillFloatTest() {
float[] floats = new float[5];
float fillVal = 1;
JavaUtil.Fill(floats, fillVal);
foreach (float b in floats) {
Assert.AreEqual(fillVal, b);
}
}
[Test]
public virtual void JavaUtilFillDoubleTest() {
double[] doubles = new double[5];
double fillVal = 1;
JavaUtil.Fill(doubles, fillVal);
foreach (double d in doubles) {
Assert.AreEqual(fillVal, d);
}
}
[Test]
public virtual void JavaUtilFillObjectTest() {
string[] strings = new string[5];
string fillVal = "hello";
JavaUtil.Fill(strings, fillVal);
foreach (string s in strings) {
Assert.AreEqual(fillVal, s);
}
}
}
}

View File

@@ -0,0 +1,576 @@
/*
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.Commons.Logs;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Commons.Utils {
[NUnit.Framework.Category("UnitTest")]
public class JsonUtilTest : ExtendedTSpdfTest {
private static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/commons/utils/JsonUtilTest/";
private static bool isRunOnJava = false;
static JsonUtilTest() {
// Android-Conversion-Skip-Block-Start (cutting area is used to understand whether code is running on Android or not)
isRunOnJava = true;
}
// Android-Conversion-Skip-Block-End
[NUnit.Framework.Test]
public virtual void Utf8CharsetStringTest() {
NUnit.Framework.Assert.AreEqual("\"©\"", JsonUtil.SerializeToString("©"));
}
[NUnit.Framework.Test]
public virtual void Utf8CharsetStreamTest() {
MemoryStream byteArray = new MemoryStream();
JsonUtil.SerializeToStream(byteArray, "©");
NUnit.Framework.Assert.AreEqual("\"©\"", EncodingUtil.ConvertToString(byteArray.ToArray(), "UTF-8"));
}
[NUnit.Framework.Test]
public virtual void SerializeInstanceWithEnumStringTest() {
String cmp = SOURCE_FOLDER + "classWithEnum.json";
JsonUtilTest.ClassWithEnum classWithEnum = CreateClassWithEnumObject();
String resultString = JsonUtil.SerializeToString(classWithEnum);
String cmpString = GetJsonStringFromFile(cmp);
NUnit.Framework.Assert.IsTrue(JsonUtil.AreTwoJsonObjectEquals(cmpString, resultString));
}
[NUnit.Framework.Test]
public virtual void SerializeInstanceWithEnumStreamTest() {
// Android-Conversion-Ignore-Test (TODO DEVSIX-7371 investigate different behavior of a few TSpdfCore tests on Java and Android)
String cmp;
if (isRunOnJava) {
cmp = SOURCE_FOLDER + "classWithEnum.json";
}
else {
// Test is run on Android, so field order will be different from Java.
cmp = SOURCE_FOLDER + "classWithEnumAndroid.json";
}
using (Stream inputStream = FileUtil.GetInputStreamForFile(cmp)) {
using (MemoryStream baos = ConvertInputStreamToOutput(inputStream)) {
using (MemoryStream serializationResult = new MemoryStream()) {
JsonUtil.SerializeToStream(serializationResult, CreateClassWithEnumObject());
serializationResult.Flush();
NUnit.Framework.Assert.AreEqual(baos.ToArray(), serializationResult.ToArray());
}
}
}
}
[NUnit.Framework.Test]
public virtual void SerializeToMinimalInstanceWithEnumStringTest() {
String cmp = SOURCE_FOLDER + "minimalClassWithEnum.json";
JsonUtilTest.ClassWithEnum classWithEnum = CreateClassWithEnumObject();
String resultString = JsonUtil.SerializeToMinimalString(classWithEnum);
String compareString = GetJsonStringFromFile(cmp);
NUnit.Framework.Assert.IsTrue(JsonUtil.AreTwoJsonObjectEquals(compareString, resultString));
}
[NUnit.Framework.Test]
public virtual void SerializeToMinimalInstanceWithEnumStreamTest() {
// Android-Conversion-Ignore-Test (TODO DEVSIX-7371 investigate different behavior of a few TSpdfCore tests on Java and Android)
String cmp;
if (isRunOnJava) {
cmp = SOURCE_FOLDER + "minimalClassWithEnum.json";
}
else {
// Test is run on Android, so field order will be different from Java.
cmp = SOURCE_FOLDER + "minimalClassWithEnumAndroid.json";
}
using (Stream inputStream = FileUtil.GetInputStreamForFile(cmp)) {
using (MemoryStream baos = ConvertInputStreamToOutput(inputStream)) {
using (MemoryStream serializationResult = new MemoryStream()) {
JsonUtil.SerializeToMinimalStream(serializationResult, CreateClassWithEnumObject());
serializationResult.Flush();
NUnit.Framework.Assert.AreEqual(baos.ToArray(), serializationResult.ToArray());
}
}
}
}
[NUnit.Framework.Test]
public virtual void SerializeStringWithLineBreakStringTest() {
String cmp = SOURCE_FOLDER + "stringsWithLineBreaks.json";
String[] stringsForSerialization = CreateStringWithLineBreaks();
String resultString = JsonUtil.SerializeToString(stringsForSerialization);
String cmpString = GetJsonStringFromFile(cmp);
NUnit.Framework.Assert.AreEqual(cmpString, resultString);
}
[NUnit.Framework.Test]
public virtual void SerializeStringWithLineBreakStreamTest() {
String path = SOURCE_FOLDER + "stringsWithLineBreaks.json";
using (Stream inputStream = FileUtil.GetInputStreamForFile(path)) {
using (MemoryStream baos = ConvertInputStreamToOutput(inputStream)) {
using (MemoryStream serializationResult = new MemoryStream()) {
JsonUtil.SerializeToStream(serializationResult, CreateStringWithLineBreaks());
NUnit.Framework.Assert.AreEqual(baos.ToArray(), serializationResult.ToArray());
}
}
}
}
[NUnit.Framework.Test]
public virtual void SerializeToMinimalStringWithLineBreakStringTest() {
String cmp = SOURCE_FOLDER + "minimalStringsWithLineBreaks.json";
String[] stringsForSerialization = CreateStringWithLineBreaks();
String resultString = JsonUtil.SerializeToMinimalString(stringsForSerialization);
String cmpString = GetJsonStringFromFile(cmp);
NUnit.Framework.Assert.AreEqual(cmpString, resultString);
}
[NUnit.Framework.Test]
public virtual void SerializeToMinimalStringWithLineBreakStreamTest() {
String path = SOURCE_FOLDER + "minimalStringsWithLineBreaks.json";
using (Stream inputStream = FileUtil.GetInputStreamForFile(path)) {
using (MemoryStream baos = ConvertInputStreamToOutput(inputStream)) {
using (MemoryStream serializationResult = new MemoryStream()) {
JsonUtil.SerializeToMinimalStream(serializationResult, CreateStringWithLineBreaks());
NUnit.Framework.Assert.AreEqual(baos.ToArray(), serializationResult.ToArray());
}
}
}
}
[NUnit.Framework.Test]
public virtual void SerializeComplexStructureStringTest() {
String cmp = SOURCE_FOLDER + "complexStructure.json";
JsonUtilTest.ComplexStructure complexStructure = CreateComplexStructureObject();
String resultString = JsonUtil.SerializeToString(complexStructure);
String compareString = GetJsonStringFromFile(cmp);
NUnit.Framework.Assert.IsTrue(JsonUtil.AreTwoJsonObjectEquals(compareString, resultString));
}
[NUnit.Framework.Test]
public virtual void SerializeComplexStructureStreamTest() {
// Android-Conversion-Ignore-Test (TODO DEVSIX-7371 investigate different behavior of a few TSpdfCore tests on Java and Android)
String cmp;
if (isRunOnJava) {
cmp = SOURCE_FOLDER + "complexStructure.json";
}
else {
// Test is run on Android, so field order will be different from Java.
cmp = SOURCE_FOLDER + "complexStructureAndroid.json";
}
using (Stream inputStream = FileUtil.GetInputStreamForFile(cmp)) {
using (MemoryStream baos = ConvertInputStreamToOutput(inputStream)) {
using (MemoryStream serializationResult = new MemoryStream()) {
JsonUtil.SerializeToStream(serializationResult, CreateComplexStructureObject());
NUnit.Framework.Assert.AreNotEqual(0, serializationResult.Length);
NUnit.Framework.Assert.AreEqual(baos.ToArray(), serializationResult.ToArray());
}
}
}
}
[NUnit.Framework.Test]
public virtual void SerializeToMinimalComplexStructureStringTest() {
String cmp = SOURCE_FOLDER + "minimalComplexStructure.json";
JsonUtilTest.ComplexStructure complexStructure = CreateComplexStructureObject();
String resultString = JsonUtil.SerializeToMinimalString(complexStructure);
String compareString = GetJsonStringFromFile(cmp);
NUnit.Framework.Assert.IsTrue(JsonUtil.AreTwoJsonObjectEquals(compareString, resultString));
}
[NUnit.Framework.Test]
public virtual void SerializeToMinimalComplexStructureStreamTest() {
// Android-Conversion-Ignore-Test (TODO DEVSIX-7371 investigate different behavior of a few TSpdfCore tests on Java and Android)
String cmp;
if (isRunOnJava) {
cmp = SOURCE_FOLDER + "minimalComplexStructure.json";
}
else {
// Test is run on Android, so field order will be different from Java.
cmp = SOURCE_FOLDER + "minimalComplexStructureAndroid.json";
}
using (Stream inputStream = FileUtil.GetInputStreamForFile(cmp)) {
using (MemoryStream baos = ConvertInputStreamToOutput(inputStream)) {
using (MemoryStream serializationResult = new MemoryStream()) {
JsonUtil.SerializeToMinimalStream(serializationResult, CreateComplexStructureObject());
NUnit.Framework.Assert.AreNotEqual(0, serializationResult.Length);
NUnit.Framework.Assert.AreEqual(baos.ToArray(), serializationResult.ToArray());
}
}
}
}
[NUnit.Framework.Test]
public virtual void SerializeWithNullFieldsStringTest() {
String cmp = SOURCE_FOLDER + "serializeWithNullFields.json";
JsonUtilTest.ClassWithDefaultValue complexStructure = CreateClassWithDefaultValueObject(null, 4, null);
String resultString = JsonUtil.SerializeToString(complexStructure);
String compareString = GetJsonStringFromFile(cmp);
NUnit.Framework.Assert.IsTrue(JsonUtil.AreTwoJsonObjectEquals(compareString, resultString));
}
[NUnit.Framework.Test]
public virtual void SerializeWithNullFieldsStreamTest() {
String path = SOURCE_FOLDER + "serializeWithNullFields.json";
using (Stream inputStream = FileUtil.GetInputStreamForFile(path)) {
using (MemoryStream baos = ConvertInputStreamToOutput(inputStream)) {
using (MemoryStream serializationResult = new MemoryStream()) {
JsonUtil.SerializeToStream(serializationResult, CreateClassWithDefaultValueObject(null, 4, null));
NUnit.Framework.Assert.AreEqual(baos.ToArray(), serializationResult.ToArray());
}
}
}
}
[NUnit.Framework.Test]
public virtual void SerializeToMinimalWithNullFieldsStringTest() {
String cmp = SOURCE_FOLDER + "minimalSerializeWithNullFields.json";
JsonUtilTest.ClassWithDefaultValue complexStructure = CreateClassWithDefaultValueObject(null, 4, null);
String resultString = JsonUtil.SerializeToMinimalString(complexStructure);
String compareString = GetJsonStringFromFile(cmp);
NUnit.Framework.Assert.IsTrue(JsonUtil.AreTwoJsonObjectEquals(compareString, resultString));
}
[NUnit.Framework.Test]
public virtual void SerializeToMinimalWithNullFieldsStreamTest() {
String path = SOURCE_FOLDER + "minimalSerializeWithNullFields.json";
using (Stream inputStream = FileUtil.GetInputStreamForFile(path)) {
using (MemoryStream baos = ConvertInputStreamToOutput(inputStream)) {
using (MemoryStream serializationResult = new MemoryStream()) {
JsonUtil.SerializeToMinimalStream(serializationResult, CreateClassWithDefaultValueObject(null, 4, null));
NUnit.Framework.Assert.AreEqual(baos.ToArray(), serializationResult.ToArray());
}
}
}
}
[NUnit.Framework.Test]
[LogMessage(CommonsLogMessageConstant.UNABLE_TO_DESERIALIZE_JSON, LogLevel = LogLevelConstants.WARN)]
public virtual void DeserializeInvalidJsonFileStringTest() {
String source = SOURCE_FOLDER + "invalidJson.json";
String jsonString = GetJsonStringFromFile(source);
String resultStr = JsonUtil.DeserializeFromString<String>(jsonString);
NUnit.Framework.Assert.IsNull(resultStr);
}
[NUnit.Framework.Test]
[LogMessage(CommonsLogMessageConstant.UNABLE_TO_DESERIALIZE_JSON, LogLevel = LogLevelConstants.WARN)]
public virtual void DeserializeInvalidJsonFileStreamTest() {
String source = SOURCE_FOLDER + "invalidJson.json";
using (Stream inputStream = FileUtil.GetInputStreamForFile(source)) {
String resultStr = JsonUtil.DeserializeFromStream<String>(inputStream);
NUnit.Framework.Assert.IsNull(resultStr);
}
}
[NUnit.Framework.Test]
public virtual void DeserializeWithDefaultValueStringTest() {
String source = SOURCE_FOLDER + "classWithDefaultValue.json";
String jsonString = GetJsonStringFromFile(source);
JsonUtilTest.ClassWithDefaultValue instance = JsonUtil.DeserializeFromString<JsonUtilTest.ClassWithDefaultValue
>(jsonString);
NUnit.Framework.Assert.AreEqual(CreateClassWithDefaultValueObject(null, 2, 5.0), instance);
}
[NUnit.Framework.Test]
public virtual void DeserializeWithDefaultValueStreamTest() {
String source = SOURCE_FOLDER + "classWithDefaultValue.json";
using (Stream inputStream = FileUtil.GetInputStreamForFile(source)) {
JsonUtilTest.ClassWithDefaultValue instance = JsonUtil.DeserializeFromStream<JsonUtilTest.ClassWithDefaultValue
>(inputStream);
NUnit.Framework.Assert.AreEqual(CreateClassWithDefaultValueObject(null, 2, 5.0), instance);
}
}
[NUnit.Framework.Test]
public virtual void DeserializeComplexStructureStringTest() {
String source = SOURCE_FOLDER + "complexStructure.json";
String jsonString = GetJsonStringFromFile(source);
JsonUtilTest.ComplexStructure complexStructure = JsonUtil.DeserializeFromString<JsonUtilTest.ComplexStructure
>(jsonString);
NUnit.Framework.Assert.AreEqual(CreateComplexStructureObject(), complexStructure);
}
[NUnit.Framework.Test]
public virtual void DeserializeComplexStructureStreamTest() {
String source = SOURCE_FOLDER + "complexStructure.json";
using (Stream inputStream = FileUtil.GetInputStreamForFile(source)) {
JsonUtilTest.ComplexStructure complexStructure = JsonUtil.DeserializeFromStream<JsonUtilTest.ComplexStructure
>(inputStream);
NUnit.Framework.Assert.AreEqual(CreateComplexStructureObject(), complexStructure);
}
}
[NUnit.Framework.Test]
public virtual void DeserializeInstanceWithEnumStringTest() {
String source = SOURCE_FOLDER + "classWithEnum.json";
String jsonString = GetJsonStringFromFile(source);
JsonUtilTest.ClassWithEnum classWithEnum = JsonUtil.DeserializeFromString<JsonUtilTest.ClassWithEnum>(jsonString
);
NUnit.Framework.Assert.AreEqual(CreateClassWithEnumObject(), classWithEnum);
}
[NUnit.Framework.Test]
public virtual void DeserializeInstanceWithEnumStreamTest() {
String source = SOURCE_FOLDER + "classWithEnum.json";
using (Stream inputStream = FileUtil.GetInputStreamForFile(source)) {
JsonUtilTest.ClassWithEnum classWithEnum = JsonUtil.DeserializeFromStream<JsonUtilTest.ClassWithEnum>(inputStream
);
NUnit.Framework.Assert.AreEqual(CreateClassWithEnumObject(), classWithEnum);
}
}
[NUnit.Framework.Test]
public virtual void DeserializeWithUnknownPropertiesStringTest() {
String source = SOURCE_FOLDER + "classWithUnknownProperties.json";
String jsonString = GetJsonStringFromFile(source);
JsonUtilTest.ClassWithDefaultValue instance = JsonUtil.DeserializeFromString<JsonUtilTest.ClassWithDefaultValue
>(jsonString);
NUnit.Framework.Assert.AreEqual(CreateClassWithDefaultValueObject("some small string", 8, 26.0), instance);
}
[NUnit.Framework.Test]
public virtual void DeserializeWithUnknownPropertiesStreamTest() {
String source = SOURCE_FOLDER + "classWithUnknownProperties.json";
using (Stream inputStream = FileUtil.GetInputStreamForFile(source)) {
JsonUtilTest.ClassWithDefaultValue instance = JsonUtil.DeserializeFromStream<JsonUtilTest.ClassWithDefaultValue
>(inputStream);
NUnit.Framework.Assert.IsNotNull(instance);
NUnit.Framework.Assert.AreEqual(CreateClassWithDefaultValueObject("some small string", 8, 26.0), instance);
}
}
[NUnit.Framework.Test]
public virtual void DeserializeWithDefaultValueTypeReferenceStreamTest() {
String source = SOURCE_FOLDER + "classWithDefaultValue.json";
using (Stream inputStream = FileUtil.GetInputStreamForFile(source)) {
JsonUtilTest.ClassWithDefaultValue instance = JsonUtil.DeserializeFromStream<JsonUtilTest.ClassWithDefaultValue
>(inputStream);
NUnit.Framework.Assert.AreEqual(CreateClassWithDefaultValueObject(null, 2, 5.0), instance);
}
}
[NUnit.Framework.Test]
public virtual void DeserializeWithDefaultValueTypeReferenceStringTest() {
String source = SOURCE_FOLDER + "classWithDefaultValue.json";
String jsonString = GetJsonStringFromFile(source);
JsonUtilTest.ClassWithDefaultValue instance = JsonUtil.DeserializeFromString<JsonUtilTest.ClassWithDefaultValue
>(jsonString);
NUnit.Framework.Assert.AreEqual(CreateClassWithDefaultValueObject(null, 2, 5.0), instance);
}
private String GetJsonStringFromFile(String pathToFile) {
byte[] fileBytes = File.ReadAllBytes(System.IO.Path.Combine(pathToFile));
// Use String(byte[]) because there is autoporting for this
// construction by sharpen by call JavaUtil#GetStringForBytes
return TSpdf.Commons.Utils.JavaUtil.GetStringForBytes(fileBytes, System.Text.Encoding.UTF8);
}
private static MemoryStream ConvertInputStreamToOutput(Stream inputStream) {
MemoryStream result = new MemoryStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.Read(buffer)) != -1) {
result.Write(buffer, 0, length);
}
result.Flush();
return result;
}
private static JsonUtilTest.ComplexStructure CreateComplexStructureObject() {
JsonUtilTest.ComplexStructure complexStructure = new JsonUtilTest.ComplexStructure();
complexStructure.map.Put("FirstMapKey", 15);
complexStructure.map.Put("SecondMapKey", 8);
complexStructure.str = "StringFieldValue";
JsonUtilTest.ChildInComplexStructure child = new JsonUtilTest.ChildInComplexStructure();
child.arrayStr = new String[] { "someStr1", "someStr2" };
JsonUtilTest.GrandsonComplexStructure grandson = new JsonUtilTest.GrandsonComplexStructure();
grandson.integer = 13;
grandson.name = "someName";
child.grandsons = new JsonUtilTest.GrandsonComplexStructure[] { grandson, new JsonUtilTest.GrandsonComplexStructure
() };
complexStructure.childsMap.Put("ChildMapkey", child);
complexStructure.childsMap.Put("ChildMapKey2", new JsonUtilTest.ChildInComplexStructure());
return complexStructure;
}
private static JsonUtilTest.ClassWithDefaultValue CreateClassWithDefaultValueObject(String firstString, int
value, double? doubleValue) {
return new JsonUtilTest.ClassWithDefaultValue(firstString, value, doubleValue);
}
private static JsonUtilTest.ClassWithEnum CreateClassWithEnumObject() {
JsonUtilTest.ClassWithEnum classWithEnum = new JsonUtilTest.ClassWithEnum();
classWithEnum.enumArray = new JsonUtilTest.SomeEnum[] { JsonUtilTest.SomeEnum.FIRST_VALUE, JsonUtilTest.SomeEnum
.FIRST_VALUE, JsonUtilTest.SomeEnum.SECOND_VALUE };
classWithEnum.firstValue = JsonUtilTest.SomeEnum.SECOND_VALUE;
return classWithEnum;
}
private static String[] CreateStringWithLineBreaks() {
return new String[] { "String\n\rtest", " \n \t" };
}
private class ComplexStructure {
public IDictionary<String, int?> map = new LinkedDictionary<String, int?>();
public String str = "";
public IDictionary<String, JsonUtilTest.ChildInComplexStructure> childsMap = new LinkedDictionary<String,
JsonUtilTest.ChildInComplexStructure>();
public override bool Equals(Object o) {
if (this == o) {
return true;
}
if (o == null || GetType() != o.GetType()) {
return false;
}
JsonUtilTest.ComplexStructure that = (JsonUtilTest.ComplexStructure)o;
return MapUtil.Equals(map, that.map) && Object.Equals(str, that.str) && MapUtil.Equals(childsMap, that.childsMap
);
}
public override int GetHashCode() {
int result = map != null ? MapUtil.GetHashCode(map) : 0;
result = 31 * result + (str != null ? str.GetHashCode() : 0);
result = 31 * result + (childsMap != null ? MapUtil.GetHashCode(childsMap) : 0);
return result;
}
}
private class ChildInComplexStructure {
public String[] arrayStr = new String[] { "" };
public JsonUtilTest.GrandsonComplexStructure[] grandsons = new JsonUtilTest.GrandsonComplexStructure[] { new
JsonUtilTest.GrandsonComplexStructure() };
public override bool Equals(Object o) {
if (this == o) {
return true;
}
if (o == null || GetType() != o.GetType()) {
return false;
}
JsonUtilTest.ChildInComplexStructure that = (JsonUtilTest.ChildInComplexStructure)o;
return JavaUtil.ArraysEquals(arrayStr, that.arrayStr) && JavaUtil.ArraysEquals(grandsons, that.grandsons);
}
public override int GetHashCode() {
int result = JavaUtil.ArraysHashCode(arrayStr);
result = 31 * result + JavaUtil.ArraysHashCode(grandsons);
return result;
}
}
private class GrandsonComplexStructure {
public int integer = 0;
public String name = "";
public override bool Equals(Object o) {
if (this == o) {
return true;
}
if (o == null || GetType() != o.GetType()) {
return false;
}
JsonUtilTest.GrandsonComplexStructure that = (JsonUtilTest.GrandsonComplexStructure)o;
return integer == that.integer && Object.Equals(name, that.name);
}
public override int GetHashCode() {
int result = integer;
result = 31 * result + (name != null ? name.GetHashCode() : 0);
return result;
}
}
private class ClassWithEnum {
public JsonUtilTest.SomeEnum firstValue;
public JsonUtilTest.SomeEnum[] enumArray = new JsonUtilTest.SomeEnum[] { };
public override bool Equals(Object o) {
if (this == o) {
return true;
}
if (o == null || GetType() != o.GetType()) {
return false;
}
JsonUtilTest.ClassWithEnum that = (JsonUtilTest.ClassWithEnum)o;
return firstValue == that.firstValue && JavaUtil.ArraysEquals(enumArray, that.enumArray);
}
public override int GetHashCode() {
int result = JavaUtil.ArraysHashCode(firstValue);
result = 31 * result + JavaUtil.ArraysHashCode(enumArray);
return result;
}
}
private enum SomeEnum {
FIRST_VALUE,
SECOND_VALUE,
THIRD_VALUE
}
private class ClassWithDefaultValue {
public String firstString = "defaultValue";
public int? integer = 3;
public double? doubleValue = 0.0;
public ClassWithDefaultValue(String firstString, int? integer, double? doubleValue) {
if (firstString != null) {
this.firstString = firstString;
}
if (integer != null) {
this.integer = integer;
}
this.doubleValue = doubleValue;
}
public override bool Equals(Object o) {
if (this == o) {
return true;
}
if (o == null || GetType() != o.GetType()) {
return false;
}
JsonUtilTest.ClassWithDefaultValue that = (JsonUtilTest.ClassWithDefaultValue)o;
return Object.Equals(firstString, that.firstString) && Object.Equals(integer, that.integer) && Object.Equals
(doubleValue, that.doubleValue);
}
public override int GetHashCode() {
int result = (firstString == null ? 0 : firstString.GetHashCode());
result = 31 * result + (integer == null ? 0 : integer.GetHashCode());
result = 31 * result + (doubleValue == null ? 0 : doubleValue.GetHashCode());
return result;
}
}
}
}

View File

@@ -0,0 +1,163 @@
/*
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.Test;
using Newtonsoft.Json;
namespace TSpdf.Commons.Utils {
[NUnit.Framework.Category("UnitTest")]
public class JsonUtilWithNewtonsoftTest : ExtendedTSpdfTest {
private static Func<JsonSerializerSettings> DEFAULT_JSON_CONVERTER_SETTINGS;
private static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/commons/utils/JsonUtilTest/";
[NUnit.Framework.SetUp]
public virtual void SetUpHandler() {
DEFAULT_JSON_CONVERTER_SETTINGS = JsonConvert.DefaultSettings;
}
[NUnit.Framework.TearDown]
public virtual void ResetHandler() {
JsonConvert.DefaultSettings = DEFAULT_JSON_CONVERTER_SETTINGS;
}
[NUnit.Framework.Test]
public virtual void TryToOverrideDefaultSerializationSettingForSerializeToStringTest() {
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
};
String cmp = SOURCE_FOLDER + "classWithEnum.json";
ClassWithEnum classWithEnum = CreateClassWithEnumObject();
String resultString = JsonUtil.SerializeToString(classWithEnum);
String cmpString = GetJsonStringFromFile(cmp);
NUnit.Framework.Assert.IsTrue(JsonUtil.AreTwoJsonObjectEquals(cmpString, resultString));
}
[NUnit.Framework.Test]
public virtual void TryToOverrideDefaultSerializationSettingForSerializeToStreamTest() {
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
};
String path = SOURCE_FOLDER + "classWithEnum.json";
using (Stream inputStream = FileUtil.GetInputStreamForFile(path)) {
using (MemoryStream baos = ConvertInputStreamToOutput(inputStream)) {
using (MemoryStream serializationResult = new MemoryStream()) {
JsonUtil.SerializeToStream(serializationResult, CreateClassWithEnumObject());
serializationResult.Flush();
NUnit.Framework.Assert.AreEqual(baos.ToArray(), serializationResult.ToArray());
}
}
}
}
[NUnit.Framework.Test]
public virtual void TryToOverrideDefaultSerializationSettingForSerializeToMinimalStringTest() {
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Arrays
};
String cmp = SOURCE_FOLDER + "minimalClassWithEnum.json";
ClassWithEnum classWithEnum = CreateClassWithEnumObject();
String resultString = JsonUtil.SerializeToMinimalString(classWithEnum);
String compareString = GetJsonStringFromFile(cmp);
NUnit.Framework.Assert.IsTrue(JsonUtil.AreTwoJsonObjectEquals(compareString, resultString));
}
[NUnit.Framework.Test]
public virtual void TryToOverrideDefaultSerializationSettingForSerializeToMinimalStreamTest() {
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
};
String path = SOURCE_FOLDER + "minimalClassWithEnum.json";
using (Stream inputStream = FileUtil.GetInputStreamForFile(path)) {
using (MemoryStream baos = ConvertInputStreamToOutput(inputStream)) {
using (MemoryStream serializationResult = new MemoryStream()) {
JsonUtil.SerializeToMinimalStream(serializationResult, CreateClassWithEnumObject());
serializationResult.Flush();
NUnit.Framework.Assert.AreEqual(baos.ToArray(), serializationResult.ToArray());
}
}
}
}
private String GetJsonStringFromFile(String pathToFile) {
byte[] fileBytes = File.ReadAllBytes(System.IO.Path.Combine(pathToFile));
// Use String(byte[]) because there is autoporting for this
// construction by sharpen by call JavaUtil#GetStringForBytes
return TSpdf.Commons.Utils.JavaUtil.GetStringForBytes(fileBytes, System.Text.Encoding.UTF8);
}
private static MemoryStream ConvertInputStreamToOutput(Stream inputStream) {
MemoryStream result = new MemoryStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.Read(buffer)) != -1) {
result.Write(buffer, 0, length);
}
result.Flush();
return result;
}
private static ClassWithEnum CreateClassWithEnumObject() {
ClassWithEnum classWithEnum = new ClassWithEnum();
classWithEnum.enumArray = new SomeEnum[] { SomeEnum.FIRST_VALUE, SomeEnum
.FIRST_VALUE, SomeEnum.SECOND_VALUE };
classWithEnum.firstValue = SomeEnum.SECOND_VALUE;
return classWithEnum;
}
private class ClassWithEnum {
public SomeEnum firstValue;
public SomeEnum[] enumArray = new SomeEnum[] { };
public override bool Equals(Object o) {
if (this == o) {
return true;
}
if (o == null || GetType() != o.GetType()) {
return false;
}
ClassWithEnum that = (ClassWithEnum)o;
return firstValue == that.firstValue && JavaUtil.ArraysEquals(enumArray, that.enumArray);
}
public override int GetHashCode() {
int result = JavaUtil.ArraysHashCode(firstValue);
result = 31 * result + JavaUtil.ArraysHashCode(enumArray);
return result;
}
}
private enum SomeEnum {
FIRST_VALUE,
SECOND_VALUE,
THIRD_VALUE
}
}
}

View File

@@ -0,0 +1,158 @@
/*
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.Test;
namespace TSpdf.Commons.Utils {
[NUnit.Framework.Category("UnitTest")]
public class MapUtilTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void NullMapsAreEqualTest() {
NUnit.Framework.Assert.IsTrue(MapUtil.Equals(null, null));
}
[NUnit.Framework.Test]
public virtual void NullMapIsNotEqualToEmptyMapTest() {
NUnit.Framework.Assert.IsFalse(MapUtil.Equals(new Dictionary<String, String>(), null));
NUnit.Framework.Assert.IsFalse(MapUtil.Equals(null, new Dictionary<String, String>()));
}
[NUnit.Framework.Test]
public virtual void MapsOfDifferentTypesAreNotEqualTest() {
NUnit.Framework.Assert.IsFalse(MapUtil.Equals(new Dictionary<String, String>(), new SortedDictionary<String
, String>()));
}
[NUnit.Framework.Test]
public virtual void MapsOfDifferentSizeAreNotEqualTest() {
IDictionary<String, String> m1 = new Dictionary<String, String>();
m1.Put("m1", "m1");
IDictionary<String, String> m2 = new Dictionary<String, String>();
m2.Put("m1", "m1");
m2.Put("m2", "m2");
NUnit.Framework.Assert.IsFalse(MapUtil.Equals(m1, m2));
}
[NUnit.Framework.Test]
public virtual void NullValueInMapTest() {
IDictionary<String, String> m1 = JavaCollectionsUtil.SingletonMap<String, String>("nullKey", null);
IDictionary<String, String> m2 = JavaCollectionsUtil.SingletonMap("notNullKey", "notNull");
NUnit.Framework.Assert.IsFalse(MapUtil.Equals(m1, m2));
}
[NUnit.Framework.Test]
public virtual void MapsWithDifferentKeysAreNotEqualTest() {
IDictionary<String, String> m1 = new Dictionary<String, String>();
m1.Put("m1", "value");
IDictionary<String, String> m2 = new Dictionary<String, String>();
m2.Put("m2", "value");
NUnit.Framework.Assert.IsFalse(MapUtil.Equals(m1, m2));
}
[NUnit.Framework.Test]
public virtual void MapsWithDifferentValuesAreNotEqualTest() {
IDictionary<String, String> m1 = new Dictionary<String, String>();
m1.Put("key", "m1");
IDictionary<String, String> m2 = new Dictionary<String, String>();
m2.Put("key", "m2");
NUnit.Framework.Assert.IsFalse(MapUtil.Equals(m1, m2));
}
[NUnit.Framework.Test]
public virtual void EqualArraysTest() {
IDictionary<String, String> m1 = new Dictionary<String, String>();
m1.Put("key", "value");
IDictionary<String, String> m2 = new Dictionary<String, String>();
m2.Put("key", "value");
NUnit.Framework.Assert.IsTrue(MapUtil.Equals(m1, m2));
}
[NUnit.Framework.Test]
public virtual void PutIfNotNullTest() {
IDictionary<String, String> m1 = new Dictionary<String, String>();
MapUtil.PutIfNotNull(m1, "key", null);
NUnit.Framework.Assert.IsTrue(m1.IsEmpty());
MapUtil.PutIfNotNull(m1, "key", "value");
NUnit.Framework.Assert.IsFalse(m1.IsEmpty());
NUnit.Framework.Assert.AreEqual("value", m1.Get("key"));
}
[NUnit.Framework.Test]
public virtual void NullMapsEqualEqualHashCodeTest() {
NUnit.Framework.Assert.AreEqual(MapUtil.GetHashCode((IDictionary<String, String>)null), MapUtil.GetHashCode
((IDictionary<String, String>)null));
}
[NUnit.Framework.Test]
public virtual void NullMapEmptyMapDiffHashCodeTest() {
NUnit.Framework.Assert.AreEqual(MapUtil.GetHashCode((IDictionary<String, String>)null), MapUtil.GetHashCode
(new Dictionary<String, String>()));
}
[NUnit.Framework.Test]
public virtual void MapsOfDifferentTypesHashCodeTest() {
NUnit.Framework.Assert.AreEqual(MapUtil.GetHashCode(new SortedDictionary<Object, Object>()), MapUtil.GetHashCode
(new Dictionary<String, String>()));
}
[NUnit.Framework.Test]
public virtual void EqualMapsHashCodeTest() {
IDictionary<String, String> m1 = new Dictionary<String, String>();
m1.Put("key", "value");
IDictionary<String, String> m2 = new Dictionary<String, String>();
m2.Put("key", "value");
NUnit.Framework.Assert.AreEqual(MapUtil.GetHashCode(m1), MapUtil.GetHashCode(m2));
}
[NUnit.Framework.Test]
public virtual void MapsMergeTest() {
IDictionary<int, int?> destination = new Dictionary<int, int?>();
destination.Put(1, 5);
destination.Put(2, 5);
destination.Put(4, 5);
IDictionary<int, int?> source = new Dictionary<int, int?>();
source.Put(1, 10);
source.Put(2, 10);
source.Put(3, 10);
MapUtil.Merge(destination, JavaCollectionsUtil.UnmodifiableMap(source), (d, s) => d + s);
IDictionary<int, int?> expectedMap = new Dictionary<int, int?>();
expectedMap.Put(1, 15);
expectedMap.Put(2, 15);
expectedMap.Put(3, 10);
expectedMap.Put(4, 5);
NUnit.Framework.Assert.AreEqual(expectedMap, destination);
}
[NUnit.Framework.Test]
public virtual void SameMapsMergeTest() {
IDictionary<int, int?> map = new Dictionary<int, int?>();
map.Put(1, 5);
map.Put(2, 5);
map.Put(4, 5);
IDictionary<int, int?> expectedMap = new Dictionary<int, int?>(map);
MapUtil.Merge(map, map, (d, s) => d + s);
NUnit.Framework.Assert.AreEqual(expectedMap, map);
}
}
}

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 System.Collections.Generic;
using System.Linq;
using TSpdf.Test;
namespace TSpdf.Commons.Utils {
[NUnit.Framework.Category("UnitTest")]
[NUnit.Framework.TestFixtureSource("DataSourceTestFixtureData")]
public class MessageFormatUtilTest : ExtendedTSpdfTest {
private String expectedResult;
private String pattern;
private Object[] arguments;
public MessageFormatUtilTest(Object expectedResult, Object pattern, Object arguments, Object name) {
this.expectedResult = (String)expectedResult;
this.pattern = (String)pattern;
this.arguments = (Object[])arguments;
}
public MessageFormatUtilTest(Object[] array)
: this(array[0], array[1], array[2], array[3]) {
}
public static IEnumerable<Object[]> DataSource() {
return JavaUtil.ArraysAsList(new Object[][] { new Object[] { "Plain message with params 1 test", "Plain message with params {0} {1}"
, new Object[] { 1, "test" }, "test with simple params" }, new Object[] { "Message with 'single quotes'"
, "Message with 'single quotes'", new Object[0], "test with single quotes" }, new Object[] { "Message with ''doubled single quotes''"
, "Message with ''doubled single quotes''", new Object[0], "test with doubled single quotes" }, new Object
[] { "Message with {curly braces} and a parameter {I'm between curly braces too}", "Message with {{curly braces}} and a parameter {{{0}}}"
, new Object[] { "I'm between curly braces too" }, "Test with curly braces" }, new Object[] { "'{value}'"
, "'{{{0}}}'", new Object[] { "value" }, "Mix om multiple brackets and quotes 1" }, new Object[] { "'value'"
, "'{0}'", new Object[] { "value" }, "Mix of brackets and quotes" }, new Object[] { "{'0'}", "{{'0'}}"
, new Object[0], "Mix of multiple brackets and quotes 2" }, new Object[] { "single opening brace {0 test"
, "single opening brace {{0 test", new Object[0], "Test single opening brace" }, new Object[] { "single closing brace 0} test"
, "single closing brace 0}} test", new Object[0], "Test single closing brace" }, new Object[] { "single opening + closing brace { test }"
, "single opening + closing brace {{ {0} }}", new Object[] { "test" }, "Test single opening and closing brace"
} });
}
public static ICollection<NUnit.Framework.TestFixtureData> DataSourceTestFixtureData() {
return DataSource().Select(array => new NUnit.Framework.TestFixtureData(array)).ToList();
}
[NUnit.Framework.Test]
public virtual void TestFormatting() {
NUnit.Framework.Assert.AreEqual(expectedResult, MessageFormatUtil.Format(pattern, arguments));
}
}
}

View File

@@ -0,0 +1,50 @@
/*
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.Commons.Utils {
[NUnit.Framework.Category("UnitTest")]
public class ProcessInfoTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void GetExitCodeTest() {
int exitCode = 1;
ProcessInfo processInfo = new ProcessInfo(exitCode, null, null);
NUnit.Framework.Assert.AreEqual(exitCode, processInfo.GetExitCode());
}
[NUnit.Framework.Test]
public virtual void GetProcessStdOutput() {
String stdOutput = "output";
ProcessInfo processInfo = new ProcessInfo(0, stdOutput, null);
NUnit.Framework.Assert.AreEqual(stdOutput, processInfo.GetProcessStdOutput());
}
[NUnit.Framework.Test]
public virtual void GetProcessErrOutput() {
String stdOutput = "output";
ProcessInfo processInfo = new ProcessInfo(0, null, stdOutput);
NUnit.Framework.Assert.AreEqual(stdOutput, processInfo.GetProcessErrOutput());
}
}
}

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 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;
using TSpdf.Test;
namespace TSpdf.Commons.Utils {
/// <summary>At the moment there is no StringUtil class in Java, but there is one in C# and we are testing</summary>
[NUnit.Framework.Category("UnitTest")]
public class StringUtilTest : ExtendedTSpdfTest {
[NUnit.Framework.Test]
public virtual void PatternSplitTest01() {
// Android-Conversion-Ignore-Test (TODO DEVSIX-6457 fix different behavior of Pattern.split method)
// Pattern.split in Java works differently compared to Regex.Split in C#
// In C#, empty strings are possible at the beginning of the resultant array for non-capturing groups in split regex
// Thus, in C# we use a separate utility for splitting to align the implementation with Java
// This test verifies that the resultant behavior is the same
Regex pattern = TSpdf.Commons.Utils.StringUtil.RegexCompile("(?=[ab])");
String source = "a01aa78ab89b";
String[] expected = new String[] { "a01", "a", "a78", "a", "b89", "b" };
String[] result = TSpdf.Commons.Utils.StringUtil.Split(pattern, source);
NUnit.Framework.Assert.AreEqual(expected, result);
}
[NUnit.Framework.Test]
public virtual void PatternSplitTest02() {
Regex pattern = TSpdf.Commons.Utils.StringUtil.RegexCompile("(?=[ab])");
String source = "";
String[] expected = new String[] { "" };
String[] result = TSpdf.Commons.Utils.StringUtil.Split(pattern, source);
NUnit.Framework.Assert.AreEqual(expected, result);
}
[NUnit.Framework.Test]
public virtual void StringSplitTest01() {
// Android-Conversion-Ignore-Test (TODO DEVSIX-6457 fix different behavior of Pattern.split method)
String source = "a01aa78ab89b";
String[] expected = new String[] { "a01", "a", "a78", "a", "b89", "b" };
String[] result = TSpdf.Commons.Utils.StringUtil.Split(source, "(?=[ab])");
NUnit.Framework.Assert.AreEqual(expected, result);
}
[NUnit.Framework.Test]
public virtual void StringSplitTest02() {
String source = "";
String[] expected = new String[] { "" };
String[] result = TSpdf.Commons.Utils.StringUtil.Split(source, "(?=[ab])");
NUnit.Framework.Assert.AreEqual(expected, result);
}
}
}

View File

@@ -0,0 +1,175 @@
/*
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.Diagnostics;
using System.Text;
using TSpdf.Test;
namespace TSpdf.Commons.Utils {
public class SystemUtilTest : ExtendedTSpdfTest {
private const String MAGICK_COMPARE_ENVIRONMENT_VARIABLE_LEGACY = "compareExec";
private const String MAGICK_COMPARE_ENVIRONMENT_VARIABLE = "TSpdf_MAGICK_COMPARE_EXEC";
public static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework
.TestContext.CurrentContext.TestDirectory) + "/resources/TSpdf/commons/utils/SystemUtilTest/";
private static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/commons/utils/SystemUtilTest/";
// This is empty file that used to check the logic for existed execution file
public static readonly String STUB_EXEC_FILE = SOURCE_FOLDER + "folder with space/stubFile";
[NUnit.Framework.SetUp]
public virtual void SetUp() {
CreateOrClearDestinationFolder(DESTINATION_FOLDER);
}
[NUnit.Framework.Test]
public virtual void SetProcessStartInfoTest() {
Process process = new Process();
SystemUtil.SetProcessStartInfo(process, "command", "param1 param2");
NUnit.Framework.Assert.IsFalse(process.StartInfo.UseShellExecute);
NUnit.Framework.Assert.IsTrue(process.StartInfo.RedirectStandardOutput);
NUnit.Framework.Assert.IsTrue(process.StartInfo.RedirectStandardError);
NUnit.Framework.Assert.IsTrue(process.StartInfo.CreateNoWindow);
NUnit.Framework.Assert.AreEqual("command", process.StartInfo.FileName);
NUnit.Framework.Assert.AreEqual("param1 param2", process.StartInfo.Arguments);
}
[NUnit.Framework.Test]
public virtual void PrepareProcessArgumentsStubExecFileTest() {
String[] processArguments = SystemUtil.PrepareProcessArguments(STUB_EXEC_FILE, "param1 param2");
NUnit.Framework.Assert.AreEqual(STUB_EXEC_FILE, processArguments[0]);
NUnit.Framework.Assert.AreEqual("param1 param2", processArguments[1]);
}
[NUnit.Framework.Test]
public virtual void PrepareProcessArgumentsStubExecFileInQuotesTest() {
String testLine = "\"" + STUB_EXEC_FILE + "\"" + " compare";
String[] processArguments = SystemUtil.PrepareProcessArguments(testLine, "param1 param2");
NUnit.Framework.Assert.AreEqual("\"" + STUB_EXEC_FILE + "\"", processArguments[0]);
NUnit.Framework.Assert.AreEqual("compare param1 param2", processArguments[1]);
}
[NUnit.Framework.Test]
public virtual void PrepareProcessArgumentsGsTest() {
String[] processArguments = SystemUtil.PrepareProcessArguments("gs", "param1 param2");
NUnit.Framework.Assert.AreEqual("gs", processArguments[0]);
NUnit.Framework.Assert.AreEqual("param1 param2", processArguments[1]);
}
[NUnit.Framework.Test]
public virtual void PrepareProcessArgumentsMagickCompareTest() {
String[] processArguments =
SystemUtil.PrepareProcessArguments("magick compare", "param1 param2");
NUnit.Framework.Assert.AreEqual("magick", processArguments[0]);
NUnit.Framework.Assert.AreEqual("compare param1 param2", processArguments[1]);
}
[NUnit.Framework.Test]
public virtual void SplitIntoProcessArgumentsPathInQuotesTest() {
String[] processArguments =
SystemUtil.SplitIntoProcessArguments("\"C:\\Test directory with spaces\\file.exe\"",
"param1 param2");
NUnit.Framework.Assert.AreEqual("\"C:\\Test directory with spaces\\file.exe\"", processArguments[0]);
NUnit.Framework.Assert.AreEqual("param1 param2", processArguments[1]);
}
[NUnit.Framework.Test]
public virtual void SplitIntoProcessArgumentsGsTest() {
String[] processArguments = SystemUtil.SplitIntoProcessArguments("gs",
" -dSAFER -dNOPAUSE -dBATCH -sDEVICE=png16m -r150 -sOutputFile='./target/test/com/TSpdfpdf/kernel/utils/CompareToolTest/cmp_simple_pdf_with_space .pdf-%03d.png' './src/test/resources/com/TSpdfpdf/kernel/utils/CompareToolTest/cmp_simple_pdf_with_space .pdf'");
NUnit.Framework.Assert.AreEqual("gs", processArguments[0]);
NUnit.Framework.Assert.AreEqual(
"-dSAFER -dNOPAUSE -dBATCH -sDEVICE=png16m -r150 -sOutputFile=\"./target/test/com/TSpdfpdf/kernel/utils/CompareToolTest/cmp_simple_pdf_with_space .pdf-%03d.png\" \"./src/test/resources/com/TSpdfpdf/kernel/utils/CompareToolTest/cmp_simple_pdf_with_space .pdf\"",
processArguments[1]);
}
[NUnit.Framework.Test]
public virtual void SplitIntoProcessArgumentsMagickCompareTest() {
String[] processArguments = SystemUtil.SplitIntoProcessArguments("magick compare",
"'D:\\TSpdf\\java\\TSpdfcore\\kernel\\.\\target\\test\\com\\TSpdfpdf\\kernel\\utils\\CompareToolTest\\simple_pdf.pdf-001.png' 'D:\\TSpdf\\java\\TSpdfcore\\kernel\\.\\target\\test\\com\\TSpdfpdf\\kernel\\utils\\CompareToolTest\\cmp_simple_pdf_with_space .pdf-001.png'");
NUnit.Framework.Assert.AreEqual("magick", processArguments[0]);
NUnit.Framework.Assert.AreEqual(
"compare \"D:\\TSpdf\\java\\TSpdfcore\\kernel\\.\\target\\test\\com\\TSpdfpdf\\kernel\\utils\\CompareToolTest\\simple_pdf.pdf-001.png\" \"D:\\TSpdf\\java\\TSpdfcore\\kernel\\.\\target\\test\\com\\TSpdfpdf\\kernel\\utils\\CompareToolTest\\cmp_simple_pdf_with_space .pdf-001.png\"",
processArguments[1]);
}
[NUnit.Framework.Test]
public virtual void RunProcessAndWaitWithWorkingDirectoryTest() {
String imageMagickPath = SystemUtil.GetEnvironmentVariable(MAGICK_COMPARE_ENVIRONMENT_VARIABLE);
if (imageMagickPath == null) {
imageMagickPath = SystemUtil.GetEnvironmentVariable(MAGICK_COMPARE_ENVIRONMENT_VARIABLE_LEGACY);
}
String inputImage = "image.jpg";
String cmpImage = "cmp_image.jpg";
String diff = DESTINATION_FOLDER + "diff_differentImages.png";
StringBuilder currCompareParams = new StringBuilder();
currCompareParams
.Append("'")
.Append(inputImage).Append("' '")
.Append(cmpImage).Append("' '")
.Append(diff).Append("'");
bool result = SystemUtil.RunProcessAndWait(imageMagickPath, currCompareParams.ToString(), SOURCE_FOLDER);
NUnit.Framework.Assert.False(result);
NUnit.Framework.Assert.True(FileUtil.FileExists(diff));
}
[NUnit.Framework.Test]
public void RunProcessAndGetProcessInfoTest() {
String imageMagickPath = SystemUtil.GetEnvironmentVariable(MAGICK_COMPARE_ENVIRONMENT_VARIABLE);
if (imageMagickPath == null) {
imageMagickPath = SystemUtil.GetEnvironmentVariable(MAGICK_COMPARE_ENVIRONMENT_VARIABLE_LEGACY);
}
ProcessInfo processInfo = SystemUtil.RunProcessAndGetProcessInfo(imageMagickPath,"--version");
NUnit.Framework.Assert.NotNull(processInfo);
NUnit.Framework.Assert.AreEqual(0, processInfo.GetExitCode());
}
}
}

View File

@@ -0,0 +1,191 @@
/*
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.Commons.Exceptions;
using TSpdf.Commons.Logs;
using TSpdf.Test;
using TSpdf.Test.Attributes;
namespace TSpdf.Commons.Utils {
[NUnit.Framework.Category("UnitTest")]
public class ZipFileReaderTest : ExtendedTSpdfTest {
private static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/commons/utils/ZipFileReaderTest/";
[NUnit.Framework.Test]
public virtual void ConstructorWithNullPathTest() {
Exception ex = NUnit.Framework.Assert.Catch(typeof(System.IO.IOException), () => new ZipFileReader(null));
NUnit.Framework.Assert.AreEqual(CommonsExceptionMessageConstant.FILE_NAME_CAN_NOT_BE_NULL, ex.Message);
}
[NUnit.Framework.Test]
public virtual void ConstructorWithInvalidPathTest() {
NUnit.Framework.Assert.Catch(typeof(Exception), () => new ZipFileReader("invalidPath"));
}
[NUnit.Framework.Test]
public virtual void ConstructorWithNonZipPathTest() {
NUnit.Framework.Assert.Catch(typeof(Exception), () => new ZipFileReader(SOURCE_FOLDER + "firstFile.txt"));
}
[NUnit.Framework.Test]
public virtual void GetFileNamesFromEmptyZipTest() {
// Android-Conversion-Ignore-Test (TODO DEVSIX-6906 fix different behavior of ZipFileWriter\Reader)
using (ZipFileReader fileReader = new ZipFileReader(SOURCE_FOLDER + "emptyZip.zip")) {
ICollection<String> nameSet = fileReader.GetFileNames();
NUnit.Framework.Assert.IsTrue(nameSet.IsEmpty());
}
}
[NUnit.Framework.Test]
public virtual void GetFileNamesFromZipTest() {
using (ZipFileReader fileReader = new ZipFileReader(SOURCE_FOLDER + "archive.zip")) {
ICollection<String> nameSet = fileReader.GetFileNames();
NUnit.Framework.Assert.IsNotNull(nameSet);
NUnit.Framework.Assert.AreEqual(6, nameSet.Count);
NUnit.Framework.Assert.IsTrue(nameSet.Contains("firstFile.txt"));
NUnit.Framework.Assert.IsTrue(nameSet.Contains("secondFile.txt"));
NUnit.Framework.Assert.IsTrue(nameSet.Contains("subfolder/thirdFile.txt"));
NUnit.Framework.Assert.IsTrue(nameSet.Contains("subfolder/fourthFile.txt"));
NUnit.Framework.Assert.IsTrue(nameSet.Contains("subfolder/subsubfolder/fifthFile.txt"));
NUnit.Framework.Assert.IsTrue(nameSet.Contains("subfolder/subsubfolder/sixthFile.txt"));
}
}
[NUnit.Framework.Test]
[LogMessage(CommonsLogMessageConstant.UNCOMPRESSED_DATA_SIZE_IS_TOO_MUCH)]
public virtual void GetFileNamesFromZipBombBySettingThresholdSizeTest() {
using (ZipFileReader fileReader = new ZipFileReader(SOURCE_FOLDER + "zipBombTest.zip")) {
fileReader.SetThresholdRatio(1000);
fileReader.SetThresholdSize(10000);
ICollection<String> nameSet = fileReader.GetFileNames();
NUnit.Framework.Assert.IsNotNull(nameSet);
NUnit.Framework.Assert.AreEqual(0, nameSet.Count);
}
}
[NUnit.Framework.Test]
[LogMessage(CommonsLogMessageConstant.RATIO_IS_HIGHLY_SUSPICIOUS)]
public virtual void GetFileNamesFromZipBombBySettingThresholdRatioTest() {
using (ZipFileReader fileReader = new ZipFileReader(SOURCE_FOLDER + "zipBombTest.zip")) {
fileReader.SetThresholdRatio(5);
ICollection<String> nameSet = fileReader.GetFileNames();
NUnit.Framework.Assert.IsNotNull(nameSet);
NUnit.Framework.Assert.AreEqual(0, nameSet.Count);
}
}
[NUnit.Framework.Test]
[LogMessage(CommonsLogMessageConstant.TOO_MUCH_ENTRIES_IN_ARCHIVE)]
public virtual void GetFileNamesFromZipBombBySettingThresholdEntriesTest() {
using (ZipFileReader fileReader = new ZipFileReader(SOURCE_FOLDER + "archive.zip")) {
fileReader.SetThresholdEntries(5);
ICollection<String> nameSet = fileReader.GetFileNames();
NUnit.Framework.Assert.IsNotNull(nameSet);
NUnit.Framework.Assert.IsTrue(nameSet.Count <= 5);
}
}
[NUnit.Framework.Test]
public virtual void ReadFromZipWithNullPathTest() {
using (ZipFileReader reader = new ZipFileReader(SOURCE_FOLDER + "archive.zip")) {
Exception ex = NUnit.Framework.Assert.Catch(typeof(System.IO.IOException), () => reader.ReadFromZip(null));
NUnit.Framework.Assert.AreEqual(CommonsExceptionMessageConstant.FILE_NAME_CAN_NOT_BE_NULL, ex.Message);
}
}
[NUnit.Framework.Test]
public virtual void ReadFromZipWithNotExistingPathTest() {
String fileName = "name";
using (ZipFileReader reader = new ZipFileReader(SOURCE_FOLDER + "archive.zip")) {
Exception ex = NUnit.Framework.Assert.Catch(typeof(System.IO.IOException), () => reader.ReadFromZip(fileName
));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(CommonsExceptionMessageConstant.ZIP_ENTRY_NOT_FOUND
, fileName), ex.Message);
}
}
[NUnit.Framework.Test]
public virtual void ReadFromZipWithInvalidPathTest() {
String fileName = "thirdFile.txt";
using (ZipFileReader reader = new ZipFileReader(SOURCE_FOLDER + "archive.zip")) {
Exception ex = NUnit.Framework.Assert.Catch(typeof(System.IO.IOException), () => reader.ReadFromZip(fileName
));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(CommonsExceptionMessageConstant.ZIP_ENTRY_NOT_FOUND
, fileName), ex.Message);
}
}
[NUnit.Framework.Test]
public virtual void ReadFromZipWithPathAtRootTest() {
using (ZipFileReader reader = new ZipFileReader(SOURCE_FOLDER + "archive.zip")) {
using (Stream inputStream = reader.ReadFromZip("firstFile.txt")) {
NUnit.Framework.Assert.IsNotNull(inputStream);
NUnit.Framework.Assert.AreEqual("1", ConvertInputStreamToString(inputStream));
}
}
}
[NUnit.Framework.Test]
public virtual void ReadFromZipWithFileInSubFolderTest() {
using (ZipFileReader reader = new ZipFileReader(SOURCE_FOLDER + "archive.zip")) {
using (Stream inputStream = reader.ReadFromZip("subfolder/thirdFile.txt")) {
NUnit.Framework.Assert.IsNotNull(inputStream);
NUnit.Framework.Assert.AreEqual("3", ConvertInputStreamToString(inputStream));
}
}
}
[NUnit.Framework.Test]
public virtual void ReadFromZipWithFileInSubSubFolderPathTest() {
using (ZipFileReader reader = new ZipFileReader(SOURCE_FOLDER + "archive.zip")) {
using (Stream inputStream = reader.ReadFromZip("subfolder/subsubfolder/fifthFile.txt")) {
NUnit.Framework.Assert.IsNotNull(inputStream);
NUnit.Framework.Assert.AreEqual("5", ConvertInputStreamToString(inputStream));
}
}
}
[NUnit.Framework.Test]
public virtual void ReadFromZipWithClosedReaderTest() {
ZipFileReader reader = new ZipFileReader(SOURCE_FOLDER + "archive.zip");
reader.Dispose();
NUnit.Framework.Assert.Catch(typeof(InvalidOperationException), () => reader.ReadFromZip("subfolder/subsubfolder/fifthFile.txt"
));
}
private static String ConvertInputStreamToString(Stream inputStream) {
using (MemoryStream result = new MemoryStream()) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.Read(buffer)) != -1) {
result.Write(buffer, 0, length);
}
result.Flush();
return EncodingUtil.ConvertToString(result.ToArray(), "UTF-8");
}
}
}
}

View File

@@ -0,0 +1,292 @@
/*
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.Commons.Exceptions;
using TSpdf.Test;
namespace TSpdf.Commons.Utils {
[NUnit.Framework.Category("IntegrationTest")]
public class ZipFileWriterTest : ExtendedTSpdfTest {
private static readonly String SOURCE_FOLDER = TSpdf.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
.CurrentContext.TestDirectory) + "/resources/TSpdf/commons/utils/ZipFileWriter/";
private static readonly String DESTINATION_FOLDER = NUnit.Framework.TestContext.CurrentContext.TestDirectory
+ "/test/TSpdf/commons/utils/ZipFileWriter/";
[NUnit.Framework.OneTimeSetUp]
public static void BeforeClass() {
CreateOrClearDestinationFolder(DESTINATION_FOLDER);
}
[NUnit.Framework.Test]
public virtual void ConstructorWithNullPathTest() {
Exception ex = NUnit.Framework.Assert.Catch(typeof(System.IO.IOException), () => new ZipFileWriter(null));
NUnit.Framework.Assert.AreEqual(CommonsExceptionMessageConstant.FILE_NAME_CAN_NOT_BE_NULL, ex.Message);
}
[NUnit.Framework.Test]
public virtual void ConstructorWithNotExistingDirsInPathTest() {
NUnit.Framework.Assert.Catch(typeof(System.IO.IOException), () => new ZipFileWriter(DESTINATION_FOLDER + "notExistingDir/archive.zip"
));
}
[NUnit.Framework.Test]
public virtual void ConstructorWithAlreadyExistedFilePathTest() {
String fileName = "constructorWithAlreadyExistedFilePath.zip";
FileUtil.Copy(SOURCE_FOLDER + fileName, DESTINATION_FOLDER + fileName);
Exception ex = NUnit.Framework.Assert.Catch(typeof(System.IO.IOException), () => new ZipFileWriter(DESTINATION_FOLDER
+ fileName));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(CommonsExceptionMessageConstant.FILE_NAME_ALREADY_EXIST
, DESTINATION_FOLDER + fileName), ex.Message);
}
[NUnit.Framework.Test]
public virtual void ConstructorWithNotZipFileTest() {
String fileName = "testFile.txt";
FileUtil.Copy(SOURCE_FOLDER + fileName, DESTINATION_FOLDER + fileName);
Exception ex = NUnit.Framework.Assert.Catch(typeof(System.IO.IOException), () => new ZipFileWriter(DESTINATION_FOLDER
+ fileName));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(CommonsExceptionMessageConstant.FILE_NAME_ALREADY_EXIST
, DESTINATION_FOLDER + fileName), ex.Message);
}
[NUnit.Framework.Test]
public virtual void ConstructorWithDirectoryPathTest() {
String pathToDirectory = DESTINATION_FOLDER + "constructorWithDirectoryPath/";
FileUtil.CreateDirectories(pathToDirectory);
Exception ex = NUnit.Framework.Assert.Catch(typeof(System.IO.IOException), () => new ZipFileWriter(pathToDirectory
));
NUnit.Framework.Assert.AreEqual(MessageFormatUtil.Format(CommonsExceptionMessageConstant.FILE_NAME_ALREADY_EXIST
, pathToDirectory), ex.Message);
}
[NUnit.Framework.Test]
public virtual void EmptyZipCreationTest() {
// Android-Conversion-Ignore-Test (TODO DEVSIX-6906 fix different behavior of ZipFileWriter\Reader)
String pathToFile = DESTINATION_FOLDER + "emptyZipCreation.zip";
ZipFileWriter writer = new ZipFileWriter(pathToFile);
writer.Dispose();
NUnit.Framework.Assert.IsTrue(FileUtil.FileExists(pathToFile));
// We are not using ZipFileWriter in ZipFileReader tests, so we don't have testing cycles here.
using (ZipFileReader zip = new ZipFileReader(pathToFile)) {
NUnit.Framework.Assert.IsTrue(zip.GetFileNames().IsEmpty());
}
}
[NUnit.Framework.Test]
public virtual void AddNullFileEntryTest() {
// Android-Conversion-Ignore-Test (TODO DEVSIX-6906 fix different behavior of ZipFileWriter\Reader)
String pathToFile = DESTINATION_FOLDER + "addNullFileEntry.zip";
using (ZipFileWriter writer = new ZipFileWriter(pathToFile)) {
Exception ex = NUnit.Framework.Assert.Catch(typeof(System.IO.IOException), () => writer.AddEntry("fileName.txt"
, (FileInfo)null));
NUnit.Framework.Assert.AreEqual(CommonsExceptionMessageConstant.FILE_SHOULD_EXIST, ex.Message);
}
}
[NUnit.Framework.Test]
public virtual void AddEntryWithNotExistingFileTest() {
// Android-Conversion-Ignore-Test (TODO DEVSIX-6906 fix different behavior of ZipFileWriter\Reader)
using (ZipFileWriter writer = new ZipFileWriter(DESTINATION_FOLDER + "addEntryWithNotExistingFile.zip")) {
NUnit.Framework.Assert.Catch(typeof(System.IO.IOException), () => writer.AddEntry("fileName", new FileInfo
(SOURCE_FOLDER + "invalidPath")));
}
}
[NUnit.Framework.Test]
public virtual void AddNullStreamEntryTest() {
// Android-Conversion-Ignore-Test (TODO DEVSIX-6906 fix different behavior of ZipFileWriter\Reader)
String pathToFile = DESTINATION_FOLDER + "addNullStreamEntry.zip";
using (ZipFileWriter writer = new ZipFileWriter(pathToFile)) {
Exception ex = NUnit.Framework.Assert.Catch(typeof(System.IO.IOException), () => writer.AddEntry("fileName.txt"
, (Stream)null));
NUnit.Framework.Assert.AreEqual(CommonsExceptionMessageConstant.STREAM_CAN_NOT_BE_NULL, ex.Message);
}
}
[NUnit.Framework.Test]
public virtual void AddNullJsonEntryTest() {
// Android-Conversion-Ignore-Test (TODO DEVSIX-6906 fix different behavior of ZipFileWriter\Reader)
String pathToFile = DESTINATION_FOLDER + "addNullJsonEntry.zip";
using (ZipFileWriter writer = new ZipFileWriter(pathToFile)) {
Exception ex = NUnit.Framework.Assert.Catch(typeof(System.IO.IOException), () => writer.AddJsonEntry("fileName.txt"
, null));
NUnit.Framework.Assert.AreEqual(CommonsExceptionMessageConstant.JSON_OBJECT_CAN_NOT_BE_NULL, ex.Message);
}
}
[NUnit.Framework.Test]
public virtual void AddEntryWhenWriterIsClosedTest() {
// Android-Conversion-Ignore-Test (TODO DEVSIX-6906 fix different behavior of ZipFileWriter\Reader)
String pathToFile = DESTINATION_FOLDER + "addEntryWhenWriterIsClosed.zip";
ZipFileWriter writer = new ZipFileWriter(pathToFile);
writer.Dispose();
NUnit.Framework.Assert.Catch(typeof(Exception), () => writer.AddEntry("firstName", new FileInfo(SOURCE_FOLDER
+ "testFile.txt")));
}
[NUnit.Framework.Test]
public virtual void AddTextFileEntryTest() {
String pathToFile = DESTINATION_FOLDER + "addTextFileEntry.zip";
String textFilePath = SOURCE_FOLDER + "testFile.txt";
String fileNameInZip = "text.txt";
using (ZipFileWriter writer = new ZipFileWriter(pathToFile)) {
writer.AddEntry(fileNameInZip, new FileInfo(textFilePath));
}
using (ZipFileReader reader = new ZipFileReader(pathToFile)) {
using (Stream streamFromZip = reader.ReadFromZip(fileNameInZip)) {
using (Stream streamWithFile = FileUtil.GetInputStreamForFile(textFilePath)) {
ICollection<String> fileNames = reader.GetFileNames();
NUnit.Framework.Assert.AreEqual(1, fileNames.Count);
NUnit.Framework.Assert.IsTrue(fileNames.Contains(fileNameInZip));
NUnit.Framework.Assert.IsTrue(CompareStreams(streamWithFile, streamFromZip));
}
}
}
}
[NUnit.Framework.Test]
public virtual void AddInputStreamEntryInSubfolderTest() {
String pathToFile = DESTINATION_FOLDER + "addInputStreamEntryInSubfolder.zip";
String textFilePath = SOURCE_FOLDER + "testFile.txt";
String fileNameInZip = "subfolder/text.txt";
using (ZipFileWriter writer = new ZipFileWriter(pathToFile)) {
writer.AddEntry(fileNameInZip, FileUtil.GetInputStreamForFile(textFilePath));
}
using (ZipFileReader reader = new ZipFileReader(pathToFile)) {
using (Stream streamFromZip = reader.ReadFromZip(fileNameInZip)) {
using (Stream streamWithFile = FileUtil.GetInputStreamForFile(textFilePath)) {
ICollection<String> fileNames = reader.GetFileNames();
NUnit.Framework.Assert.AreEqual(1, fileNames.Count);
NUnit.Framework.Assert.IsTrue(fileNames.Contains(fileNameInZip));
NUnit.Framework.Assert.IsTrue(CompareStreams(streamWithFile, streamFromZip));
}
}
}
}
[NUnit.Framework.Test]
public virtual void AddJsonEntryTest() {
String pathToFile = DESTINATION_FOLDER + "addJsonEntry.zip";
String compareString = "\"©\"";
String fileNameInZip = "entry.json";
using (ZipFileWriter writer = new ZipFileWriter(pathToFile)) {
writer.AddJsonEntry(fileNameInZip, "©");
}
using (ZipFileReader reader = new ZipFileReader(pathToFile)) {
using (Stream streamFromZip = reader.ReadFromZip(fileNameInZip)) {
using (Stream compareStream = new MemoryStream(compareString.GetBytes(System.Text.Encoding.UTF8))) {
ICollection<String> fileNames = reader.GetFileNames();
NUnit.Framework.Assert.AreEqual(1, fileNames.Count);
NUnit.Framework.Assert.IsTrue(fileNames.Contains(fileNameInZip));
NUnit.Framework.Assert.IsTrue(CompareStreams(compareStream, streamFromZip));
}
}
}
}
[NUnit.Framework.Test]
public virtual void AddEntryWithSameFilePathTwiceTest() {
String pathToFile = DESTINATION_FOLDER + "addEntryWithSameFilePathTwice.zip";
String fileNameInZip = "entry.json";
using (ZipFileWriter writer = new ZipFileWriter(pathToFile)) {
writer.AddJsonEntry(fileNameInZip, "©");
NUnit.Framework.Assert.Catch(typeof(System.IO.IOException), () => writer.AddJsonEntry(fileNameInZip, "aaa"
));
}
}
[NUnit.Framework.Test]
public virtual void AddSeveralEntriesToZipTest() {
String pathToFile = DESTINATION_FOLDER + "addSeveralEntriesToZip.zip";
String firstTextFilePath = SOURCE_FOLDER + "testFile.txt";
String secondTextFilePath = SOURCE_FOLDER + "someTextFile.txt";
String compareString = "\"©\"";
String firstFileNameInZip = "firstName.txt";
String secondFileNameInZip = "subfolder/secondName.txt";
String thirdFileNameInZip = "subfolder/subfolder/thirdName.json";
using (ZipFileWriter writer = new ZipFileWriter(pathToFile)) {
writer.AddEntry(firstFileNameInZip, new FileInfo(firstTextFilePath));
writer.AddEntry(secondFileNameInZip, FileUtil.GetInputStreamForFile(secondTextFilePath));
writer.AddJsonEntry(thirdFileNameInZip, "©");
}
using (ZipFileReader reader = new ZipFileReader(pathToFile)) {
using (Stream streamWithFirstFromZip = reader.ReadFromZip(firstFileNameInZip)) {
using (Stream streamWithFirstFile = FileUtil.GetInputStreamForFile(firstTextFilePath)) {
using (Stream streamWithSecondFromZip = reader.ReadFromZip(secondFileNameInZip)) {
using (Stream streamWithSecondFile = FileUtil.GetInputStreamForFile(secondTextFilePath)) {
using (Stream streamWithJsonFromZip = reader.ReadFromZip(thirdFileNameInZip)) {
using (Stream compareStream = new MemoryStream(compareString.GetBytes(System.Text.Encoding.UTF8))) {
ICollection<String> fileNames = reader.GetFileNames();
NUnit.Framework.Assert.AreEqual(3, fileNames.Count);
NUnit.Framework.Assert.IsTrue(fileNames.Contains(firstFileNameInZip));
NUnit.Framework.Assert.IsTrue(fileNames.Contains(secondFileNameInZip));
NUnit.Framework.Assert.IsTrue(fileNames.Contains(thirdFileNameInZip));
NUnit.Framework.Assert.IsTrue(CompareStreams(streamWithFirstFile, streamWithFirstFromZip));
NUnit.Framework.Assert.IsTrue(CompareStreams(streamWithSecondFile, streamWithSecondFromZip));
NUnit.Framework.Assert.IsTrue(CompareStreams(compareStream, streamWithJsonFromZip));
}
}
}
}
}
}
}
}
[NUnit.Framework.Test]
public virtual void AddEntryWithNullFileNameTest() {
// Android-Conversion-Ignore-Test (TODO DEVSIX-6906 fix different behavior of ZipFileWriter\Reader)
String pathToFile = DESTINATION_FOLDER + "addEntryWithNullFileName.zip";
String firstTextFilePath = SOURCE_FOLDER + "testFile.txt";
using (ZipFileWriter writer = new ZipFileWriter(pathToFile)) {
Exception ex = NUnit.Framework.Assert.Catch(typeof(System.IO.IOException), () => writer.AddEntry(null, new
FileInfo(firstTextFilePath)));
NUnit.Framework.Assert.AreEqual(CommonsExceptionMessageConstant.FILE_NAME_SHOULD_BE_UNIQUE, ex.Message);
}
}
private static bool CompareStreams(Stream firstStream, Stream secondStream) {
if (firstStream == null || secondStream == null) {
throw new System.IO.IOException(CommonsExceptionMessageConstant.STREAM_CAN_NOT_BE_NULL);
}
byte[] firstStreamBytes = ConvertInputStreamToByteArray(firstStream);
byte[] secondStreamBytes = ConvertInputStreamToByteArray(secondStream);
return JavaUtil.ArraysEquals(firstStreamBytes, secondStreamBytes);
}
private static byte[] ConvertInputStreamToByteArray(Stream inputStream) {
using (MemoryStream result = new MemoryStream()) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.Read(buffer)) != -1) {
result.Write(buffer, 0, length);
}
result.Flush();
return result.ToArray();
}
}
}
}