Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Move String2Stream and ExecuteTransform into TestHelpers
  • Loading branch information
anthonylangsworth committed Mar 4, 2017
commit c742452c45a0e6df82664cf35dccaa4453870c50
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,6 @@
<Compile Include="XmlDsigXsltTransformTest.cs" />
<Compile Include="XmlLicenseTransformTest.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\Common\tests\System\IO\TempFile.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="EncryptedXmlSample3.xml" />
<EmbeddedResource Include="EncryptedXmlSample2.xml" />
Expand All @@ -57,4 +54,4 @@
<Compile Include="Samples\Samples.cs" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project>
</Project>
109 changes: 109 additions & 0 deletions src/System.Security.Cryptography.Xml/tests/TestHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,28 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.IO;
using System.Text;
using System.Xml;

namespace System.Security.Cryptography.Xml.Tests
{
public class TempFile : IDisposable
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

{
public TempFile(string fileName)
{
Path = fileName;
}

public string Path { get; }

public void Dispose()
{

}
}

internal static class TestHelpers
{
public static TempFile CreateTestDtdFile(string testName)
Expand Down Expand Up @@ -43,5 +61,96 @@ public static string EscapePath(string path)
{
return path.Replace("-", "&#2D;");
}

/// <summary>
/// Convert a <see cref="Stream"/> to a <see cref="string"/> using the given <see cref="Encoding"/>.
/// </summary>
/// <param name="stream">
/// The <see cref="Stream"/> to read from. This cannot be null.
/// </param>
/// <param name="encoding">
/// The <see cref="Encoding"/> to use. This cannot be null.
/// </param>
/// <returns>
/// The stream as a string.
/// </returns>
/// <exception cref="ArgumentNullException">
/// No argument can be null.
/// </exception>
public static string StreamToString(Stream stream, Encoding encoding)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (encoding == null)
{
throw new ArgumentNullException(nameof(encoding));
}

using (StreamReader streamReader = new StreamReader(stream, encoding))
{
return streamReader.ReadToEnd();
}
}

/// <summary>
/// Perform
/// </summary>
/// <param name="inputXml">
/// The XML to transform. This cannot be null, empty or whitespace.
/// </param>
/// <param name="transform">
/// The <see cref="Transform"/> to perform on
/// <paramref name="inputXml"/>. This cannot be null.
/// </param>
/// <param name="encoding">
/// An optional <see cref="Encoding"/> to use when serializing or
/// deserializing <paramref name="inputXml"/>. This should match the
/// encoding specified in <paramref name="inputXml"/>. If omitted or
/// null, <see cref="UTF8Encoding"/> is used.
/// </param>
/// <param name="resolver">
/// An optional <see cref="XmlResolver"/> to use. If omitted or null,
/// no resolver is used.
/// </param>
/// <returns>
/// The transformed <paramref name="inputXml"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="transform"/> cannot be null.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="inputXml"/> cannot be null, empty or whitespace.
/// </exception>
/// <exception cref="XmlException">
/// <paramref name="inputXml"/> is not valid XML.
/// </exception>
public static string ExecuteTransform(string inputXml, Transform transform, Encoding encoding = null, XmlResolver resolver = null)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wow, this xml doc is long

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, it's test code, but it's shared test code ;-)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this code is probably going to be shared across multiple test classes, I wanted to document it properly, including exceptions, so Intellisense will give the correct values.

{
if (string.IsNullOrEmpty(inputXml))
{
throw new ArgumentException("Cannot be null, empty or whitespace", nameof(inputXml));
}
if (transform == null)
{
throw new ArgumentNullException(nameof(Transform));
}

XmlDocument doc = new XmlDocument();
doc.XmlResolver = resolver;
doc.PreserveWhitespace = true;
doc.LoadXml(inputXml);

Encoding actualEncoding = encoding ?? Encoding.UTF8;
byte[] data = actualEncoding.GetBytes(inputXml);
using (Stream stream = new MemoryStream(data))
using (XmlReader reader = XmlReader.Create(stream, new XmlReaderSettings { ValidationType = ValidationType.None, DtdProcessing = DtdProcessing.Parse, XmlResolver = resolver }))
{
doc.Load(reader);
transform.LoadInput(doc);
return StreamToString((Stream)transform.GetOutput(), actualEncoding);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Resolvers;
using Xunit;

namespace System.Security.Cryptography.Xml.Tests
Expand Down Expand Up @@ -108,18 +109,6 @@ public void GetInnerXml()
Assert.Null(xnl);
}

private string Stream2String(Stream s)
{
StringBuilder sb = new StringBuilder();
int b = s.ReadByte();
while (b != -1)
{
sb.Append(Convert.ToChar(b));
b = s.ReadByte();
}
return sb.ToString();
}

static string xml = "<Test attrib='at ' xmlns=\"http://www.go-mono.com/\" > \r\n &#xD; <Toto/> text &amp; </Test >";
// GOOD for Stream input
static string c14xml2 = "<Test xmlns=\"http://www.go-mono.com/\" attrib=\"at \"> \n &#xD; <Toto></Toto> text &amp; </Test>";
Expand All @@ -142,7 +131,7 @@ public void LoadInputAsXmlDocument()
XmlDocument doc = GetDoc();
transform.LoadInput(doc);
Stream s = (Stream)transform.GetOutput();
string output = Stream2String(s);
string output = TestHelpers.StreamToString(s, Encoding.UTF8);
Assert.Equal(c14xml3, output);
}

Expand All @@ -154,7 +143,7 @@ public void LoadInputAsXmlNodeList()
// Argument list just contains element Test.
transform.LoadInput(doc.ChildNodes);
Stream s = (Stream)transform.GetOutput();
string output = Stream2String(s);
string output = TestHelpers.StreamToString(s, Encoding.UTF8);
Assert.Equal("<Test></Test>", output);
}

Expand All @@ -167,7 +156,7 @@ public void LoadInputAsXmlNodeList2()
XmlDocument doc = GetDoc();
transform.LoadInput(doc.SelectNodes("//*"));
Stream s = (Stream)transform.GetOutput();
string output = Stream2String(s);
string output = TestHelpers.StreamToString(s, Encoding.UTF8);
string expected = @"<Test><Toto></Toto></Test>";
Assert.Equal(expected, output);
}
Expand All @@ -181,7 +170,7 @@ public void LoadInputAsStream()
ms.Position = 0;
transform.LoadInput(ms);
Stream s = (Stream)transform.GetOutput();
string output = Stream2String(s);
string output = TestHelpers.StreamToString(s, Encoding.UTF8);
Assert.Equal(c14xml2, output);
}

Expand All @@ -202,11 +191,10 @@ public void UnsupportedOutput()
[Fact]
public void C14NSpecExample1()
{
using (TestHelpers.CreateTestDtdFile(GetType().Name + "." + nameof(C14NSpecExample1)))
{
string res = ExecuteXmlDSigC14NTransform(C14NSpecExample1Input);
Assert.Equal(C14NSpecExample1Output, res);
}
XmlPreloadedResolver resolver = new XmlPreloadedResolver();
resolver.Add(new Uri("doc.xsl", UriKind.Relative), "");
string res = ExecuteXmlDSigC14NTransform(C14NSpecExample1Input, resolver);
Assert.Equal(C14NSpecExample1Output, res);
}

[Fact]
Expand All @@ -224,22 +212,22 @@ public void C14NSpecExample3()
}

[Fact]
// [Ignore ("This test should be fine, but it does not pass under MS.NET")]
public void C14NSpecExample4()
{
string res = ExecuteXmlDSigC14NTransform(C14NSpecExample4Input);
Assert.Equal(C14NSpecExample4Output, res);
}

[Fact(Skip = "TODO: fix me")]
[Fact]
public void C14NSpecExample5()
{
string testName = GetType().Name + "." + nameof(C14NSpecExample5);
using (TestHelpers.CreateTestTextFile(testName, "world"))
{
string res = ExecuteXmlDSigC14NTransform(C14NSpecExample5Input(testName));
Assert.Equal(C14NSpecExample5Output, res);
}
//string testName = GetType().Name + "." + nameof(C14NSpecExample5);
//using (TestHelpers.CreateTestTextFile(testName, "world"))
//{
XmlPreloadedResolver resolver = new XmlPreloadedResolver();
resolver.Add(new Uri("file://doc.txt"), "world");
string res = ExecuteXmlDSigC14NTransform(C14NSpecExample5Input, resolver);
Assert.Equal(C14NSpecExample5Output, res);
}

[Fact]
Expand All @@ -249,10 +237,11 @@ public void C14NSpecExample6()
Assert.Equal(C14NSpecExample6Output, res);
}

private string ExecuteXmlDSigC14NTransform(string InputXml)
private string ExecuteXmlDSigC14NTransform(string InputXml, XmlResolver resolver = null)
{
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.XmlResolver = resolver;
doc.LoadXml(InputXml);

// Testing default attribute support with
Expand All @@ -261,12 +250,12 @@ private string ExecuteXmlDSigC14NTransform(string InputXml)
UTF8Encoding utf8 = new UTF8Encoding();
byte[] data = utf8.GetBytes(InputXml.ToString());
Stream stream = new MemoryStream(data);
using (XmlReader reader = XmlReader.Create(stream, new XmlReaderSettings { ValidationType = ValidationType.None, DtdProcessing = DtdProcessing.Parse }))
using (XmlReader reader = XmlReader.Create(stream, new XmlReaderSettings { ValidationType = ValidationType.None, DtdProcessing = DtdProcessing.Parse, XmlResolver = resolver}))
{
doc.Load(reader);

transform.LoadInput(doc);
return Stream2String((Stream)transform.GetOutput());
return TestHelpers.StreamToString((Stream)transform.GetOutput(), utf8);
}
}

Expand All @@ -283,7 +272,6 @@ private string ExecuteXmlDSigC14NTransform(string InputXml)
"<?xml-stylesheet href=\"doc.xsl\"\n" +
" type=\"text/xsl\" ?>\n" +
"\n" +
// "<!DOCTYPE doc SYSTEM \"doc.dtd\">\n" +
"\n" +
"<doc>Hello, world!<!-- Comment 1 --></doc>\n" +
"\n" +
Expand Down Expand Up @@ -401,11 +389,11 @@ private string ExecuteXmlDSigC14NTransform(string InputXml)
// Example 5 from C14N spec - Entity References:
// http://www.w3.org/TR/xml-c14n#Example-Entities
//
static string C14NSpecExample5Input(string worldName) =>
static string C14NSpecExample5Input =>
"<!DOCTYPE doc [\n" +
"<!ATTLIST doc attrExtEnt ENTITY #IMPLIED>\n" +
"<!ENTITY ent1 \"Hello\">\n" +
$"<!ENTITY ent2 SYSTEM \"{worldName}.txt\">\n" +
$"<!ENTITY ent2 SYSTEM \"file://doc.txt\">\n" +
"<!ENTITY entExt SYSTEM \"earth.gif\" NDATA gif>\n" +
"<!NOTATION gif SYSTEM \"viewgif.exe\">\n" +
"]>\n" +
Expand Down Expand Up @@ -453,7 +441,7 @@ public void OrdinalSortForAttributes()

transform.LoadInput(doc);
Stream s = (Stream)transform.GetOutput();
string output = Stream2String(s);
string output = TestHelpers.StreamToString(s, Encoding.UTF8);
Assert.Equal(xml, output);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,15 +133,7 @@ private string ExecuteXmlDSigC14NTransform(string inputXml, Encoding encoding =
doc.Load(reader);
XmlDsigC14NWithCommentsTransform transform = new XmlDsigC14NWithCommentsTransform();
transform.LoadInput(doc);
return Stream2String((Stream) transform.GetOutput(), actualEncoding);
}
}

private string Stream2String(Stream stream, Encoding encoding)
{
using (StreamReader streamReader = new StreamReader(stream, encoding))
{
return streamReader.ReadToEnd();
return TestHelpers.StreamToString((Stream) transform.GetOutput(), actualEncoding);
}
}

Expand Down