我们创建了一个使用下面的方法来生成随机UTF8文本单元测试:C#的XmlWriter和无效的UTF8字符
private static Random _rand = new Random(Environment.TickCount);
public static byte CreateByte()
{
return (byte)_rand.Next(byte.MinValue, byte.MaxValue + 1);
}
public static byte[] CreateByteArray(int length)
{
return Repeat(CreateByte, length).ToArray();
}
public static string CreateUtf8String(int length)
{
return Encoding.UTF8.GetString(CreateByteArray(length));
}
private static IEnumerable<T> Repeat<T>(Func<T> func, int count)
{
for (int i = 0; i < count; i++)
{
yield return func();
}
}
在发送随机UTF8字符串,我们的业务逻辑,的XmlWriter将产生的串并能失败,错误:
Test method UnitTest.Utf8 threw exception:
System.ArgumentException: ' ', hexadecimal value 0x0E, is an invalid character.
System.Xml.XmlUtf8RawTextWriter.InvalidXmlChar(Int32 ch, Byte* pDst, Boolean entitize)
System.Xml.XmlUtf8RawTextWriter.WriteAttributeTextBlock(Char* pSrc, Char* pSrcEnd)
System.Xml.XmlUtf8RawTextWriter.WriteString(String text)
System.Xml.XmlUtf8RawTextWriterIndent.WriteString(String text)
System.Xml.XmlWellFormedWriter.WriteString(String text)
System.Xml.XmlWriter.WriteAttributeString(String localName, String value)
我们想支持任何可能的字符串传入,并需要这些无效字符以某种方式转义。
XmlWriter已经逃脱了像&,<,>等等的东西,我们如何处理其他无效字符,如控制字符等?
PS - 让我知道,如果我们的UTF8发生器是有缺陷的(我已经看到了,我不应该让它产生“\ 0”)
我想我可以在我的随机字节发生器上检查IsXmlChar,并在失败时重试。我认为这是一个很好的解决方案。我们并不担心性能,因为这是单元测试。 – jonathanpeppers 2010-12-09 13:16:04