-Refactor ExceptionAssert

This commit is contained in:
James Newton-King
2014-09-12 21:33:53 +12:00
parent 4b9ce67ab7
commit dfb2ac17a5
43 changed files with 979 additions and 1482 deletions
@@ -419,29 +419,27 @@ namespace Newtonsoft.Json.Tests.Bson
[Test]
public void ReadAsInt32BadString()
{
ExceptionAssert.Throws<JsonReaderException>(
"Could not convert string to integer: a. Path '[0]'.",
() =>
{
byte[] data = HexToBytes("20-00-00-00-02-30-00-02-00-00-00-61-00-02-31-00-02-00-00-00-62-00-02-32-00-02-00-00-00-63-00-00");
ExceptionAssert.Throws<JsonReaderException>(() =>
{
byte[] data = HexToBytes("20-00-00-00-02-30-00-02-00-00-00-61-00-02-31-00-02-00-00-00-62-00-02-32-00-02-00-00-00-63-00-00");
MemoryStream ms = new MemoryStream(data);
BsonReader reader = new BsonReader(ms);
MemoryStream ms = new MemoryStream(data);
BsonReader reader = new BsonReader(ms);
Assert.AreEqual(false, reader.ReadRootValueAsArray);
Assert.AreEqual(DateTimeKind.Local, reader.DateTimeKindHandling);
Assert.AreEqual(false, reader.ReadRootValueAsArray);
Assert.AreEqual(DateTimeKind.Local, reader.DateTimeKindHandling);
reader.ReadRootValueAsArray = true;
reader.DateTimeKindHandling = DateTimeKind.Utc;
reader.ReadRootValueAsArray = true;
reader.DateTimeKindHandling = DateTimeKind.Utc;
Assert.AreEqual(true, reader.ReadRootValueAsArray);
Assert.AreEqual(DateTimeKind.Utc, reader.DateTimeKindHandling);
Assert.AreEqual(true, reader.ReadRootValueAsArray);
Assert.AreEqual(DateTimeKind.Utc, reader.DateTimeKindHandling);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartArray, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartArray, reader.TokenType);
reader.ReadAsInt32();
});
reader.ReadAsInt32();
}, "Could not convert string to integer: a. Path '[0]'.");
}
[Test]
@@ -415,57 +415,53 @@ namespace Newtonsoft.Json.Tests.Bson
[Test]
public void WriteComment()
{
ExceptionAssert.Throws<JsonWriterException>("Cannot write JSON comment as BSON. Path ''.",
() =>
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
ExceptionAssert.Throws<JsonWriterException>(() =>
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartArray();
writer.WriteComment("fail");
});
writer.WriteStartArray();
writer.WriteComment("fail");
}, "Cannot write JSON comment as BSON. Path ''.");
}
[Test]
public void WriteConstructor()
{
ExceptionAssert.Throws<JsonWriterException>("Cannot write JSON constructor as BSON. Path ''.",
() =>
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
ExceptionAssert.Throws<JsonWriterException>(() =>
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartArray();
writer.WriteStartConstructor("fail");
});
writer.WriteStartArray();
writer.WriteStartConstructor("fail");
}, "Cannot write JSON constructor as BSON. Path ''.");
}
[Test]
public void WriteRaw()
{
ExceptionAssert.Throws<JsonWriterException>("Cannot write raw JSON as BSON. Path ''.",
() =>
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
ExceptionAssert.Throws<JsonWriterException>(() =>
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartArray();
writer.WriteRaw("fail");
});
writer.WriteStartArray();
writer.WriteRaw("fail");
}, "Cannot write raw JSON as BSON. Path ''.");
}
[Test]
public void WriteRawValue()
{
ExceptionAssert.Throws<JsonWriterException>("Cannot write raw JSON as BSON. Path ''.",
() =>
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
ExceptionAssert.Throws<JsonWriterException>(() =>
{
MemoryStream ms = new MemoryStream();
BsonWriter writer = new BsonWriter(ms);
writer.WriteStartArray();
writer.WriteRawValue("fail");
});
writer.WriteStartArray();
writer.WriteRawValue("fail");
}, "Cannot write raw JSON as BSON. Path ''.");
}
[Test]
@@ -689,17 +685,16 @@ namespace Newtonsoft.Json.Tests.Bson
[Test]
public void WriteValueOutsideOfObjectOrArray()
{
ExceptionAssert.Throws<JsonWriterException>("Error writing String value. BSON must start with an Object or Array. Path ''.",
() =>
{
MemoryStream stream = new MemoryStream();
ExceptionAssert.Throws<JsonWriterException>(() =>
{
MemoryStream stream = new MemoryStream();
using (BsonWriter writer = new BsonWriter(stream))
{
writer.WriteValue("test");
writer.Flush();
}
});
using (BsonWriter writer = new BsonWriter(stream))
{
writer.WriteValue("test");
writer.Flush();
}
}, "Error writing String value. BSON must start with an Object or Array. Path ''.");
}
[Test]
@@ -757,11 +752,10 @@ namespace Newtonsoft.Json.Tests.Bson
BsonWriter writer = new BsonWriter(ms);
ExceptionAssert.Throws<JsonWriterException>("Error writing Binary value. BSON must start with an Object or Array. Path ''.",
() =>
{
serializer.Serialize(writer, b);
});
ExceptionAssert.Throws<JsonWriterException>(() =>
{
serializer.Serialize(writer, b);
}, "Error writing Binary value. BSON must start with an Object or Array. Path ''.");
}
public class GuidTestClass
@@ -44,8 +44,7 @@ namespace Newtonsoft.Json.Tests.Converters
[Test]
public void DeserializeInvalidDataTable()
{
ExceptionAssert.Throws<JsonException>("Unexpected JSON token when reading DataTable. Expected StartArray, got Integer. Path 'pending_count', line 1, position 19.",
() => JsonConvert.DeserializeObject<DataSet>("{\"pending_count\":23,\"completed_count\":45}"));
ExceptionAssert.Throws<JsonException>(() => JsonConvert.DeserializeObject<DataSet>("{\"pending_count\":23,\"completed_count\":45}"), "Unexpected JSON token when reading DataTable. Expected StartArray, got Integer. Path 'pending_count', line 1, position 19.");
}
[Test]
@@ -81,50 +81,43 @@ namespace Newtonsoft.Json.Tests.Converters
[Test]
public void DeserializeBasicUnion_NoMatch()
{
ExceptionAssert.Throws<JsonSerializationException>("No union type found with the name 'abcdefg'. Path 'Case', line 1, position 17.",
() => JsonConvert.DeserializeObject<Currency>(@"{""Case"":""abcdefg"",""Fields"":[]}"));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<Currency>(@"{""Case"":""abcdefg"",""Fields"":[]}"), "No union type found with the name 'abcdefg'. Path 'Case', line 1, position 17.");
}
[Test]
public void DeserializeBasicUnion_MismatchedFieldCount()
{
ExceptionAssert.Throws<JsonSerializationException>("The number of field values does not match the number of properties definied by union 'AUD'. Path '', line 1, position 27.",
() => JsonConvert.DeserializeObject<Currency>(@"{""Case"":""AUD"",""Fields"":[1]}"));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<Currency>(@"{""Case"":""AUD"",""Fields"":[1]}"), "The number of field values does not match the number of properties definied by union 'AUD'. Path '', line 1, position 27.");
}
[Test]
public void DeserializeBasicUnion_NoCaseName()
{
ExceptionAssert.Throws<JsonSerializationException>("No 'Case' property with union name found. Path '', line 1, position 14.",
() => JsonConvert.DeserializeObject<Currency>(@"{""Fields"":[1]}"));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<Currency>(@"{""Fields"":[1]}"), "No 'Case' property with union name found. Path '', line 1, position 14.");
}
[Test]
public void DeserializeBasicUnion_NoFields()
{
ExceptionAssert.Throws<JsonSerializationException>("No 'Fields' property with union fields found. Path '', line 1, position 14.",
() => JsonConvert.DeserializeObject<Currency>(@"{""Case"":""AUD""}"));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<Currency>(@"{""Case"":""AUD""}"), "No 'Fields' property with union fields found. Path '', line 1, position 14.");
}
[Test]
public void DeserializeBasicUnion_UnexpectedEnd()
{
ExceptionAssert.Throws<JsonSerializationException>("Unexpected end when reading union. Path 'Case', line 1, position 8.",
() => JsonConvert.DeserializeObject<Currency>(@"{""Case"":"));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<Currency>(@"{""Case"":"), "Unexpected end when reading union. Path 'Case', line 1, position 8.");
}
[Test]
public void DeserializeBasicUnion_FieldsObject()
{
ExceptionAssert.Throws<JsonSerializationException>("Union fields must been an array. Path 'Fields', line 1, position 24.",
() => JsonConvert.DeserializeObject<Currency>(@"{""Case"":""AUD"",""Fields"":{}}"));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<Currency>(@"{""Case"":""AUD"",""Fields"":{}}"), "Union fields must been an array. Path 'Fields', line 1, position 24.");
}
[Test]
public void DeserializeBasicUnion_UnexpectedProperty()
{
ExceptionAssert.Throws<JsonSerializationException>("Unexpected property 'Case123' found when reading union. Path 'Case123', line 1, position 11.",
() => JsonConvert.DeserializeObject<Currency>(@"{""Case123"":""AUD""}"));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<Currency>(@"{""Case123"":""AUD""}"), "Unexpected property 'Case123' found when reading union. Path 'Case123', line 1, position 11.");
}
}
}
@@ -224,12 +224,11 @@ namespace Newtonsoft.Json.Tests.Converters
[Test]
public void DeserializeNullToNonNullable()
{
ExceptionAssert.Throws<JsonSerializationException>("Cannot convert null value to System.DateTime. Path 'DateTimeField', line 1, position 38.",
() =>
{
DateTimeTestClass c2 =
JsonConvert.DeserializeObject<DateTimeTestClass>(@"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}", new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
});
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
DateTimeTestClass c2 =
JsonConvert.DeserializeObject<DateTimeTestClass>(@"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}", new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
}, "Cannot convert null value to System.DateTime. Path 'DateTimeField', line 1, position 38.");
}
[Test]
@@ -102,12 +102,11 @@ namespace Newtonsoft.Json.Tests.Converters
[Test]
public void DeserializeNullToNonNullable()
{
ExceptionAssert.Throws<Exception>("Cannot convert null value to System.DateTime. Path 'DateTimeField', line 1, position 38.",
() =>
{
DateTimeTestClass c2 =
JsonConvert.DeserializeObject<DateTimeTestClass>(@"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}", new JavaScriptDateTimeConverter());
});
ExceptionAssert.Throws<Exception>(() =>
{
DateTimeTestClass c2 =
JsonConvert.DeserializeObject<DateTimeTestClass>(@"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}", new JavaScriptDateTimeConverter());
}, "Cannot convert null value to System.DateTime. Path 'DateTimeField', line 1, position 38.");
}
[Test]
@@ -55,8 +55,7 @@ namespace Newtonsoft.Json.Tests.Converters
[Test]
public void DeserializeUnexpectedEnd()
{
ExceptionAssert.Throws<JsonSerializationException>("Unexpected end when reading KeyValuePair. Path 'Key', line 1, position 14.",
() => JsonConvert.DeserializeObject<KeyValuePair<string, int>>(@"{""Key"": ""123"","));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<KeyValuePair<string, int>>(@"{""Key"": ""123"","), "Unexpected end when reading KeyValuePair. Path 'Key', line 1, position 14.");
}
}
}
@@ -104,16 +104,15 @@ namespace Newtonsoft.Json.Tests.Converters
[Test]
public void NamedEnumDuplicateTest()
{
ExceptionAssert.Throws<Exception>("Enum name 'Third' already exists on enum 'NamedEnumDuplicate'.",
() =>
ExceptionAssert.Throws<Exception>(() =>
{
EnumContainer<NamedEnumDuplicate> c = new EnumContainer<NamedEnumDuplicate>
{
EnumContainer<NamedEnumDuplicate> c = new EnumContainer<NamedEnumDuplicate>
{
Enum = NamedEnumDuplicate.First
};
Enum = NamedEnumDuplicate.First
};
JsonConvert.SerializeObject(c, Formatting.Indented, new StringEnumConverter());
});
JsonConvert.SerializeObject(c, Formatting.Indented, new StringEnumConverter());
}, "Enum name 'Third' already exists on enum 'NamedEnumDuplicate'.");
}
[Test]
@@ -347,14 +346,12 @@ namespace Newtonsoft.Json.Tests.Converters
{
string json = "{ \"Value\" : \"Three\" }";
ExceptionAssert.Throws<JsonSerializationException>(
@"Error converting value ""Three"" to type 'Newtonsoft.Json.Tests.Converters.StringEnumConverterTests+MyEnum'. Path 'Value', line 1, position 19.",
() =>
{
var serializer = new JsonSerializer();
serializer.Converters.Add(new StringEnumConverter());
serializer.Deserialize<Bucket>(new JsonTextReader(new StringReader(json)));
});
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
var serializer = new JsonSerializer();
serializer.Converters.Add(new StringEnumConverter());
serializer.Deserialize<Bucket>(new JsonTextReader(new StringReader(json)));
}, @"Error converting value ""Three"" to type 'Newtonsoft.Json.Tests.Converters.StringEnumConverterTests+MyEnum'. Path 'Value', line 1, position 19.");
}
public class Bucket
@@ -881,17 +881,13 @@ namespace Newtonsoft.Json.Tests.Converters
[Test]
public void NoRootObject()
{
ExceptionAssert.Throws<JsonSerializationException>(
"XmlNodeConverter can only convert JSON that begins with an object.",
() => { XmlDocument newDoc = (XmlDocument)JsonConvert.DeserializeXmlNode(@"[1]"); });
ExceptionAssert.Throws<JsonSerializationException>(() => { XmlDocument newDoc = (XmlDocument)JsonConvert.DeserializeXmlNode(@"[1]"); }, "XmlNodeConverter can only convert JSON that begins with an object.");
}
[Test]
public void RootObjectMultipleProperties()
{
ExceptionAssert.Throws<JsonSerializationException>(
"JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.",
() => { XmlDocument newDoc = (XmlDocument)JsonConvert.DeserializeXmlNode(@"{Prop1:1,Prop2:2}"); });
ExceptionAssert.Throws<JsonSerializationException>(() => { XmlDocument newDoc = (XmlDocument)JsonConvert.DeserializeXmlNode(@"{Prop1:1,Prop2:2}"); }, "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.");
}
[Test]
@@ -1007,9 +1003,7 @@ namespace Newtonsoft.Json.Tests.Converters
{
string json = @"{""count"": 773840,""photos"": null}";
ExceptionAssert.Throws<JsonSerializationException>(
"JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.",
() => { JsonConvert.DeserializeXmlNode(json); });
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeXmlNode(json); }, "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.");
}
#if !NET20
@@ -1018,9 +1012,7 @@ namespace Newtonsoft.Json.Tests.Converters
{
string json = @"{""count"": 773840,""photos"": null}";
ExceptionAssert.Throws<JsonSerializationException>(
"JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.",
() => { JsonConvert.DeserializeXNode(json); });
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeXNode(json); }, "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.");
}
#endif
@@ -1481,9 +1473,7 @@ namespace Newtonsoft.Json.Tests.Converters
}
}";
ExceptionAssert.Throws<JsonSerializationException>(
"XmlNodeConverter cannot convert JSON with an empty property name to XML.",
() => { DeserializeXmlNode(json); });
ExceptionAssert.Throws<JsonSerializationException>(() => { DeserializeXmlNode(json); }, "XmlNodeConverter cannot convert JSON with an empty property name to XML.");
}
[Test]
+10 -14
View File
@@ -407,8 +407,7 @@ namespace Newtonsoft.Json.Tests
[Test]
public void ToStringInvalid()
{
ExceptionAssert.Throws<ArgumentException>("Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation.",
() => { JsonConvert.ToString(new Version(1, 0)); });
ExceptionAssert.Throws<ArgumentException>(() => { JsonConvert.ToString(new Version(1, 0)); }, "Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation.");
}
[Test]
@@ -499,18 +498,17 @@ namespace Newtonsoft.Json.Tests
[Test]
public void TestInvalidStrings()
{
ExceptionAssert.Throws<JsonReaderException>("Additional text encountered after finished reading JSON content: t. Path '', line 1, position 19.",
() =>
{
string orig = @"this is a string ""that has quotes"" ";
ExceptionAssert.Throws<JsonReaderException>(() =>
{
string orig = @"this is a string ""that has quotes"" ";
string serialized = JsonConvert.SerializeObject(orig);
string serialized = JsonConvert.SerializeObject(orig);
// *** Make string invalid by stripping \" \"
serialized = serialized.Replace(@"\""", "\"");
// *** Make string invalid by stripping \" \"
serialized = serialized.Replace(@"\""", "\"");
JsonConvert.DeserializeObject<string>(serialized);
});
JsonConvert.DeserializeObject<string>(serialized);
}, "Additional text encountered after finished reading JSON content: t. Path '', line 1, position 19.");
}
[Test]
@@ -1029,9 +1027,7 @@ namespace Newtonsoft.Json.Tests
Assert.AreEqual(typeof(BigInteger), v.Value.GetType());
Assert.AreEqual(BigInteger.Parse(new String('9', 380)), (BigInteger)v.Value);
ExceptionAssert.Throws<JsonReaderException>(
"JSON integer " + new String('9', 381) + " is too large to parse. Path 'biginteger', line 1, position 395.",
() => JObject.Parse(@"{""biginteger"":" + new String('9', 381) + "}"));
ExceptionAssert.Throws<JsonReaderException>(() => JObject.Parse(@"{""biginteger"":" + new String('9', 381) + "}"), "JSON integer " + new String('9', 381) + " is too large to parse. Path 'biginteger', line 1, position 395.");
}
#endif
+77 -175
View File
@@ -132,9 +132,7 @@ third line", jsonTextReader.Value);
Assert.IsTrue(jsonTextReader.Read());
Assert.AreEqual(JsonToken.PropertyName, jsonTextReader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
"JSON integer 333333333333333333333333333333333333333 is too large or small for an Int32. Path 'ChildId', line 2, position 53.",
() => jsonTextReader.ReadAsInt32());
ExceptionAssert.Throws<JsonReaderException>(() => jsonTextReader.ReadAsInt32(), "JSON integer 333333333333333333333333333333333333333 is too large or small for an Int32. Path 'ChildId', line 2, position 53.");
Assert.IsTrue(jsonTextReader.Read());
Assert.AreEqual(JsonToken.EndObject, jsonTextReader.TokenType);
@@ -157,21 +155,13 @@ third line", jsonTextReader.Value);
Assert.IsTrue(jsonTextReader.Read());
Assert.AreEqual(JsonToken.StartArray, jsonTextReader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
"JSON integer 333333333333333333333333333333333333333 is too large or small for an Int32. Path '[0]', line 2, position 42.",
() => jsonTextReader.ReadAsInt32());
ExceptionAssert.Throws<JsonReaderException>(() => jsonTextReader.ReadAsInt32(), "JSON integer 333333333333333333333333333333333333333 is too large or small for an Int32. Path '[0]', line 2, position 42.");
ExceptionAssert.Throws<JsonReaderException>(
"Input string '3.3' is not a valid integer. Path '[1]', line 3, position 6.",
() => jsonTextReader.ReadAsInt32());
ExceptionAssert.Throws<JsonReaderException>(() => jsonTextReader.ReadAsInt32(), "Input string '3.3' is not a valid integer. Path '[1]', line 3, position 6.");
ExceptionAssert.Throws<JsonReaderException>(
"Error reading integer. Unexpected token: Undefined. Path '[2]', line 4, position 3.",
() => jsonTextReader.ReadAsInt32());
ExceptionAssert.Throws<JsonReaderException>(() => jsonTextReader.ReadAsInt32(), "Error reading integer. Unexpected token: Undefined. Path '[2]', line 4, position 3.");
ExceptionAssert.Throws<JsonReaderException>(
"Input string '0f' is not a valid integer. Path '[3]', line 5, position 5.",
() => jsonTextReader.ReadAsInt32());
ExceptionAssert.Throws<JsonReaderException>(() => jsonTextReader.ReadAsInt32(), "Input string '0f' is not a valid integer. Path '[3]', line 5, position 5.");
Assert.IsTrue(jsonTextReader.Read());
Assert.AreEqual(JsonToken.EndArray, jsonTextReader.TokenType);
@@ -240,18 +230,15 @@ third line", jsonTextReader.Value);
JsonTextReader reader = new JsonTextReader(new StringReader(json));
ExceptionAssert.Throws<JsonReaderException>("Unexpected character encountered while parsing number: q. Path '', line 1, position 2.",
() => { reader.Read(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.Read(); }, "Unexpected character encountered while parsing number: q. Path '', line 1, position 2.");
reader = new JsonTextReader(new StringReader(json));
ExceptionAssert.Throws<JsonReaderException>("Unexpected character encountered while parsing number: q. Path '', line 1, position 2.",
() => { reader.ReadAsDecimal(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsDecimal(); }, "Unexpected character encountered while parsing number: q. Path '', line 1, position 2.");
reader = new JsonTextReader(new StringReader(json));
ExceptionAssert.Throws<JsonReaderException>("Unexpected character encountered while parsing number: q. Path '', line 1, position 2.",
() => { reader.ReadAsInt32(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsInt32(); }, "Unexpected character encountered while parsing number: q. Path '', line 1, position 2.");
}
[Test]
@@ -273,8 +260,7 @@ third line", jsonTextReader.Value);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>("Unexpected content while parsing JSON. Path 'u', line 1, position 27.",
() => { reader.Read(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.Read(); }, "Unexpected content while parsing JSON. Path 'u', line 1, position 27.");
}
[Test]
@@ -323,9 +309,7 @@ third line", jsonTextReader.Value);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartArray, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
"Cannot read NaN as a decimal.",
() => reader.Read());
ExceptionAssert.Throws<JsonReaderException>(() => reader.Read(), "Cannot read NaN as a decimal.");
}
[Test]
@@ -515,14 +499,12 @@ third line", jsonTextReader.Value);
JsonTextReader reader = new JsonTextReader(new StringReader(json));
ExceptionAssert.Throws<JsonReaderException>(
"Additional text encountered after finished reading JSON content: ,. Path '', line 5, position 2.",
() =>
ExceptionAssert.Throws<JsonReaderException>(() =>
{
while (reader.Read())
{
while (reader.Read())
{
}
});
}
}, "Additional text encountered after finished reading JSON content: ,. Path '', line 5, position 2.");
}
[Test]
@@ -554,9 +536,7 @@ third line", jsonTextReader.Value);
reader.Read();
Assert.AreEqual(5, reader.LineNumber);
ExceptionAssert.Throws<JsonReaderException>(
"Additional text encountered after finished reading JSON content: c. Path '', line 5, position 2.",
() => { reader.Read(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.Read(); }, "Additional text encountered after finished reading JSON content: c. Path '', line 5, position 2.");
}
[Test]
@@ -583,14 +563,12 @@ third line", jsonTextReader.Value);
JsonTextReader reader = new JsonTextReader(new StringReader(json));
ExceptionAssert.Throws<JsonReaderException>(
"Additional text encountered after finished reading JSON content: a. Path '', line 1, position 5.",
() =>
ExceptionAssert.Throws<JsonReaderException>(() =>
{
while (reader.Read())
{
while (reader.Read())
{
}
});
}
}, "Additional text encountered after finished reading JSON content: a. Path '', line 1, position 5.");
}
[Test]
@@ -817,9 +795,7 @@ third line", jsonTextReader.Value);
{
JsonReader reader = new JsonTextReader(new StringReader("'hi"));
ExceptionAssert.Throws<JsonReaderException>(
"Unterminated string. Expected delimiter: '. Path '', line 1, position 3.",
() => { reader.Read(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.Read(); }, "Unterminated string. Expected delimiter: '. Path '', line 1, position 3.");
}
[Test]
@@ -953,13 +929,11 @@ third line", jsonTextReader.Value);
for (int j = 1; j < 1000; j++)
{
long total = j + i;
ExceptionAssert.Throws<JsonReaderException>(
"JSON integer " + total + " is too large or small for an Int32. Path '', line 1, position 10.",
() =>
{
reader = new JsonTextReader(new StringReader(total.ToString(CultureInfo.InvariantCulture)));
reader.ReadAsInt32();
});
ExceptionAssert.Throws<JsonReaderException>(() =>
{
reader = new JsonTextReader(new StringReader(total.ToString(CultureInfo.InvariantCulture)));
reader.ReadAsInt32();
}, "JSON integer " + total + " is too large or small for an Int32. Path '', line 1, position 10.");
}
}
@@ -976,13 +950,11 @@ third line", jsonTextReader.Value);
for (int j = 1; j < 1000; j++)
{
long total = -j + i;
ExceptionAssert.Throws<JsonReaderException>(
"JSON integer " + total + " is too large or small for an Int32. Path '', line 1, position 11.",
() =>
{
reader = new JsonTextReader(new StringReader(total.ToString(CultureInfo.InvariantCulture)));
reader.ReadAsInt32();
});
ExceptionAssert.Throws<JsonReaderException>(() =>
{
reader = new JsonTextReader(new StringReader(total.ToString(CultureInfo.InvariantCulture)));
reader.ReadAsInt32();
}, "JSON integer " + total + " is too large or small for an Int32. Path '', line 1, position 11.");
}
}
@@ -1075,9 +1047,7 @@ third line", jsonTextReader.Value);
{
JsonReader reader = new JsonTextReader(new StringReader(@"'h\u123"));
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected end while parsing unicode character. Path '', line 1, position 4.",
() => { reader.Read(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.Read(); }, "Unexpected end while parsing unicode character. Path '', line 1, position 4.");
}
[Test]
@@ -1085,9 +1055,7 @@ third line", jsonTextReader.Value);
{
JsonReader reader = new JsonTextReader(new StringReader(@"'h\"));
ExceptionAssert.Throws<JsonReaderException>(
"Unterminated string. Expected delimiter: '. Path '', line 1, position 3.",
() => { reader.Read(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.Read(); }, "Unterminated string. Expected delimiter: '. Path '', line 1, position 3.");
}
[Test]
@@ -1095,9 +1063,7 @@ third line", jsonTextReader.Value);
{
JsonReader reader = new JsonTextReader(new StringReader(@"true"));
ExceptionAssert.Throws<JsonReaderException>(
"Error reading bytes. Unexpected token: Boolean. Path '', line 1, position 4.",
() => { reader.ReadAsBytes(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsBytes(); }, "Error reading bytes. Unexpected token: Boolean. Path '', line 1, position 4.");
}
[Test]
@@ -1108,9 +1074,7 @@ third line", jsonTextReader.Value);
JsonReader reader = new JsonTextReader(new StringReader(@"'" + Convert.ToBase64String(helloWorldData)));
ExceptionAssert.Throws<JsonReaderException>(
"Unterminated string. Expected delimiter: '. Path '', line 1, position 17.",
() => { reader.ReadAsBytes(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsBytes(); }, "Unterminated string. Expected delimiter: '. Path '', line 1, position 17.");
}
[Test]
@@ -1129,9 +1093,7 @@ third line", jsonTextReader.Value);
JsonReader reader = new JsonTextReader(new StringReader(@"{aww"));
Assert.IsTrue(reader.Read());
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected end while parsing unquoted property name. Path '', line 1, position 4.",
() => { reader.Read(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.Read(); }, "Unexpected end while parsing unquoted property name. Path '', line 1, position 4.");
}
[Test]
@@ -1383,22 +1345,22 @@ third line", jsonTextReader.Value);
Assert.AreEqual(int.MinValue, reader.ReadAsInt32());
reader = new JsonTextReader(new StringReader(long.MaxValue.ToString()));
ExceptionAssert.Throws<JsonReaderException>("JSON integer 9223372036854775807 is too large or small for an Int32. Path '', line 1, position 19.", () => reader.ReadAsInt32());
ExceptionAssert.Throws<JsonReaderException>(() => reader.ReadAsInt32(), "JSON integer 9223372036854775807 is too large or small for an Int32. Path '', line 1, position 19.");
reader = new JsonTextReader(new StringReader("9999999999999999999999999999999999999999999999999999999999999999999999999999asdasdasd"));
ExceptionAssert.Throws<JsonReaderException>("Unexpected character encountered while parsing number: s. Path '', line 1, position 77.", () => reader.ReadAsInt32());
ExceptionAssert.Throws<JsonReaderException>(() => reader.ReadAsInt32(), "Unexpected character encountered while parsing number: s. Path '', line 1, position 77.");
reader = new JsonTextReader(new StringReader("1E-06"));
ExceptionAssert.Throws<JsonReaderException>("Input string '1E-06' is not a valid integer. Path '', line 1, position 5.", () => reader.ReadAsInt32());
ExceptionAssert.Throws<JsonReaderException>(() => reader.ReadAsInt32(), "Input string '1E-06' is not a valid integer. Path '', line 1, position 5.");
reader = new JsonTextReader(new StringReader("1.1"));
ExceptionAssert.Throws<JsonReaderException>("Input string '1.1' is not a valid integer. Path '', line 1, position 3.", () => reader.ReadAsInt32());
ExceptionAssert.Throws<JsonReaderException>(() => reader.ReadAsInt32(), "Input string '1.1' is not a valid integer. Path '', line 1, position 3.");
reader = new JsonTextReader(new StringReader(""));
Assert.AreEqual(null, reader.ReadAsInt32());
reader = new JsonTextReader(new StringReader("-"));
ExceptionAssert.Throws<JsonReaderException>("Input string '-' is not a valid integer. Path '', line 1, position 1.", () => reader.ReadAsInt32());
ExceptionAssert.Throws<JsonReaderException>(() => reader.ReadAsInt32(), "Input string '-' is not a valid integer. Path '', line 1, position 1.");
}
[Test]
@@ -1419,11 +1381,11 @@ third line", jsonTextReader.Value);
Assert.AreEqual(0, reader.ReadAsDecimal());
reader = new JsonTextReader(new StringReader("9999999999999999999999999999999999999999999999999999999999999999999999999999asdasdasd"));
ExceptionAssert.Throws<JsonReaderException>("Unexpected character encountered while parsing number: s. Path '', line 1, position 77.", () => reader.ReadAsDecimal());
ExceptionAssert.Throws<JsonReaderException>(() => reader.ReadAsDecimal(), "Unexpected character encountered while parsing number: s. Path '', line 1, position 77.");
reader = new JsonTextReader(new StringReader("9999999999999999999999999999999999999999999999999999999999999999999999999999asdasdasd"));
reader.FloatParseHandling = Json.FloatParseHandling.Decimal;
ExceptionAssert.Throws<JsonReaderException>("Unexpected character encountered while parsing number: s. Path '', line 1, position 77.", () => reader.Read());
ExceptionAssert.Throws<JsonReaderException>(() => reader.Read(), "Unexpected character encountered while parsing number: s. Path '', line 1, position 77.");
reader = new JsonTextReader(new StringReader("1E-06"));
Assert.AreEqual(0.000001m, reader.ReadAsDecimal());
@@ -1432,7 +1394,7 @@ third line", jsonTextReader.Value);
Assert.AreEqual(null, reader.ReadAsDecimal());
reader = new JsonTextReader(new StringReader("-"));
ExceptionAssert.Throws<JsonReaderException>("Input string '-' is not a valid decimal. Path '', line 1, position 1.", () => reader.ReadAsDecimal());
ExceptionAssert.Throws<JsonReaderException>(() => reader.ReadAsDecimal(), "Input string '-' is not a valid decimal. Path '', line 1, position 1.");
}
[Test]
@@ -1461,7 +1423,7 @@ third line", jsonTextReader.Value);
Assert.AreEqual(-0.0d, reader.Value);
reader = new JsonTextReader(new StringReader("9999999999999999999999999999999999999999999999999999999999999999999999999999asdasdasd"));
ExceptionAssert.Throws<JsonReaderException>("Unexpected character encountered while parsing number: s. Path '', line 1, position 77.", () => reader.Read());
ExceptionAssert.Throws<JsonReaderException>(() => reader.Read(), "Unexpected character encountered while parsing number: s. Path '', line 1, position 77.");
reader = new JsonTextReader(new StringReader("1E-06"));
Assert.IsTrue(reader.Read());
@@ -1472,7 +1434,7 @@ third line", jsonTextReader.Value);
Assert.IsFalse(reader.Read());
reader = new JsonTextReader(new StringReader("-"));
ExceptionAssert.Throws<JsonReaderException>("Input string '-' is not a valid number. Path '', line 1, position 1.", () => reader.Read());
ExceptionAssert.Throws<JsonReaderException>(() => reader.Read(), "Input string '-' is not a valid number. Path '', line 1, position 1.");
}
[Test]
@@ -1723,9 +1685,7 @@ third line", jsonTextReader.Value);
reader.Read();
Assert.AreEqual(JsonToken.Boolean, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
@"Invalid character after parsing property name. Expected ':' but got: "". Path 'A', line 3, position 9.",
() => { reader.Read(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.Read(); }, @"Invalid character after parsing property name. Expected ':' but got: "". Path 'A', line 3, position 9.");
}
[Test]
@@ -1835,9 +1795,7 @@ third line", jsonTextReader.Value);
reader.Read();
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected character encountered while parsing value: }. Path '', line 1, position 1.",
() => { reader.Read(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.Read(); }, "Unexpected character encountered while parsing value: }. Path '', line 1, position 1.");
}
[Test]
@@ -1863,9 +1821,7 @@ third line", jsonTextReader.Value);
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"{"));
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected end when reading bytes. Path '', line 1, position 1.",
() => { reader.ReadAsBytes(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsBytes(); }, "Unexpected end when reading bytes. Path '', line 1, position 1.");
}
#if !NET20
@@ -1884,9 +1840,7 @@ third line", jsonTextReader.Value);
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"new Date()"));
ExceptionAssert.Throws<JsonReaderException>(
"Error reading decimal. Unexpected token: StartConstructor. Path '', line 1, position 9.",
() => { reader.ReadAsDecimal(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsDecimal(); }, "Error reading decimal. Unexpected token: StartConstructor. Path '', line 1, position 9.");
}
[Test]
@@ -1894,9 +1848,7 @@ third line", jsonTextReader.Value);
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"new Date()"));
ExceptionAssert.Throws<JsonReaderException>(
"Error reading bytes. Unexpected token: StartConstructor. Path '', line 1, position 9.",
() => { reader.ReadAsBytes(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsBytes(); }, "Error reading bytes. Unexpected token: StartConstructor. Path '', line 1, position 9.");
}
#if !NET20
@@ -1905,9 +1857,7 @@ third line", jsonTextReader.Value);
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"new Date()"));
ExceptionAssert.Throws<JsonReaderException>(
"Error reading date. Unexpected token: StartConstructor. Path '', line 1, position 9.",
() => { reader.ReadAsDateTimeOffset(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsDateTimeOffset(); }, "Error reading date. Unexpected token: StartConstructor. Path '', line 1, position 9.");
}
#endif
@@ -1927,9 +1877,7 @@ third line", jsonTextReader.Value);
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"[1"));
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected end when reading bytes. Path '[0]', line 1, position 2.",
() => { reader.ReadAsBytes(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsBytes(); }, "Unexpected end when reading bytes. Path '[0]', line 1, position 2.");
}
[Test]
@@ -1937,9 +1885,7 @@ third line", jsonTextReader.Value);
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"[1.0]"));
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected token when reading bytes: Float. Path '[0]', line 1, position 4.",
() => { reader.ReadAsBytes(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsBytes(); }, "Unexpected token when reading bytes: Float. Path '[0]', line 1, position 4.");
}
[Test]
@@ -2048,9 +1994,7 @@ third line", jsonTextReader.Value);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
"Could not convert string to DateTimeOffset: blablahbla. Path 'Offset', line 1, position 22.",
() => { reader.ReadAsDateTimeOffset(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsDateTimeOffset(); }, "Could not convert string to DateTimeOffset: blablahbla. Path 'Offset', line 1, position 22.");
}
[Test]
@@ -2202,9 +2146,7 @@ third line", jsonTextReader.Value);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
"Input string '1.1' is not a valid integer. Path 'Name', line 1, position 12.",
() => { reader.ReadAsInt32(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsInt32(); }, "Input string '1.1' is not a valid integer. Path 'Name', line 1, position 12.");
}
[Test]
@@ -2212,9 +2154,7 @@ third line", jsonTextReader.Value);
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"nul"));
ExceptionAssert.Throws<JsonReaderException>(
"Error parsing null value. Path '', line 0, position 0.",
() => { reader.Read(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.Read(); }, "Error parsing null value. Path '', line 0, position 0.");
}
[Test]
@@ -2222,9 +2162,7 @@ third line", jsonTextReader.Value);
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"nulz"));
ExceptionAssert.Throws<JsonReaderException>(
"Error parsing null value. Path '', line 0, position 0.",
() => { reader.Read(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.Read(); }, "Error parsing null value. Path '', line 0, position 0.");
}
[Test]
@@ -2232,9 +2170,7 @@ third line", jsonTextReader.Value);
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"nullz"));
ExceptionAssert.Throws<JsonReaderException>(
"Error parsing null value. Path '', line 1, position 4.",
() => { reader.Read(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.Read(); }, "Error parsing null value. Path '', line 1, position 4.");
}
[Test]
@@ -2242,9 +2178,7 @@ third line", jsonTextReader.Value);
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"/* sdf"));
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected end while parsing comment. Path '', line 1, position 6.",
() => { reader.Read(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.Read(); }, "Unexpected end while parsing comment. Path '', line 1, position 6.");
}
[Test]
@@ -2252,9 +2186,7 @@ third line", jsonTextReader.Value);
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"/sdf"));
ExceptionAssert.Throws<JsonReaderException>(
"Error parsing comment. Expected: *, got s. Path '', line 1, position 1.",
() => { reader.Read(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.Read(); }, "Error parsing comment. Expected: *, got s. Path '', line 1, position 1.");
}
[Test]
@@ -2486,9 +2418,7 @@ third line", jsonTextReader.Value);
string json = "new Dat";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected end while parsing constructor. Path '', line 1, position 7.",
() => { reader.Read(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.Read(); }, "Unexpected end while parsing constructor. Path '', line 1, position 7.");
}
[Test]
@@ -2497,9 +2427,7 @@ third line", jsonTextReader.Value);
string json = "new Date !";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected character while parsing constructor: !. Path '', line 1, position 9.",
() => { reader.Read(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.Read(); }, "Unexpected character while parsing constructor: !. Path '', line 1, position 9.");
}
[Test]
@@ -2545,9 +2473,7 @@ third line", jsonTextReader.Value);
{
JsonTextReader reader = new JsonTextReader(new StringReader("true/"));
ExceptionAssert.Throws<JsonReaderException>(
"Error parsing boolean value. Path '', line 1, position 4.",
() => { reader.Read(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.Read(); }, "Error parsing boolean value. Path '', line 1, position 4.");
}
[Test]
@@ -2569,9 +2495,7 @@ third line", jsonTextReader.Value);
string json = "new Date,()";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected character while parsing constructor: ,. Path '', line 1, position 8.",
() => { Assert.IsTrue(reader.Read()); });
ExceptionAssert.Throws<JsonReaderException>(() => { Assert.IsTrue(reader.Read()); }, "Unexpected character while parsing constructor: ,. Path '', line 1, position 8.");
}
[Test]
@@ -2834,9 +2758,7 @@ null//comment
JsonTextReader reader = new JsonTextReader(new StreamReader(new SlowStream(json, new UTF8Encoding(false), 1)));
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected end while parsing comment. Path '', line 1, position 1.",
() => { reader.Read(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.Read(); }, "Unexpected end while parsing comment. Path '', line 1, position 1.");
}
[Test]
@@ -2896,9 +2818,7 @@ null//comment
Assert.IsTrue(reader.Read());
Assert.IsTrue(reader.Read());
ExceptionAssert.Throws<JsonReaderException>(
"Additional text encountered after finished reading JSON content: }. Path '', line 1, position 2.",
() => { reader.Read(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.Read(); }, "Additional text encountered after finished reading JSON content: }. Path '', line 1, position 2.");
}
[Test]
@@ -2981,9 +2901,7 @@ null//comment
Assert.IsTrue(reader.Read());
ExceptionAssert.Throws<JsonReaderException>(
"The reader's MaxDepth of 1 has been exceeded. Path '[0]', line 1, position 2.",
() => { Assert.IsTrue(reader.Read()); });
ExceptionAssert.Throws<JsonReaderException>(() => { Assert.IsTrue(reader.Read()); }, "The reader's MaxDepth of 1 has been exceeded. Path '[0]', line 1, position 2.");
}
[Test]
@@ -2999,9 +2917,7 @@ null//comment
Assert.IsTrue(reader.Read());
Assert.AreEqual(0, reader.Depth);
ExceptionAssert.Throws<JsonReaderException>(
"The reader's MaxDepth of 1 has been exceeded. Path '[0]', line 1, position 2.",
() => { Assert.IsTrue(reader.Read()); });
ExceptionAssert.Throws<JsonReaderException>(() => { Assert.IsTrue(reader.Read()); }, "The reader's MaxDepth of 1 has been exceeded. Path '[0]', line 1, position 2.");
Assert.AreEqual(1, reader.Depth);
Assert.IsTrue(reader.Read());
@@ -3019,9 +2935,7 @@ null//comment
Assert.IsTrue(reader.Read());
Assert.AreEqual(1, reader.Depth);
ExceptionAssert.Throws<JsonReaderException>(
"The reader's MaxDepth of 1 has been exceeded. Path '[1]', line 1, position 9.",
() => { Assert.IsTrue(reader.Read()); });
ExceptionAssert.Throws<JsonReaderException>(() => { Assert.IsTrue(reader.Read()); }, "The reader's MaxDepth of 1 has been exceeded. Path '[1]', line 1, position 9.");
Assert.AreEqual(1, reader.Depth);
Assert.IsTrue(reader.Read());
@@ -3179,12 +3093,8 @@ null//comment
toggleReaderError.Error = true;
ExceptionAssert.Throws<Exception>(
"Read error",
() => jsonTextReader.Read());
ExceptionAssert.Throws<Exception>(
"Read error",
() => jsonTextReader.Read());
ExceptionAssert.Throws<Exception>(() => jsonTextReader.Read(), "Read error");
ExceptionAssert.Throws<Exception>(() => jsonTextReader.Read(), "Read error");
toggleReaderError.Error = false;
@@ -3193,9 +3103,7 @@ null//comment
toggleReaderError.Error = true;
ExceptionAssert.Throws<Exception>(
"Read error",
() => jsonTextReader.Read());
ExceptionAssert.Throws<Exception>(() => jsonTextReader.Read(), "Read error");
toggleReaderError.Error = false;
@@ -3204,15 +3112,9 @@ null//comment
toggleReaderError.Error = true;
ExceptionAssert.Throws<Exception>(
"Read error",
() => jsonTextReader.Read());
ExceptionAssert.Throws<Exception>(
"Read error",
() => jsonTextReader.Read());
ExceptionAssert.Throws<Exception>(
"Read error",
() => jsonTextReader.Read());
ExceptionAssert.Throws<Exception>(() => jsonTextReader.Read(), "Read error");
ExceptionAssert.Throws<Exception>(() => jsonTextReader.Read(), "Read error");
ExceptionAssert.Throws<Exception>(() => jsonTextReader.Read(), "Read error");
toggleReaderError.Error = false;
+31 -37
View File
@@ -236,18 +236,16 @@ namespace Newtonsoft.Json.Tests
[Test]
public void WriteValueObjectWithUnsupportedValue()
{
ExceptionAssert.Throws<JsonWriterException>(
@"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation. Path ''.",
() =>
ExceptionAssert.Throws<JsonWriterException>(() =>
{
StringWriter sw = new StringWriter();
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
StringWriter sw = new StringWriter();
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(new Version(1, 1, 1, 1));
jsonWriter.WriteEndArray();
}
});
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(new Version(1, 1, 1, 1));
jsonWriter.WriteEndArray();
}
}, @"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation. Path ''.");
}
[Test]
@@ -823,41 +821,37 @@ namespace Newtonsoft.Json.Tests
[Test]
public void BadWriteEndArray()
{
ExceptionAssert.Throws<JsonWriterException>(
"No token to close. Path ''.",
() =>
ExceptionAssert.Throws<JsonWriterException>(() =>
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
jsonWriter.WriteStartArray();
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue(0.0);
jsonWriter.WriteValue(0.0);
jsonWriter.WriteEndArray();
jsonWriter.WriteEndArray();
}
});
jsonWriter.WriteEndArray();
jsonWriter.WriteEndArray();
}
}, "No token to close. Path ''.");
}
[Test]
public void InvalidQuoteChar()
{
ExceptionAssert.Throws<ArgumentException>(
@"Invalid JavaScript string quote character. Valid quote characters are ' and "".",
() =>
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
ExceptionAssert.Throws<ArgumentException>(() =>
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.QuoteChar = '*';
}
});
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.QuoteChar = '*';
}
}, @"Invalid JavaScript string quote character. Valid quote characters are ' and "".");
}
[Test]
@@ -400,19 +400,18 @@ namespace Newtonsoft.Json.Tests
[Test]
public void ThrowExceptionWhenNoValidationEventHandler()
{
ExceptionAssert.Throws<JsonSchemaException>("Integer 10 exceeds maximum value of 5. Line 1, position 2.",
() =>
{
string schemaJson = @"{
ExceptionAssert.Throws<JsonSchemaException>(() =>
{
string schemaJson = @"{
""type"":""integer"",
""maximum"":5
}";
JsonValidatingReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader("10")));
reader.Schema = JsonSchema.Parse(schemaJson);
JsonValidatingReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader("10")));
reader.Schema = JsonSchema.Parse(schemaJson);
Assert.IsTrue(reader.Read());
});
Assert.IsTrue(reader.Read());
}, "Integer 10 exceeds maximum value of 5. Line 1, position 2.");
}
[Test]
@@ -1621,18 +1620,17 @@ namespace Newtonsoft.Json.Tests
[Test]
public void ReadAsInt32Failure()
{
ExceptionAssert.Throws<JsonSchemaException>("Integer 5 exceeds maximum value of 2. Line 1, position 1.",
() =>
{
JsonSchema s = new JsonSchemaGenerator().Generate(typeof(int));
s.Maximum = 2;
ExceptionAssert.Throws<JsonSchemaException>(() =>
{
JsonSchema s = new JsonSchemaGenerator().Generate(typeof(int));
s.Maximum = 2;
JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"5")))
{
Schema = s
};
reader.ReadAsInt32();
});
JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"5")))
{
Schema = s
};
reader.ReadAsInt32();
}, "Integer 5 exceeds maximum value of 2. Line 1, position 1.");
}
[Test]
@@ -1652,18 +1650,17 @@ namespace Newtonsoft.Json.Tests
[Test]
public void ReadAsDecimalFailure()
{
ExceptionAssert.Throws<JsonSchemaException>("Float 5.5 is not evenly divisible by 1. Line 1, position 3.",
() =>
{
JsonSchema s = new JsonSchemaGenerator().Generate(typeof(decimal));
s.DivisibleBy = 1;
ExceptionAssert.Throws<JsonSchemaException>(() =>
{
JsonSchema s = new JsonSchemaGenerator().Generate(typeof(decimal));
s.DivisibleBy = 1;
JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"5.5")))
{
Schema = s
};
reader.ReadAsDecimal();
});
JsonReader reader = new JsonValidatingReader(new JsonTextReader(new StringReader(@"5.5")))
{
Schema = s
};
reader.ReadAsDecimal();
}, "Float 5.5 is not evenly divisible by 1. Line 1, position 3.");
}
[Test]
@@ -133,14 +133,12 @@ namespace Newtonsoft.Json.Tests.Linq
[Test]
public void JObjectPropertyNameWithNonToken()
{
ExceptionAssert.Throws<ArgumentException>(
"Could not determine JSON object type for type System.String[].",
() =>
{
dynamic d = new JObject();
ExceptionAssert.Throws<ArgumentException>(() =>
{
dynamic d = new JObject();
d.First = new[] { "One", "II", "3" };
});
d.First = new[] { "One", "II", "3" };
}, "Could not determine JSON object type for type System.String[].");
}
[Test]
+22 -46
View File
@@ -127,10 +127,8 @@ namespace Newtonsoft.Json.Tests.Linq
{
JArray j = new JArray();
ExceptionAssert.Throws<ArgumentNullException>(
@"Value cannot be null.
Parameter name: array",
() => { ((ICollection<JToken>)j).CopyTo(null, 0); });
ExceptionAssert.Throws<ArgumentNullException>(() => { ((ICollection<JToken>)j).CopyTo(null, 0); }, @"Value cannot be null.
Parameter name: array");
}
[Test]
@@ -138,10 +136,8 @@ Parameter name: array",
{
JArray j = new JArray();
ExceptionAssert.Throws<ArgumentOutOfRangeException>(
@"arrayIndex is less than 0.
Parameter name: arrayIndex",
() => { ((ICollection<JToken>)j).CopyTo(new JToken[1], -1); });
ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => { ((ICollection<JToken>)j).CopyTo(new JToken[1], -1); }, @"arrayIndex is less than 0.
Parameter name: arrayIndex");
}
[Test]
@@ -149,9 +145,7 @@ Parameter name: arrayIndex",
{
JArray j = new JArray();
ExceptionAssert.Throws<ArgumentException>(
@"arrayIndex is equal to or greater than the length of array.",
() => { ((ICollection<JToken>)j).CopyTo(new JToken[1], 1); });
ExceptionAssert.Throws<ArgumentException>(() => { ((ICollection<JToken>)j).CopyTo(new JToken[1], 1); }, @"arrayIndex is equal to or greater than the length of array.");
}
[Test]
@@ -162,9 +156,7 @@ Parameter name: arrayIndex",
j.Add(new JValue(2));
j.Add(new JValue(3));
ExceptionAssert.Throws<ArgumentException>(
@"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.",
() => { ((ICollection<JToken>)j).CopyTo(new JToken[3], 1); });
ExceptionAssert.Throws<ArgumentException>(() => { ((ICollection<JToken>)j).CopyTo(new JToken[3], 1); }, @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.");
}
[Test]
@@ -240,10 +232,8 @@ Parameter name: arrayIndex",
{
JArray j = new JArray();
ExceptionAssert.Throws<ArgumentOutOfRangeException>(
@"Index is equal to or greater than Count.
Parameter name: index",
() => { j.RemoveAt(0); });
ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => { j.RemoveAt(0); }, @"Index is equal to or greater than Count.
Parameter name: index");
}
[Test]
@@ -251,10 +241,8 @@ Parameter name: index",
{
JArray j = new JArray();
ExceptionAssert.Throws<ArgumentOutOfRangeException>(
@"Index is less than 0.
Parameter name: index",
() => { j.RemoveAt(-1); });
ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => { j.RemoveAt(-1); }, @"Index is less than 0.
Parameter name: index");
}
[Test]
@@ -332,10 +320,8 @@ Parameter name: index",
{
JArray j = new JArray();
ExceptionAssert.Throws<ArgumentOutOfRangeException>(
@"Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index",
() => { j.Insert(-1, new JValue(1)); });
ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => { j.Insert(-1, new JValue(1)); }, @"Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index");
}
[Test]
@@ -343,10 +329,8 @@ Parameter name: index",
{
JArray j = new JArray();
ExceptionAssert.Throws<ArgumentOutOfRangeException>(
@"Index must be within the bounds of the List.
Parameter name: index",
() => { j.Insert(2, new JValue(1)); });
ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => { j.Insert(2, new JValue(1)); }, @"Index must be within the bounds of the List.
Parameter name: index");
}
[Test]
@@ -376,9 +360,7 @@ Parameter name: index",
{
string json = @"{""prop"":""value""}";
ExceptionAssert.Throws<JsonReaderException>(
"Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1.",
() => { JArray.Parse(json); });
ExceptionAssert.Throws<JsonReaderException>(() => { JArray.Parse(json); }, "Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1.");
}
public class ListItemFields
@@ -481,13 +463,11 @@ Parameter name: index",
[Test]
public void SetValueWithInvalidIndex()
{
ExceptionAssert.Throws<ArgumentException>(
@"Set JArray values with invalid key value: ""badvalue"". Array position index expected.",
() =>
{
JArray a = new JArray();
a["badvalue"] = new JValue(3);
});
ExceptionAssert.Throws<ArgumentException>(() =>
{
JArray a = new JArray();
a["badvalue"] = new JValue(3);
}, @"Set JArray values with invalid key value: ""badvalue"". Array position index expected.");
}
[Test]
@@ -518,9 +498,7 @@ Parameter name: index",
[Test]
public void ParseIncomplete()
{
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected end of content while loading JArray. Path '[0]', line 1, position 2.",
() => { JArray.Parse("[1"); });
ExceptionAssert.Throws<JsonReaderException>(() => { JArray.Parse("[1"); }, "Unexpected end of content while loading JArray. Path '[0]', line 1, position 2.");
}
[Test]
@@ -544,9 +522,7 @@ Parameter name: index",
""Large""
], 987987";
ExceptionAssert.Throws<JsonReaderException>(
"Additional text encountered after finished reading JSON content: ,. Path '', line 5, position 2.",
() => { JArray.Parse(json); });
ExceptionAssert.Throws<JsonReaderException>(() => { JArray.Parse(json); }, "Additional text encountered after finished reading JSON content: ,. Path '', line 5, position 2.");
}
[Test]
@@ -84,12 +84,11 @@ namespace Newtonsoft.Json.Tests.Linq
[Test]
public void SetValueWithInvalidIndex()
{
ExceptionAssert.Throws<ArgumentException>(@"Set JConstructor values with invalid key value: ""badvalue"". Argument position index expected.",
() =>
{
JConstructor c = new JConstructor();
c["badvalue"] = new JValue(3);
});
ExceptionAssert.Throws<ArgumentException>(() =>
{
JConstructor c = new JConstructor();
c["badvalue"] = new JValue(3);
}, @"Set JConstructor values with invalid key value: ""badvalue"". Argument position index expected.");
}
[Test]
+162 -203
View File
@@ -194,14 +194,12 @@ namespace Newtonsoft.Json.Tests.Linq
[Test]
public void DuplicatePropertyNameShouldThrow()
{
ExceptionAssert.Throws<ArgumentException>(
"Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.",
() =>
{
JObject o = new JObject();
o.Add("PropertyNameValue", null);
o.Add("PropertyNameValue", null);
});
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
o.Add("PropertyNameValue", null);
o.Add("PropertyNameValue", null);
}, "Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.");
}
[Test]
@@ -308,55 +306,47 @@ namespace Newtonsoft.Json.Tests.Linq
[Test]
public void GenericCollectionCopyToNullArrayShouldThrow()
{
ExceptionAssert.Throws<ArgumentException>(
@"Value cannot be null.
Parameter name: array",
() =>
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(null, 0);
});
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(null, 0);
}, @"Value cannot be null.
Parameter name: array");
}
[Test]
public void GenericCollectionCopyToNegativeArrayIndexShouldThrow()
{
ExceptionAssert.Throws<ArgumentOutOfRangeException>(
@"arrayIndex is less than 0.
Parameter name: arrayIndex",
() =>
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], -1);
});
ExceptionAssert.Throws<ArgumentOutOfRangeException>(() =>
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], -1);
}, @"arrayIndex is less than 0.
Parameter name: arrayIndex");
}
[Test]
public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow()
{
ExceptionAssert.Throws<ArgumentException>(
@"arrayIndex is equal to or greater than the length of array.",
() =>
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], 1);
});
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], 1);
}, @"arrayIndex is equal to or greater than the length of array.");
}
[Test]
public void GenericCollectionCopyToInsufficientArrayCapacity()
{
ExceptionAssert.Throws<ArgumentException>(
@"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.",
() =>
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
o.Add("PropertyNameValue3", new JValue(3));
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
o.Add("PropertyNameValue3", new JValue(3));
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1);
});
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1);
}, @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.");
}
[Test]
@@ -442,12 +432,11 @@ Parameter name: arrayIndex",
[Test]
public void Parse_ShouldThrowOnUnexpectedToken()
{
ExceptionAssert.Throws<JsonReaderException>("Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.",
() =>
{
string json = @"[""prop""]";
JObject.Parse(json);
});
ExceptionAssert.Throws<JsonReaderException>(() =>
{
string json = @"[""prop""]";
JObject.Parse(json);
}, "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.");
}
[Test]
@@ -478,12 +467,10 @@ Parameter name: arrayIndex",
[Test]
public void Blog()
{
ExceptionAssert.Throws<JsonReaderException>(
"Invalid property identifier character: ]. Path 'name', line 3, position 5.",
() => { JObject.Parse(@"{
ExceptionAssert.Throws<JsonReaderException>(() => { JObject.Parse(@"{
""name"": ""James"",
]!#$THIS IS: BAD JSON![{}}}}]
}"); });
}"); }, "Invalid property identifier character: ]. Path 'name', line 3, position 5.");
}
[Test]
@@ -890,48 +877,42 @@ Parameter name: arrayIndex",
[Test]
public void IListAddBadToken()
{
ExceptionAssert.Throws<ArgumentException>(
"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.",
() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
l.Add(new JValue("Bad!"));
});
l.Add(new JValue("Bad!"));
}, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.");
}
[Test]
public void IListAddBadValue()
{
ExceptionAssert.Throws<ArgumentException>(
"Argument is not a JToken.",
() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
l.Add("Bad!");
});
l.Add("Bad!");
}, "Argument is not a JToken.");
}
[Test]
public void IListAddPropertyWithExistingName()
{
ExceptionAssert.Throws<ArgumentException>(
"Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.",
() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test2", "II");
JProperty p3 = new JProperty("Test2", "II");
l.Add(p3);
});
l.Add(p3);
}, "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.");
}
[Test]
@@ -1024,34 +1005,30 @@ Parameter name: arrayIndex",
[Test]
public void IListSetItemAlreadyExists()
{
ExceptionAssert.Throws<ArgumentException>(
"Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.",
() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
l[1] = p3;
});
l[0] = p3;
l[1] = p3;
}, "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.");
}
[Test]
public void IListSetItemInvalid()
{
ExceptionAssert.Throws<ArgumentException>(
@"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.",
() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
l[0] = new JValue(true);
});
l[0] = new JValue(true);
}, @"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.");
}
[Test]
@@ -1140,46 +1117,43 @@ Parameter name: arrayIndex",
[Test]
public void GenericListJTokenAddBadToken()
{
ExceptionAssert.Throws<ArgumentException>("Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.",
() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
l.Add(new JValue("Bad!"));
});
l.Add(new JValue("Bad!"));
}, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.");
}
[Test]
public void GenericListJTokenAddBadValue()
{
ExceptionAssert.Throws<ArgumentException>("Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.",
() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
// string is implicitly converted to JValue
l.Add("Bad!");
});
// string is implicitly converted to JValue
l.Add("Bad!");
}, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.");
}
[Test]
public void GenericListJTokenAddPropertyWithExistingName()
{
ExceptionAssert.Throws<ArgumentException>("Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.",
() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test2", "II");
JProperty p3 = new JProperty("Test2", "II");
l.Add(p3);
});
l.Add(p3);
}, "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.");
}
[Test]
@@ -1265,18 +1239,17 @@ Parameter name: arrayIndex",
[Test]
public void GenericListJTokenSetItemAlreadyExists()
{
ExceptionAssert.Throws<ArgumentException>("Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.",
() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
l[1] = p3;
});
l[0] = p3;
l[1] = p3;
}, "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.");
}
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
@@ -1347,25 +1320,21 @@ Parameter name: arrayIndex",
[Test]
public void IBindingListApplySort()
{
ExceptionAssert.Throws<NotSupportedException>(
"Specified method is not supported.",
() =>
{
IBindingList l = new JObject();
l.ApplySort(null, ListSortDirection.Ascending);
});
ExceptionAssert.Throws<NotSupportedException>(() =>
{
IBindingList l = new JObject();
l.ApplySort(null, ListSortDirection.Ascending);
}, "Specified method is not supported.");
}
[Test]
public void IBindingListRemoveSort()
{
ExceptionAssert.Throws<NotSupportedException>(
"Specified method is not supported.",
() =>
{
IBindingList l = new JObject();
l.RemoveSort();
});
ExceptionAssert.Throws<NotSupportedException>(() =>
{
IBindingList l = new JObject();
l.RemoveSort();
}, "Specified method is not supported.");
}
[Test]
@@ -1379,13 +1348,11 @@ Parameter name: arrayIndex",
[Test]
public void IBindingListFind()
{
ExceptionAssert.Throws<NotSupportedException>(
"Specified method is not supported.",
() =>
{
IBindingList l = new JObject();
l.Find(null, null);
});
ExceptionAssert.Throws<NotSupportedException>(() =>
{
IBindingList l = new JObject();
l.Find(null, null);
}, "Specified method is not supported.");
}
[Test]
@@ -1398,13 +1365,11 @@ Parameter name: arrayIndex",
[Test]
public void IBindingListAddNew()
{
ExceptionAssert.Throws<JsonException>(
"Could not determine new value to add to 'Newtonsoft.Json.Linq.JObject'.",
() =>
{
IBindingList l = new JObject();
l.AddNew();
});
ExceptionAssert.Throws<JsonException>(() =>
{
IBindingList l = new JObject();
l.AddNew();
}, "Could not determine new value to add to 'Newtonsoft.Json.Linq.JObject'.");
}
[Test]
@@ -1579,12 +1544,11 @@ Parameter name: arrayIndex",
[Test]
public void SetValueWithInvalidPropertyName()
{
ExceptionAssert.Throws<ArgumentException>("Set JObject values with invalid key value: 0. Object property name expected.",
() =>
{
JObject o = new JObject();
o[0] = new JValue(3);
});
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
o[0] = new JValue(3);
}, "Set JObject values with invalid key value: 0. Object property name expected.");
}
[Test]
@@ -1635,44 +1599,41 @@ Parameter name: arrayIndex",
[Test]
public void InvalidValueCastExceptionMessage()
{
ExceptionAssert.Throws<ArgumentException>("Can not convert Object to String.",
() =>
{
string json = @"{
ExceptionAssert.Throws<ArgumentException>(() =>
{
string json = @"{
""responseData"": {},
""responseDetails"": null,
""responseStatus"": 200
}";
JObject o = JObject.Parse(json);
JObject o = JObject.Parse(json);
string name = (string)o["responseData"];
});
string name = (string)o["responseData"];
}, "Can not convert Object to String.");
}
[Test]
public void InvalidPropertyValueCastExceptionMessage()
{
ExceptionAssert.Throws<ArgumentException>("Can not convert Object to String.",
() =>
{
string json = @"{
ExceptionAssert.Throws<ArgumentException>(() =>
{
string json = @"{
""responseData"": {},
""responseDetails"": null,
""responseStatus"": 200
}";
JObject o = JObject.Parse(json);
JObject o = JObject.Parse(json);
string name = (string)o.Property("responseData");
});
string name = (string)o.Property("responseData");
}, "Can not convert Object to String.");
}
[Test]
public void ParseIncomplete()
{
ExceptionAssert.Throws<Exception>("Unexpected end of content while loading JObject. Path 'foo', line 1, position 6.",
() => { JObject.Parse("{ foo:"); });
ExceptionAssert.Throws<Exception>(() => { JObject.Parse("{ foo:"); }, "Unexpected end of content while loading JObject. Path 'foo', line 1, position 6.");
}
[Test]
@@ -1707,25 +1668,24 @@ Parameter name: arrayIndex",
[Test]
public void LoadFromNestedObjectIncomplete()
{
ExceptionAssert.Throws<JsonReaderException>("Unexpected end of content while loading JObject. Path 'short.error.code', line 6, position 15.",
() =>
{
string jsonText = @"{
ExceptionAssert.Throws<JsonReaderException>(() =>
{
string jsonText = @"{
""short"":
{
""error"":
{
""code"":0";
JsonReader reader = new JsonTextReader(new StringReader(jsonText));
reader.Read();
reader.Read();
reader.Read();
reader.Read();
reader.Read();
JsonReader reader = new JsonTextReader(new StringReader(jsonText));
reader.Read();
reader.Read();
reader.Read();
reader.Read();
reader.Read();
JToken.ReadFrom(reader);
});
JToken.ReadFrom(reader);
}, "Unexpected end of content while loading JObject. Path 'short.error.code', line 6, position 15.");
}
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
@@ -1806,10 +1766,9 @@ Parameter name: arrayIndex",
[Test]
public void ParseAdditionalContent()
{
ExceptionAssert.Throws<JsonReaderException>("Additional text encountered after finished reading JSON content: ,. Path '', line 10, position 2.",
() =>
{
string json = @"{
ExceptionAssert.Throws<JsonReaderException>(() =>
{
string json = @"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
@@ -1820,8 +1779,8 @@ Parameter name: arrayIndex",
]
}, 987987";
JObject o = JObject.Parse(json);
});
JObject o = JObject.Parse(json);
}, "Additional text encountered after finished reading JSON content: ,. Path '', line 10, position 2.");
}
[Test]
@@ -99,9 +99,7 @@ namespace Newtonsoft.Json.Tests.Linq
JProperty p = new JProperty("TestProperty", null);
IList l = p;
ExceptionAssert.Throws<JsonException>(
"Cannot add or remove items from Newtonsoft.Json.Linq.JProperty.",
() => { l.Clear(); });
ExceptionAssert.Throws<JsonException>(() => { l.Clear(); }, "Cannot add or remove items from Newtonsoft.Json.Linq.JProperty.");
}
[Test]
@@ -110,9 +108,7 @@ namespace Newtonsoft.Json.Tests.Linq
JProperty p = new JProperty("TestProperty", null);
IList l = p;
ExceptionAssert.Throws<JsonException>(
"Newtonsoft.Json.Linq.JProperty cannot have multiple values.",
() => { l.Add(null); });
ExceptionAssert.Throws<JsonException>(() => { l.Add(null); }, "Newtonsoft.Json.Linq.JProperty cannot have multiple values.");
}
[Test]
@@ -121,9 +117,7 @@ namespace Newtonsoft.Json.Tests.Linq
JProperty p = new JProperty("TestProperty", null);
IList l = p;
ExceptionAssert.Throws<JsonException>(
"Cannot add or remove items from Newtonsoft.Json.Linq.JProperty.",
() => { l.Remove(p.Value); });
ExceptionAssert.Throws<JsonException>(() => { l.Remove(p.Value); }, "Cannot add or remove items from Newtonsoft.Json.Linq.JProperty.");
}
[Test]
@@ -132,9 +126,7 @@ namespace Newtonsoft.Json.Tests.Linq
JProperty p = new JProperty("TestProperty", null);
IList l = p;
ExceptionAssert.Throws<JsonException>(
"Cannot add or remove items from Newtonsoft.Json.Linq.JProperty.",
() => { l.RemoveAt(0); });
ExceptionAssert.Throws<JsonException>(() => { l.RemoveAt(0); }, "Cannot add or remove items from Newtonsoft.Json.Linq.JProperty.");
}
[Test]
@@ -223,9 +215,7 @@ namespace Newtonsoft.Json.Tests.Linq
{
IList<JToken> t = new JProperty("error", new List<string> { "one", "two" });
ExceptionAssert.Throws<JsonException>(
"Newtonsoft.Json.Linq.JProperty cannot have multiple values.",
() => { t.Add(1); });
ExceptionAssert.Throws<JsonException>(() => { t.Add(1); }, "Newtonsoft.Json.Linq.JProperty cannot have multiple values.");
}
}
}
@@ -49,14 +49,12 @@ namespace Newtonsoft.Json.Tests.Linq
{
JObject json = JObject.Parse(@"{""IntList"":[1, ""two""]}");
ExceptionAssert.Throws<Exception>(
"Could not convert string to integer: two. Path 'IntList[1]', line 1, position 20.",
() =>
{
JsonSerializer serializer = new JsonSerializer();
ExceptionAssert.Throws<Exception>(() =>
{
JsonSerializer serializer = new JsonSerializer();
serializer.Deserialize<TraceTestObject>(json.CreateReader());
});
serializer.Deserialize<TraceTestObject>(json.CreateReader());
}, "Could not convert string to integer: two. Path 'IntList[1]', line 1, position 20.");
}
#if !NET20
@@ -152,9 +150,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
"Could not convert string to DateTimeOffset: blablahbla. Path 'Offset', line 1, position 22.",
() => { reader.ReadAsDateTimeOffset(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsDateTimeOffset(); }, "Could not convert string to DateTimeOffset: blablahbla. Path 'Offset', line 1, position 22.");
}
[Test]
@@ -172,9 +168,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
"Error reading date. Unexpected token: Boolean. Path 'Offset', line 1, position 14.",
() => { reader.ReadAsDateTimeOffset(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsDateTimeOffset(); }, "Error reading date. Unexpected token: Boolean. Path 'Offset', line 1, position 14.");
}
[Test]
@@ -320,27 +314,25 @@ namespace Newtonsoft.Json.Tests.Linq
[Test]
public void ReadBytesFailure()
{
ExceptionAssert.Throws<JsonReaderException>(
"Error reading bytes. Unexpected token: Integer. Path 'Test1'.",
() =>
ExceptionAssert.Throws<JsonReaderException>(() =>
{
JObject o =
new JObject(
new JProperty("Test1", 1)
);
using (JTokenReader jsonReader = new JTokenReader(o))
{
JObject o =
new JObject(
new JProperty("Test1", 1)
);
jsonReader.Read();
Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType);
using (JTokenReader jsonReader = new JTokenReader(o))
{
jsonReader.Read();
Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType);
jsonReader.Read();
Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType);
Assert.AreEqual("Test1", jsonReader.Value);
jsonReader.Read();
Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType);
Assert.AreEqual("Test1", jsonReader.Value);
jsonReader.ReadAsBytes();
}
});
jsonReader.ReadAsBytes();
}
}, "Error reading bytes. Unexpected token: Integer. Path 'Test1'.");
}
public class HasBytes
@@ -504,9 +496,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
"Could not convert string to integer: hi. Path 'Name', line 1, position 12.",
() => { reader.ReadAsInt32(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsInt32(); }, "Could not convert string to integer: hi. Path 'Name', line 1, position 12.");
}
[Test]
@@ -524,9 +514,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
"Error reading integer. Unexpected token: Boolean. Path 'Name', line 1, position 12.",
() => { reader.ReadAsInt32(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsInt32(); }, "Error reading integer. Unexpected token: Boolean. Path 'Name', line 1, position 12.");
}
[Test]
@@ -565,9 +553,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
"Could not convert string to decimal: blah. Path 'Name', line 1, position 14.",
() => { reader.ReadAsDecimal(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsDecimal(); }, "Could not convert string to decimal: blah. Path 'Name', line 1, position 14.");
}
[Test]
@@ -585,9 +571,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
"Error reading decimal. Unexpected token: Boolean. Path 'Name', line 1, position 12.",
() => { reader.ReadAsDecimal(); });
ExceptionAssert.Throws<JsonReaderException>(() => { reader.ReadAsDecimal(); }, "Error reading decimal. Unexpected token: Boolean. Path 'Name', line 1, position 12.");
}
[Test]
+59 -63
View File
@@ -386,67 +386,67 @@ namespace Newtonsoft.Json.Tests.Linq
[Test]
public void FailedCasting()
{
ExceptionAssert.Throws<ArgumentException>("Can not convert Boolean to DateTime.", () => { var i = (DateTime)new JValue(true); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Integer to DateTime.", () => { var i = (DateTime)new JValue(1); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Float to DateTime.", () => { var i = (DateTime)new JValue(1.1); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Float to DateTime.", () => { var i = (DateTime)new JValue(1.1m); });
ExceptionAssert.Throws<ArgumentException>("Can not convert TimeSpan to DateTime.", () => { var i = (DateTime)new JValue(TimeSpan.Zero); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Uri to DateTime.", () => { var i = (DateTime)new JValue(new Uri("http://www.google.com")); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Null to DateTime.", () => { var i = (DateTime)JValue.CreateNull(); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Guid to DateTime.", () => { var i = (DateTime)new JValue(Guid.NewGuid()); });
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(true); }, "Can not convert Boolean to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(1); }, "Can not convert Integer to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(1.1); }, "Can not convert Float to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(1.1m); }, "Can not convert Float to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(TimeSpan.Zero); }, "Can not convert TimeSpan to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(new Uri("http://www.google.com")); }, "Can not convert Uri to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)JValue.CreateNull(); }, "Can not convert Null to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(Guid.NewGuid()); }, "Can not convert Guid to DateTime.");
ExceptionAssert.Throws<ArgumentException>("Can not convert Boolean to Uri.", () => { var i = (Uri)new JValue(true); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Integer to Uri.", () => { var i = (Uri)new JValue(1); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Float to Uri.", () => { var i = (Uri)new JValue(1.1); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Float to Uri.", () => { var i = (Uri)new JValue(1.1m); });
ExceptionAssert.Throws<ArgumentException>("Can not convert TimeSpan to Uri.", () => { var i = (Uri)new JValue(TimeSpan.Zero); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Guid to Uri.", () => { var i = (Uri)new JValue(Guid.NewGuid()); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Date to Uri.", () => { var i = (Uri)new JValue(DateTime.Now); });
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(true); }, "Can not convert Boolean to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(1); }, "Can not convert Integer to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(1.1); }, "Can not convert Float to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(1.1m); }, "Can not convert Float to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(TimeSpan.Zero); }, "Can not convert TimeSpan to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(Guid.NewGuid()); }, "Can not convert Guid to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(DateTime.Now); }, "Can not convert Date to Uri.");
#if !NET20
ExceptionAssert.Throws<ArgumentException>("Can not convert Date to Uri.", () => { var i = (Uri)new JValue(DateTimeOffset.Now); });
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(DateTimeOffset.Now); }, "Can not convert Date to Uri.");
#endif
ExceptionAssert.Throws<ArgumentException>("Can not convert Boolean to TimeSpan.", () => { var i = (TimeSpan)new JValue(true); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Integer to TimeSpan.", () => { var i = (TimeSpan)new JValue(1); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Float to TimeSpan.", () => { var i = (TimeSpan)new JValue(1.1); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Float to TimeSpan.", () => { var i = (TimeSpan)new JValue(1.1m); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Null to TimeSpan.", () => { var i = (TimeSpan)JValue.CreateNull(); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Guid to TimeSpan.", () => { var i = (TimeSpan)new JValue(Guid.NewGuid()); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Date to TimeSpan.", () => { var i = (TimeSpan)new JValue(DateTime.Now); });
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(true); }, "Can not convert Boolean to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(1); }, "Can not convert Integer to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(1.1); }, "Can not convert Float to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(1.1m); }, "Can not convert Float to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)JValue.CreateNull(); }, "Can not convert Null to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(Guid.NewGuid()); }, "Can not convert Guid to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(DateTime.Now); }, "Can not convert Date to TimeSpan.");
#if !NET20
ExceptionAssert.Throws<ArgumentException>("Can not convert Date to TimeSpan.", () => { var i = (TimeSpan)new JValue(DateTimeOffset.Now); });
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(DateTimeOffset.Now); }, "Can not convert Date to TimeSpan.");
#endif
ExceptionAssert.Throws<ArgumentException>("Can not convert Uri to TimeSpan.", () => { var i = (TimeSpan)new JValue(new Uri("http://www.google.com")); });
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(new Uri("http://www.google.com")); }, "Can not convert Uri to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>("Can not convert Boolean to Guid.", () => { var i = (Guid)new JValue(true); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Integer to Guid.", () => { var i = (Guid)new JValue(1); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Float to Guid.", () => { var i = (Guid)new JValue(1.1); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Float to Guid.", () => { var i = (Guid)new JValue(1.1m); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Null to Guid.", () => { var i = (Guid)JValue.CreateNull(); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Date to Guid.", () => { var i = (Guid)new JValue(DateTime.Now); });
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(true); }, "Can not convert Boolean to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(1); }, "Can not convert Integer to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(1.1); }, "Can not convert Float to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(1.1m); }, "Can not convert Float to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)JValue.CreateNull(); }, "Can not convert Null to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(DateTime.Now); }, "Can not convert Date to Guid.");
#if !NET20
ExceptionAssert.Throws<ArgumentException>("Can not convert Date to Guid.", () => { var i = (Guid)new JValue(DateTimeOffset.Now); });
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(DateTimeOffset.Now); }, "Can not convert Date to Guid.");
#endif
ExceptionAssert.Throws<ArgumentException>("Can not convert TimeSpan to Guid.", () => { var i = (Guid)new JValue(TimeSpan.FromMinutes(1)); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Uri to Guid.", () => { var i = (Guid)new JValue(new Uri("http://www.google.com")); });
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(TimeSpan.FromMinutes(1)); }, "Can not convert TimeSpan to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(new Uri("http://www.google.com")); }, "Can not convert Uri to Guid.");
#if !NET20
ExceptionAssert.Throws<ArgumentException>("Can not convert Boolean to DateTimeOffset.", () => { var i = (DateTimeOffset)new JValue(true); });
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTimeOffset)new JValue(true); }, "Can not convert Boolean to DateTimeOffset.");
#endif
ExceptionAssert.Throws<ArgumentException>("Can not convert Boolean to Uri.", () => { var i = (Uri)new JValue(true); });
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(true); }, "Can not convert Boolean to Uri.");
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
ExceptionAssert.Throws<ArgumentException>("Can not convert Uri to BigInteger.", () => { var i = (new JValue(new Uri("http://www.google.com"))).ToObject<BigInteger>(); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Null to BigInteger.", () => { var i = (JValue.CreateNull()).ToObject<BigInteger>(); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Guid to BigInteger.", () => { var i = (new JValue(Guid.NewGuid())).ToObject<BigInteger>(); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Guid to BigInteger.", () => { var i = (new JValue(Guid.NewGuid())).ToObject<BigInteger?>(); });
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue(new Uri("http://www.google.com"))).ToObject<BigInteger>(); }, "Can not convert Uri to BigInteger.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (JValue.CreateNull()).ToObject<BigInteger>(); }, "Can not convert Null to BigInteger.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue(Guid.NewGuid())).ToObject<BigInteger>(); }, "Can not convert Guid to BigInteger.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue(Guid.NewGuid())).ToObject<BigInteger?>(); }, "Can not convert Guid to BigInteger.");
#endif
ExceptionAssert.Throws<ArgumentException>("Can not convert Date to SByte.", () => { var i = (sbyte?)new JValue(DateTime.Now); });
ExceptionAssert.Throws<ArgumentException>("Can not convert Date to SByte.", () => { var i = (sbyte)new JValue(DateTime.Now); });
ExceptionAssert.Throws<ArgumentException>(() => { var i = (sbyte?)new JValue(DateTime.Now); }, "Can not convert Date to SByte.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (sbyte)new JValue(DateTime.Now); }, "Can not convert Date to SByte.");
ExceptionAssert.Throws<ArgumentException>("Could not convert 'Ordinal1' to StringComparison.", () => { var i = (new JValue("Ordinal1")).ToObject<StringComparison>(); });
ExceptionAssert.Throws<ArgumentException>("Could not convert 'Ordinal1' to StringComparison.", () => { var i = (new JValue("Ordinal1")).ToObject<StringComparison?>(); });
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue("Ordinal1")).ToObject<StringComparison>(); }, "Could not convert 'Ordinal1' to StringComparison.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue("Ordinal1")).ToObject<StringComparison?>(); }, "Could not convert 'Ordinal1' to StringComparison.");
}
[Test]
@@ -790,24 +790,21 @@ namespace Newtonsoft.Json.Tests.Linq
[Test]
public void AddPropertyToArray()
{
ExceptionAssert.Throws<ArgumentException>("Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArray.",
() =>
{
JArray a = new JArray();
a.Add(new JProperty("PropertyName"));
});
ExceptionAssert.Throws<ArgumentException>(() =>
{
JArray a = new JArray();
a.Add(new JProperty("PropertyName"));
}, "Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArray.");
}
[Test]
public void AddValueToObject()
{
ExceptionAssert.Throws<ArgumentException>(
"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.",
() =>
{
JObject o = new JObject();
o.Add(5);
});
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
o.Add(5);
}, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.");
}
[Test]
@@ -1004,17 +1001,16 @@ namespace Newtonsoft.Json.Tests.Linq
[Test]
public void ParseAdditionalContent()
{
ExceptionAssert.Throws<JsonReaderException>("Additional text encountered after finished reading JSON content: ,. Path '', line 5, position 2.",
() =>
{
string json = @"[
ExceptionAssert.Throws<JsonReaderException>(() =>
{
string json = @"[
""Small"",
""Medium"",
""Large""
],";
JToken.Parse(json);
});
JToken.Parse(json);
}, "Additional text encountered after finished reading JSON content: ,. Path '', line 5, position 2.");
}
[Test]
+35 -42
View File
@@ -233,12 +233,11 @@ namespace Newtonsoft.Json.Tests.Linq
[Test]
public void Last()
{
ExceptionAssert.Throws<InvalidOperationException>("Cannot access child value on Newtonsoft.Json.Linq.JValue.",
() =>
{
JValue v = new JValue(true);
JToken last = v.Last;
});
ExceptionAssert.Throws<InvalidOperationException>(() =>
{
JValue v = new JValue(true);
JToken last = v.Last;
}, "Cannot access child value on Newtonsoft.Json.Linq.JValue.");
}
[Test]
@@ -252,45 +251,41 @@ namespace Newtonsoft.Json.Tests.Linq
[Test]
public void First()
{
ExceptionAssert.Throws<InvalidOperationException>("Cannot access child value on Newtonsoft.Json.Linq.JValue.",
() =>
{
JValue v = new JValue(true);
JToken first = v.First;
});
ExceptionAssert.Throws<InvalidOperationException>(() =>
{
JValue v = new JValue(true);
JToken first = v.First;
}, "Cannot access child value on Newtonsoft.Json.Linq.JValue.");
}
[Test]
public void Item()
{
ExceptionAssert.Throws<InvalidOperationException>("Cannot access child value on Newtonsoft.Json.Linq.JValue.",
() =>
{
JValue v = new JValue(true);
JToken first = v[0];
});
ExceptionAssert.Throws<InvalidOperationException>(() =>
{
JValue v = new JValue(true);
JToken first = v[0];
}, "Cannot access child value on Newtonsoft.Json.Linq.JValue.");
}
[Test]
public void Values()
{
ExceptionAssert.Throws<InvalidOperationException>("Cannot access child value on Newtonsoft.Json.Linq.JValue.",
() =>
{
JValue v = new JValue(true);
v.Values<int>();
});
ExceptionAssert.Throws<InvalidOperationException>(() =>
{
JValue v = new JValue(true);
v.Values<int>();
}, "Cannot access child value on Newtonsoft.Json.Linq.JValue.");
}
[Test]
public void RemoveParentNull()
{
ExceptionAssert.Throws<InvalidOperationException>("The parent is missing.",
() =>
{
JValue v = new JValue(true);
v.Remove();
});
ExceptionAssert.Throws<InvalidOperationException>(() =>
{
JValue v = new JValue(true);
v.Remove();
}, "The parent is missing.");
}
[Test]
@@ -331,23 +326,21 @@ namespace Newtonsoft.Json.Tests.Linq
[Test]
public void SetValue()
{
ExceptionAssert.Throws<InvalidOperationException>("Cannot set child value on Newtonsoft.Json.Linq.JValue.",
() =>
{
JToken t = new JValue(5L);
t[0] = new JValue(3);
});
ExceptionAssert.Throws<InvalidOperationException>(() =>
{
JToken t = new JValue(5L);
t[0] = new JValue(3);
}, "Cannot set child value on Newtonsoft.Json.Linq.JValue.");
}
[Test]
public void CastNullValueToNonNullable()
{
ExceptionAssert.Throws<ArgumentException>("Can not convert Null to Int32.",
() =>
{
JValue v = JValue.CreateNull();
int i = (int)v;
});
ExceptionAssert.Throws<ArgumentException>(() =>
{
JValue v = JValue.CreateNull();
int i = (int)v;
}, "Can not convert Null to Int32.");
}
[Test]
@@ -204,9 +204,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(
@"Index 1 not valid on JObject.",
() => { o.SelectToken("[1]", true); });
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[1]", true); }, @"Index 1 not valid on JObject.");
}
[Test]
@@ -215,9 +213,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(
@"Index * not valid on JObject.",
() => { o.SelectToken("[*]", true); });
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[*]", true); }, @"Index * not valid on JObject.");
}
[Test]
@@ -226,9 +222,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(
@"Array slice is not valid on JObject.",
() => { o.SelectToken("[:]", true); });
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[:]", true); }, @"Array slice is not valid on JObject.");
}
[Test]
@@ -245,9 +239,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(
@"Path returned multiple tokens.",
() => { a.SelectToken("[0, 1]"); });
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[0, 1]"); }, @"Path returned multiple tokens.");
}
[Test]
@@ -255,9 +247,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(
@"Property 'BlahBlah' not valid on JArray.",
() => { a.SelectToken("BlahBlah", true); });
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("BlahBlah", true); }, @"Property 'BlahBlah' not valid on JArray.");
}
[Test]
@@ -265,9 +255,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(
@"Index 9 outside the bounds of JArray.",
() => { a.SelectToken("[9,10]", true); });
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[9,10]", true); }, @"Index 9 outside the bounds of JArray.");
}
[Test]
@@ -275,9 +263,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
{
JConstructor c = new JConstructor("Blah");
ExceptionAssert.Throws<JsonException>(
@"Index 1 outside the bounds of JConstructor.",
() => { c.SelectToken("[1]", true); });
ExceptionAssert.Throws<JsonException>(() => { c.SelectToken("[1]", true); }, @"Index 1 outside the bounds of JConstructor.");
}
[Test]
@@ -294,9 +280,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(
"Property 'Missing' does not exist on JObject.",
() => { o.SelectToken("Missing", true); });
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("Missing", true); }, "Property 'Missing' does not exist on JObject.");
}
[Test]
@@ -315,9 +299,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
JObject o = new JObject(
new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(
"Property 'Missing' does not exist on JObject.",
() => { o.SelectToken("['Missing','Missing2']", true); });
ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("['Missing','Missing2']", true); }, "Property 'Missing' does not exist on JObject.");
}
[Test]
@@ -325,9 +307,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(
"Properties 'Missing', 'Missing2' not valid on JArray.",
() => { a.SelectToken("['Missing','Missing2']", true); });
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("['Missing','Missing2']", true); }, "Properties 'Missing', 'Missing2' not valid on JArray.");
}
[Test]
@@ -335,23 +315,15 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(
"Array slice of 99 to * returned no results.",
() => { a.SelectToken("[99:]", true); });
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[99:]", true); }, "Array slice of 99 to * returned no results.");
ExceptionAssert.Throws<JsonException>(
"Array slice of 1 to -19 returned no results.",
() => { a.SelectToken("[1:-19]", true); });
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[1:-19]", true); }, "Array slice of 1 to -19 returned no results.");
ExceptionAssert.Throws<JsonException>(
"Array slice of * to -19 returned no results.",
() => { a.SelectToken("[:-19]", true); });
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[:-19]", true); }, "Array slice of * to -19 returned no results.");
a = new JArray();
ExceptionAssert.Throws<JsonException>(
"Array slice of * to * returned no results.",
() => { a.SelectToken("[:]", true); });
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[:]", true); }, "Array slice of * to * returned no results.");
}
[Test]
@@ -368,9 +340,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
{
JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(
"Index 1000 outside the bounds of JArray.",
() => { a.SelectToken("[1000].Ha", true); });
ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[1000].Ha", true); }, "Index 1000 outside the bounds of JArray.");
}
[Test]
@@ -104,25 +104,19 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
[Test]
public void RootWithBadWhitespace()
{
ExceptionAssert.Throws<JsonException>(
@"Unexpected character while parsing path: ",
() => { new JPath("$ .Blah"); });
ExceptionAssert.Throws<JsonException>(() => { new JPath("$ .Blah"); }, @"Unexpected character while parsing path: ");
}
[Test]
public void NoFieldNameAfterDot()
{
ExceptionAssert.Throws<JsonException>(
@"Unexpected end while parsing path.",
() => { new JPath("$.Blah."); });
ExceptionAssert.Throws<JsonException>(() => { new JPath("$.Blah."); }, @"Unexpected end while parsing path.");
}
[Test]
public void RootWithBadWhitespace2()
{
ExceptionAssert.Throws<JsonException>(
@"Unexpected character while parsing path: ",
() => { new JPath("$. Blah"); });
ExceptionAssert.Throws<JsonException>(() => { new JPath("$. Blah"); }, @"Unexpected character while parsing path: ");
}
[Test]
@@ -273,9 +267,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
[Test]
public void SinglePropertyAndFilterWithUnknownEscape()
{
ExceptionAssert.Throws<JsonException>(
@"Unknown escape chracter: \i",
() => { new JPath(@"Blah[ ?( @.name=='h\i' ) ]"); });
ExceptionAssert.Throws<JsonException>(() => { new JPath(@"Blah[ ?( @.name=='h\i' ) ]"); }, @"Unknown escape chracter: \i");
}
[Test]
@@ -425,57 +417,49 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
[Test]
public void BadOr1()
{
ExceptionAssert.Throws<JsonException>("Unexpected character while parsing path query: )",
() => new JPath("[?(@.name||)]"));
ExceptionAssert.Throws<JsonException>(() => new JPath("[?(@.name||)]"), "Unexpected character while parsing path query: )");
}
[Test]
public void BaddOr2()
{
ExceptionAssert.Throws<JsonException>("Unexpected character while parsing path query: |",
() => new JPath("[?(@.name|)]"));
ExceptionAssert.Throws<JsonException>(() => new JPath("[?(@.name|)]"), "Unexpected character while parsing path query: |");
}
[Test]
public void BaddOr3()
{
ExceptionAssert.Throws<JsonException>("Unexpected character while parsing path query: |",
() => new JPath("[?(@.name|"));
ExceptionAssert.Throws<JsonException>(() => new JPath("[?(@.name|"), "Unexpected character while parsing path query: |");
}
[Test]
public void BaddOr4()
{
ExceptionAssert.Throws<JsonException>("Path ended with open query.",
() => new JPath("[?(@.name||"));
ExceptionAssert.Throws<JsonException>(() => new JPath("[?(@.name||"), "Path ended with open query.");
}
[Test]
public void NoAtAfterOr()
{
ExceptionAssert.Throws<JsonException>("Unexpected character while parsing path query: s",
() => new JPath("[?(@.name||s"));
ExceptionAssert.Throws<JsonException>(() => new JPath("[?(@.name||s"), "Unexpected character while parsing path query: s");
}
[Test]
public void NoPathAfterAt()
{
ExceptionAssert.Throws<JsonException>(@"Path ended with open query.",
() => new JPath("[?(@.name||@"));
ExceptionAssert.Throws<JsonException>(() => new JPath("[?(@.name||@"), @"Path ended with open query.");
}
[Test]
public void NoPathAfterDot()
{
ExceptionAssert.Throws<JsonException>(@"Unexpected end while parsing path.",
() => new JPath("[?(@.name||@."));
ExceptionAssert.Throws<JsonException>(() => new JPath("[?(@.name||@."), @"Unexpected end while parsing path.");
}
[Test]
public void NoPathAfterDot2()
{
ExceptionAssert.Throws<JsonException>(@"Unexpected end while parsing path.",
() => new JPath("[?(@.name||@.)]"));
ExceptionAssert.Throws<JsonException>(() => new JPath("[?(@.name||@.)]"), @"Unexpected end while parsing path.");
}
[Test]
@@ -502,17 +486,13 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
[Test]
public void BadCharactersInIndexer()
{
ExceptionAssert.Throws<JsonException>(
@"Unexpected character while parsing path indexer: [",
() => { new JPath("Blah[[0]].Two.Three[1].Four"); });
ExceptionAssert.Throws<JsonException>(() => { new JPath("Blah[[0]].Two.Three[1].Four"); }, @"Unexpected character while parsing path indexer: [");
}
[Test]
public void UnclosedIndexer()
{
ExceptionAssert.Throws<JsonException>(
@"Path ended with open indexer.",
() => { new JPath("Blah[0"); });
ExceptionAssert.Throws<JsonException>(() => { new JPath("Blah[0"); }, @"Path ended with open indexer.");
}
[Test]
@@ -634,17 +614,13 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
[Test]
public void EmptyIndexer()
{
ExceptionAssert.Throws<JsonException>(
"Array index expected.",
() => { new JPath("[]"); });
ExceptionAssert.Throws<JsonException>(() => { new JPath("[]"); }, "Array index expected.");
}
[Test]
public void IndexerCloseInProperty()
{
ExceptionAssert.Throws<JsonException>(
"Unexpected character while parsing path: ]",
() => { new JPath("]"); });
ExceptionAssert.Throws<JsonException>(() => { new JPath("]"); }, "Unexpected character while parsing path: ]");
}
[Test]
@@ -661,9 +637,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
[Test]
public void MissingDotAfterIndexer()
{
ExceptionAssert.Throws<JsonException>(
"Unexpected character following indexer: B",
() => { new JPath("[1]Blah"); });
ExceptionAssert.Throws<JsonException>(() => { new JPath("[1]Blah"); }, "Unexpected character following indexer: B");
}
}
}
@@ -120,8 +120,7 @@ undefined
jsonReader.Read();
jsonReader.Read();
ExceptionAssert.Throws<JsonReaderException>(@"Error reading JToken from JsonReader. Unexpected token: EndArray. Path '', line 1, position 2.",
() => JToken.ReadFrom(jsonReader));
ExceptionAssert.Throws<JsonReaderException>(() => JToken.ReadFrom(jsonReader), @"Error reading JToken from JsonReader. Unexpected token: EndArray. Path '', line 1, position 2.");
}
[Test]
@@ -711,34 +710,31 @@ keyword such as type of business.""
[Test]
public void JObjectIntIndex()
{
ExceptionAssert.Throws<ArgumentException>("Accessed JObject values with invalid key value: 0. Object property name expected.",
() =>
{
JObject o = new JObject();
Assert.AreEqual(null, o[0]);
});
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
Assert.AreEqual(null, o[0]);
}, "Accessed JObject values with invalid key value: 0. Object property name expected.");
}
[Test]
public void JArrayStringIndex()
{
ExceptionAssert.Throws<ArgumentException>(@"Accessed JArray values with invalid key value: ""purple"". Array position index expected.",
() =>
{
JArray a = new JArray();
Assert.AreEqual(null, a["purple"]);
});
ExceptionAssert.Throws<ArgumentException>(() =>
{
JArray a = new JArray();
Assert.AreEqual(null, a["purple"]);
}, @"Accessed JArray values with invalid key value: ""purple"". Array position index expected.");
}
[Test]
public void JConstructorStringIndex()
{
ExceptionAssert.Throws<ArgumentException>(@"Accessed JConstructor values with invalid key value: ""purple"". Argument position index expected.",
() =>
{
JConstructor c = new JConstructor("ConstructorValue");
Assert.AreEqual(null, c["purple"]);
});
ExceptionAssert.Throws<ArgumentException>(() =>
{
JConstructor c = new JConstructor("ConstructorValue");
Assert.AreEqual(null, c["purple"]);
}, @"Accessed JConstructor values with invalid key value: ""purple"". Argument position index expected.");
}
#if !NET20
@@ -1065,13 +1061,12 @@ keyword such as type of business.""
IDictionary<string, string> users = new Dictionary<string, string>();
// unfortunatly there doesn't appear to be a way around this
ExceptionAssert.Throws<Microsoft.CSharp.RuntimeBinder.RuntimeBinderException>("The best overloaded method match for 'System.Collections.Generic.IDictionary<string,string>.Add(string, string)' has some invalid arguments",
() =>
{
users.Add("name2", name);
ExceptionAssert.Throws<Microsoft.CSharp.RuntimeBinder.RuntimeBinderException>(() =>
{
users.Add("name2", name);
Assert.AreEqual(users["name2"], "Matthew Doig");
});
Assert.AreEqual(users["name2"], "Matthew Doig");
}, "The best overloaded method match for 'System.Collections.Generic.IDictionary<string,string>.Add(string, string)' has some invalid arguments");
}
#endif
}
@@ -85,13 +85,12 @@ namespace Newtonsoft.Json.Tests.Schema
[Test]
public void ValidateWithOutEventHandlerFailure()
{
ExceptionAssert.Throws<JsonSchemaException>(@"String 'pie' does not match regex pattern 'lol'.",
() =>
{
JsonSchema schema = JsonSchema.Parse("{'pattern':'lol'}");
JToken stringToken = JToken.FromObject("pie");
stringToken.Validate(schema);
});
ExceptionAssert.Throws<JsonSchemaException>(() =>
{
JsonSchema schema = JsonSchema.Parse("{'pattern':'lol'}");
JToken stringToken = JToken.FromObject("pie");
stringToken.Validate(schema);
}, @"String 'pie' does not match regex pattern 'lol'.");
}
[Test]
@@ -237,75 +236,70 @@ namespace Newtonsoft.Json.Tests.Schema
[Test]
public void ExclusiveMaximum_Int()
{
ExceptionAssert.Throws<JsonSchemaException>("Integer 10 equals maximum value of 10 and exclusive maximum is true.",
() =>
{
JsonSchema schema = new JsonSchema();
schema.Maximum = 10;
schema.ExclusiveMaximum = true;
ExceptionAssert.Throws<JsonSchemaException>(() =>
{
JsonSchema schema = new JsonSchema();
schema.Maximum = 10;
schema.ExclusiveMaximum = true;
JValue v = new JValue(10);
v.Validate(schema);
});
JValue v = new JValue(10);
v.Validate(schema);
}, "Integer 10 equals maximum value of 10 and exclusive maximum is true.");
}
[Test]
public void ExclusiveMaximum_Float()
{
ExceptionAssert.Throws<JsonSchemaException>("Float 10.1 equals maximum value of 10.1 and exclusive maximum is true.",
() =>
{
JsonSchema schema = new JsonSchema();
schema.Maximum = 10.1;
schema.ExclusiveMaximum = true;
ExceptionAssert.Throws<JsonSchemaException>(() =>
{
JsonSchema schema = new JsonSchema();
schema.Maximum = 10.1;
schema.ExclusiveMaximum = true;
JValue v = new JValue(10.1);
v.Validate(schema);
});
JValue v = new JValue(10.1);
v.Validate(schema);
}, "Float 10.1 equals maximum value of 10.1 and exclusive maximum is true.");
}
[Test]
public void ExclusiveMinimum_Int()
{
ExceptionAssert.Throws<JsonSchemaException>("Integer 10 equals minimum value of 10 and exclusive minimum is true.",
() =>
{
JsonSchema schema = new JsonSchema();
schema.Minimum = 10;
schema.ExclusiveMinimum = true;
ExceptionAssert.Throws<JsonSchemaException>(() =>
{
JsonSchema schema = new JsonSchema();
schema.Minimum = 10;
schema.ExclusiveMinimum = true;
JValue v = new JValue(10);
v.Validate(schema);
});
JValue v = new JValue(10);
v.Validate(schema);
}, "Integer 10 equals minimum value of 10 and exclusive minimum is true.");
}
[Test]
public void ExclusiveMinimum_Float()
{
ExceptionAssert.Throws<JsonSchemaException>("Float 10.1 equals minimum value of 10.1 and exclusive minimum is true.",
() =>
{
JsonSchema schema = new JsonSchema();
schema.Minimum = 10.1;
schema.ExclusiveMinimum = true;
ExceptionAssert.Throws<JsonSchemaException>(() =>
{
JsonSchema schema = new JsonSchema();
schema.Minimum = 10.1;
schema.ExclusiveMinimum = true;
JValue v = new JValue(10.1);
v.Validate(schema);
});
JValue v = new JValue(10.1);
v.Validate(schema);
}, "Float 10.1 equals minimum value of 10.1 and exclusive minimum is true.");
}
[Test]
public void DivisibleBy_Int()
{
ExceptionAssert.Throws<JsonSchemaException>("Integer 10 is not evenly divisible by 3.",
() =>
{
JsonSchema schema = new JsonSchema();
schema.DivisibleBy = 3;
ExceptionAssert.Throws<JsonSchemaException>(() =>
{
JsonSchema schema = new JsonSchema();
schema.DivisibleBy = 3;
JValue v = new JValue(10);
v.Validate(schema);
});
JValue v = new JValue(10);
v.Validate(schema);
}, "Integer 10 is not evenly divisible by 3.");
}
[Test]
@@ -384,19 +384,18 @@ namespace Newtonsoft.Json.Tests.Schema
[Test]
public void UnresolvedReference()
{
ExceptionAssert.Throws<Exception>(@"Could not resolve schema reference 'MyUnresolvedReference'.",
() =>
{
string json = @"{
ExceptionAssert.Throws<Exception>(() =>
{
string json = @"{
""id"":""CircularReferenceArray"",
""description"":""CircularReference"",
""type"":[""array""],
""items"":{""$ref"":""MyUnresolvedReference""}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
});
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json)));
}, @"Could not resolve schema reference 'MyUnresolvedReference'.");
}
[Test]
@@ -597,13 +596,11 @@ namespace Newtonsoft.Json.Tests.Schema
}
}";
ExceptionAssert.Throws<JsonException>(
"Could not resolve schema reference '#/array/10'.",
() =>
{
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
builder.Read(new JsonTextReader(new StringReader(json)));
});
ExceptionAssert.Throws<JsonException>(() =>
{
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
builder.Read(new JsonTextReader(new StringReader(json)));
}, "Could not resolve schema reference '#/array/10'.");
}
[Test]
@@ -617,13 +614,11 @@ namespace Newtonsoft.Json.Tests.Schema
}
}";
ExceptionAssert.Throws<JsonException>(
"Could not resolve schema reference '#/array/-1'.",
() =>
{
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
builder.Read(new JsonTextReader(new StringReader(json)));
});
ExceptionAssert.Throws<JsonException>(() =>
{
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
builder.Read(new JsonTextReader(new StringReader(json)));
}, "Could not resolve schema reference '#/array/-1'.");
}
[Test]
@@ -637,13 +632,11 @@ namespace Newtonsoft.Json.Tests.Schema
}
}";
ExceptionAssert.Throws<JsonException>(
"Could not resolve schema reference '#/array/one'.",
() =>
{
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
builder.Read(new JsonTextReader(new StringReader(json)));
});
ExceptionAssert.Throws<JsonException>(() =>
{
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
builder.Read(new JsonTextReader(new StringReader(json)));
}, "Could not resolve schema reference '#/array/one'.");
}
}
}
@@ -260,12 +260,11 @@ namespace Newtonsoft.Json.Tests.Schema
[Test]
public void CircularReferenceError()
{
ExceptionAssert.Throws<Exception>(@"Unresolved circular reference for type 'Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.",
() =>
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.Generate(typeof(CircularReferenceClass));
});
ExceptionAssert.Throws<Exception>(() =>
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.Generate(typeof(CircularReferenceClass));
}, @"Unresolved circular reference for type 'Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.");
}
[Test]
@@ -67,14 +67,12 @@ namespace Newtonsoft.Json.Tests.Serialization
[Test]
public void FailWithPrivateConstructorPlusParametizedAndDefault()
{
ExceptionAssert.Throws<Exception>(
null,
() =>
{
string json = @"{Name:""Name!""}";
ExceptionAssert.Throws<Exception>(() =>
{
string json = @"{Name:""Name!""}";
PrivateConstructorWithPublicParametizedConstructorTestClass c = JsonConvert.DeserializeObject<PrivateConstructorWithPublicParametizedConstructorTestClass>(json);
});
PrivateConstructorWithPublicParametizedConstructorTestClass c = JsonConvert.DeserializeObject<PrivateConstructorWithPublicParametizedConstructorTestClass>(json);
});
}
[Test]
@@ -161,12 +161,10 @@ namespace Newtonsoft.Json.Tests.Serialization
Assert.IsNull(contract.DefaultCreator);
Assert.IsNull(contract.OverrideCreator);
ExceptionAssert.Throws<JsonSerializationException>(
"Could not create an instance of type Newtonsoft.Json.Tests.Serialization.AbstractTestClass. Type is an interface or abstract class and cannot be instantiated. Path 'Value', line 1, position 7.",
() => JsonConvert.DeserializeObject<AbstractTestClass>(@"{Value:'Value!'}", new JsonSerializerSettings
{
ContractResolver = resolver
}));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<AbstractTestClass>(@"{Value:'Value!'}", new JsonSerializerSettings
{
ContractResolver = resolver
}), "Could not create an instance of type Newtonsoft.Json.Tests.Serialization.AbstractTestClass. Type is an interface or abstract class and cannot be instantiated. Path 'Value', line 1, position 7.");
contract.DefaultCreator = () => new AbstractImplementationTestClass();
@@ -188,12 +186,10 @@ namespace Newtonsoft.Json.Tests.Serialization
Assert.IsNull(contract.DefaultCreator);
Assert.IsFalse(contract.HasParametrizedCreator);
ExceptionAssert.Throws<JsonSerializationException>(
"Could not create an instance of type Newtonsoft.Json.Tests.Serialization.AbstractListTestClass`1[System.Int32]. Type is an interface or abstract class and cannot be instantiated. Path '', line 1, position 1.",
() => JsonConvert.DeserializeObject<AbstractListTestClass<int>>(@"[1,2]", new JsonSerializerSettings
{
ContractResolver = resolver
}));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<AbstractListTestClass<int>>(@"[1,2]", new JsonSerializerSettings
{
ContractResolver = resolver
}), "Could not create an instance of type Newtonsoft.Json.Tests.Serialization.AbstractListTestClass`1[System.Int32]. Type is an interface or abstract class and cannot be instantiated. Path '', line 1, position 1.");
contract.DefaultCreator = () => new AbstractImplementationListTestClass<int>();
@@ -270,12 +266,10 @@ namespace Newtonsoft.Json.Tests.Serialization
Assert.IsNull(contract.DefaultCreator);
Assert.IsFalse(contract.HasParametrizedCreator);
ExceptionAssert.Throws<JsonSerializationException>(
"Could not create an instance of type Newtonsoft.Json.Tests.Serialization.AbstractDictionaryTestClass`2[System.String,System.Int32]. Type is an interface or abstract class and cannot be instantiated. Path 'key1', line 1, position 6.",
() => JsonConvert.DeserializeObject<AbstractDictionaryTestClass<string, int>>(@"{key1:1,key2:2}", new JsonSerializerSettings
{
ContractResolver = resolver
}));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<AbstractDictionaryTestClass<string, int>>(@"{key1:1,key2:2}", new JsonSerializerSettings
{
ContractResolver = resolver
}), "Could not create an instance of type Newtonsoft.Json.Tests.Serialization.AbstractDictionaryTestClass`2[System.String,System.Int32]. Type is an interface or abstract class and cannot be instantiated. Path 'key1', line 1, position 6.");
contract.DefaultCreator = () => new AbstractImplementationDictionaryTestClass<string, int>();
@@ -155,17 +155,16 @@ namespace Newtonsoft.Json.Tests.Serialization
[Test]
public void NoPublicDefaultConstructor()
{
ExceptionAssert.Throws<JsonSerializationException>("Unable to find a default constructor to use for type System.Dynamic.DynamicObject. Path 'contributors', line 2, position 18.",
() =>
{
var settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
var json = @"{
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
var settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
var json = @"{
""contributors"": null
}";
JsonConvert.DeserializeObject<DynamicObject>(json, settings);
});
JsonConvert.DeserializeObject<DynamicObject>(json, settings);
}, "Unable to find a default constructor to use for type System.Dynamic.DynamicObject. Path 'contributors', line 2, position 18.");
}
public class DictionaryDynamicObject : DynamicObject
@@ -119,9 +119,7 @@ namespace Newtonsoft.Json.Tests.Serialization
""3""
]";
ExceptionAssert.Throws<JsonSerializationException>(
"Cannot create and populate list type Newtonsoft.Json.Tests.Serialization.JsonSerializerCollectionsTests+EnumerableClassFailure`1[System.String]. Path '', line 1, position 1.",
() => JsonConvert.DeserializeObject<EnumerableClassFailure<string>>(json));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<EnumerableClassFailure<string>>(json), "Cannot create and populate list type Newtonsoft.Json.Tests.Serialization.JsonSerializerCollectionsTests+EnumerableClassFailure`1[System.String]. Path '', line 1, position 1.");
}
public class PrivateDefaultCtorList<T> : List<T>
@@ -134,10 +132,7 @@ namespace Newtonsoft.Json.Tests.Serialization
[Test]
public void DeserializePrivateListCtor()
{
ExceptionAssert.Throws<JsonSerializationException>(
"Unable to find a constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerCollectionsTests+PrivateDefaultCtorList`1[System.Int32]. Path '', line 1, position 1.",
() => JsonConvert.DeserializeObject<PrivateDefaultCtorList<int>>("[1,2]")
);
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<PrivateDefaultCtorList<int>>("[1,2]"), "Unable to find a constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerCollectionsTests+PrivateDefaultCtorList`1[System.Int32]. Path '', line 1, position 1.");
var list = JsonConvert.DeserializeObject<PrivateDefaultCtorList<int>>("[1,2]", new JsonSerializerSettings
{
@@ -621,9 +616,7 @@ namespace Newtonsoft.Json.Tests.Serialization
{
string json = @"[ null ]";
ExceptionAssert.Throws<JsonSerializationException>(
"Cannot convert null value to KeyValuePair. Path '[0]', line 1, position 6.",
() => { JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>>>(json); });
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>>>(json); }, "Cannot convert null value to KeyValuePair. Path '[0]', line 1, position 6.");
}
#if !(NET40 || NET35 || NET20 || PORTABLE40)
@@ -939,9 +932,7 @@ namespace Newtonsoft.Json.Tests.Serialization
{
string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1,2,3],[2,1],[2,2]],""After"":""After!""}";
ExceptionAssert.Throws<Exception>(
"Cannot deserialize non-cubical array as multidimensional array.",
() => JsonConvert.DeserializeObject<Array2D>(json));
ExceptionAssert.Throws<Exception>(() => JsonConvert.DeserializeObject<Array2D>(json), "Cannot deserialize non-cubical array as multidimensional array.");
}
[Test]
@@ -949,9 +940,7 @@ namespace Newtonsoft.Json.Tests.Serialization
{
string json = @"{""Before"":""Before!"",""Coordinates"":[[1,1],[1],[2,1],[2,2]],""After"":""After!""}";
ExceptionAssert.Throws<Exception>(
"Cannot deserialize non-cubical array as multidimensional array.",
() => JsonConvert.DeserializeObject<Array2D>(json));
ExceptionAssert.Throws<Exception>(() => JsonConvert.DeserializeObject<Array2D>(json), "Cannot deserialize non-cubical array as multidimensional array.");
}
[Test]
@@ -979,9 +968,7 @@ namespace Newtonsoft.Json.Tests.Serialization
{
string json = @"{""Before"":""Before!"",""Coordinates"":[[[1,1,1],[1,1,2,1]],[[1,2,1],[1,2,2]],[[2,1,1],[2,1,2]],[[2,2,1],[2,2,2]]],""After"":""After!""}";
ExceptionAssert.Throws<Exception>(
"Cannot deserialize non-cubical array as multidimensional array.",
() => JsonConvert.DeserializeObject<Array3D>(json));
ExceptionAssert.Throws<Exception>(() => JsonConvert.DeserializeObject<Array3D>(json), "Cannot deserialize non-cubical array as multidimensional array.");
}
[Test]
@@ -989,9 +976,7 @@ namespace Newtonsoft.Json.Tests.Serialization
{
string json = @"{""Before"":""Before!"",""Coordinates"":[[[1,1,1],[1,1,2]],[[1,2,1],[1,2,2]],[[2,1,1],[2,1,2]],[[2,2,1],{}]],""After"":""After!""}";
ExceptionAssert.Throws<JsonSerializationException>(
"Unexpected token when deserializing multidimensional array: StartObject. Path 'Coordinates[3][1]', line 1, position 99.",
() => JsonConvert.DeserializeObject<Array3D>(json));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<Array3D>(json), "Unexpected token when deserializing multidimensional array: StartObject. Path 'Coordinates[3][1]', line 1, position 99.");
}
[Test]
@@ -999,9 +984,7 @@ namespace Newtonsoft.Json.Tests.Serialization
{
string json = @"{""Before"":""Before!"",""Coordinates"":[[[1,1,1],[1,1]],[[1,2,1],[1,2,2]],[[2,1,1],[2,1,2]],[[2,2,1],[2,2,2]]],""After"":""After!""}";
ExceptionAssert.Throws<Exception>(
"Cannot deserialize non-cubical array as multidimensional array.",
() => JsonConvert.DeserializeObject<Array3D>(json));
ExceptionAssert.Throws<Exception>(() => JsonConvert.DeserializeObject<Array3D>(json), "Cannot deserialize non-cubical array as multidimensional array.");
}
[Test]
@@ -1040,9 +1023,7 @@ namespace Newtonsoft.Json.Tests.Serialization
{
string json = @"{""Before"":""Before!"",""Coordinates"":[/*hi*/[/*hi*/[1/*hi*/,/*hi*/1/*hi*/,1]/*hi*/,/*hi*/[1,1";
ExceptionAssert.Throws<JsonException>(
null,
() => JsonConvert.DeserializeObject<Array3D>(json));
ExceptionAssert.Throws<JsonException>(() => JsonConvert.DeserializeObject<Array3D>(json));
}
[Test]
@@ -1050,9 +1031,7 @@ namespace Newtonsoft.Json.Tests.Serialization
{
string json = @"{""Before"":""Before!"",""Coordinates"":[/*hi*/[/*hi*/";
ExceptionAssert.Throws<JsonException>(
null,
() => JsonConvert.DeserializeObject<Array3D>(json));
ExceptionAssert.Throws<JsonException>(() => JsonConvert.DeserializeObject<Array3D>(json));
}
[Test]
@@ -1383,9 +1383,7 @@ keyword such as type of business.""
[Test]
public void BadJsonPropertyClassSerialize()
{
ExceptionAssert.Throws<JsonSerializationException>(
@"A member with the name 'pie' already exists on 'Newtonsoft.Json.Tests.TestObjects.BadJsonPropertyClass'. Use the JsonPropertyAttribute to specify another name.",
() => { JsonConvert.SerializeObject(new BadJsonPropertyClass()); });
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.SerializeObject(new BadJsonPropertyClass()); }, @"A member with the name 'pie' already exists on 'Newtonsoft.Json.Tests.TestObjects.BadJsonPropertyClass'. Use the JsonPropertyAttribute to specify another name.");
}
#if !NET20
[Test]
@@ -1429,9 +1427,7 @@ keyword such as type of business.""
{
string json = @"[""vvv\jvvv""]";
ExceptionAssert.Throws<JsonReaderException>(
@"Bad JSON escape sequence: \j. Path '', line 1, position 7.",
() => { JsonConvert.DeserializeObject<List<string>>(json); });
ExceptionAssert.Throws<JsonReaderException>(() => { JsonConvert.DeserializeObject<List<string>>(json); }, @"Bad JSON escape sequence: \j. Path '', line 1, position 7.");
}
[Test]
@@ -1938,13 +1934,11 @@ keyword such as type of business.""
[Test]
public void IncompatibleJsonAttributeShouldThrow()
{
ExceptionAssert.Throws<JsonSerializationException>(
"Unexpected value when converting date. Expected DateTime or DateTimeOffset, got Newtonsoft.Json.Tests.TestObjects.IncompatibleJsonAttributeClass.",
() =>
{
IncompatibleJsonAttributeClass c = new IncompatibleJsonAttributeClass();
JsonConvert.SerializeObject(c);
});
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
IncompatibleJsonAttributeClass c = new IncompatibleJsonAttributeClass();
JsonConvert.SerializeObject(c);
}, "Unexpected value when converting date. Expected DateTime or DateTimeOffset, got Newtonsoft.Json.Tests.TestObjects.IncompatibleJsonAttributeClass.");
}
[Test]
@@ -2122,21 +2116,19 @@ keyword such as type of business.""
[Test]
public void SerializeRequiredMembersClassNullRequiredValueProperty()
{
ExceptionAssert.Throws<JsonSerializationException>(
"Cannot write a null value for property 'FirstName'. Property requires a value. Path ''.",
() =>
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
RequiredMembersClass requiredMembersClass = new RequiredMembersClass
{
RequiredMembersClass requiredMembersClass = new RequiredMembersClass
{
FirstName = null,
BirthDate = new DateTime(2000, 10, 10, 10, 10, 10, DateTimeKind.Utc),
LastName = null,
MiddleName = null
};
FirstName = null,
BirthDate = new DateTime(2000, 10, 10, 10, 10, 10, DateTimeKind.Utc),
LastName = null,
MiddleName = null
};
string json = JsonConvert.SerializeObject(requiredMembersClass);
Console.WriteLine(json);
});
string json = JsonConvert.SerializeObject(requiredMembersClass);
Console.WriteLine(json);
}, "Cannot write a null value for property 'FirstName'. Property requires a value. Path ''.");
}
[Test]
@@ -2239,9 +2231,7 @@ keyword such as type of business.""
testClass.co = new Co();
String strFromTest = JsonConvert.SerializeObject(testClass);
ExceptionAssert.Throws<JsonSerializationException>(
@"Could not create an instance of type Newtonsoft.Json.Tests.TestObjects.ICo. Type is an interface or abstract class and cannot be instantiated. Path 'co.Name', line 1, position 14.",
() => { InterfacePropertyTestClass testFromDe = (InterfacePropertyTestClass)JsonConvert.DeserializeObject(strFromTest, typeof(InterfacePropertyTestClass)); });
ExceptionAssert.Throws<JsonSerializationException>(() => { InterfacePropertyTestClass testFromDe = (InterfacePropertyTestClass)JsonConvert.DeserializeObject(strFromTest, typeof(InterfacePropertyTestClass)); }, @"Could not create an instance of type Newtonsoft.Json.Tests.TestObjects.ICo. Type is an interface or abstract class and cannot be instantiated. Path 'co.Name', line 1, position 14.");
}
private Person GetPerson()
@@ -2492,15 +2482,13 @@ keyword such as type of business.""
{
string classRef = typeof(JsonPropertyWithHandlingValues).FullName;
ExceptionAssert.Throws<JsonSerializationException>(
"Self referencing loop detected for property 'ReferenceLoopHandlingErrorProperty' with type '" + classRef + "'. Path ''.",
() =>
{
JsonPropertyWithHandlingValues o = new JsonPropertyWithHandlingValues();
o.ReferenceLoopHandlingErrorProperty = o;
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
JsonPropertyWithHandlingValues o = new JsonPropertyWithHandlingValues();
o.ReferenceLoopHandlingErrorProperty = o;
JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
});
JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
}, "Self referencing loop detected for property 'ReferenceLoopHandlingErrorProperty' with type '" + classRef + "'. Path ''.");
}
[Test]
@@ -2869,9 +2857,7 @@ keyword such as type of business.""
{
string json = @"{""sublocation"":""AlertEmailSender.Program.Main"",""userId"":0,""type"":0,""summary"":""Loading settings variables"",""details"":null,""stackTrace"":"" at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)\r\n at System.Environment.get_StackTrace()\r\n at mr.Logging.Event..ctor(String summary) in C:\\Projects\\MRUtils\\Logging\\Event.vb:line 71\r\n at AlertEmailSender.Program.Main(String[] args) in C:\\Projects\\AlertEmailSender\\AlertEmailSender\\Program.cs:line 25"",""tag"":null,""time"":""\/Date(1249591032026-0400)\/""}";
ExceptionAssert.Throws<JsonSerializationException>(
@"Unable to find a constructor to use for type Newtonsoft.Json.Tests.TestObjects.Event. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'sublocation', line 1, position 15.",
() => { JsonConvert.DeserializeObject<TestObjects.Event>(json); });
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<TestObjects.Event>(json); }, @"Unable to find a constructor to use for type Newtonsoft.Json.Tests.TestObjects.Event. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'sublocation', line 1, position 15.");
}
[Test]
@@ -2910,11 +2896,9 @@ keyword such as type of business.""
{
string json = @"[]";
ExceptionAssert.Throws<JsonSerializationException>(
@"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Newtonsoft.Json.Tests.TestObjects.Person' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<Person>(json); }, @"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Newtonsoft.Json.Tests.TestObjects.Person' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {""name"":""value""}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.",
() => { JsonConvert.DeserializeObject<Person>(json); });
Path '', line 1, position 1.");
}
[Test]
@@ -2922,11 +2906,9 @@ Path '', line 1, position 1.",
{
string json = @"[]";
ExceptionAssert.Throws<JsonSerializationException>(
@"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<Dictionary<string, string>>(json); }, @"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {""name"":""value""}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.",
() => { JsonConvert.DeserializeObject<Dictionary<string, string>>(json); });
Path '', line 1, position 1.");
}
#if !(NETFX_CORE || PORTABLE)
@@ -2935,11 +2917,9 @@ Path '', line 1, position 1.",
{
string json = @"[]";
ExceptionAssert.Throws<JsonSerializationException>(
@"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Exception' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<Exception>(json); }, @"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Exception' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {""name"":""value""}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.",
() => { JsonConvert.DeserializeObject<Exception>(json); });
Path '', line 1, position 1.");
}
#endif
@@ -2948,11 +2928,9 @@ Path '', line 1, position 1.",
{
string json = @"[]";
ExceptionAssert.Throws<JsonSerializationException>(
@"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Double' because the type requires a JSON primitive value (e.g. string, number, boolean, null) to deserialize correctly.
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<double>(json); }, @"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Double' because the type requires a JSON primitive value (e.g. string, number, boolean, null) to deserialize correctly.
To fix this error either change the JSON to a JSON primitive value (e.g. string, number, boolean, null) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.",
() => { JsonConvert.DeserializeObject<double>(json); });
Path '', line 1, position 1.");
}
#if !(NET35 || NET20 || PORTABLE40)
@@ -2961,11 +2939,9 @@ Path '', line 1, position 1.",
{
string json = @"[]";
ExceptionAssert.Throws<JsonSerializationException>(
@"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Newtonsoft.Json.Tests.Linq.DynamicDictionary' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<DynamicDictionary>(json); }, @"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Newtonsoft.Json.Tests.Linq.DynamicDictionary' because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {""name"":""value""}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.",
() => { JsonConvert.DeserializeObject<DynamicDictionary>(json); });
Path '', line 1, position 1.");
}
#endif
@@ -2987,9 +2963,7 @@ Path '', line 1, position 1.",
{
string json = @"new Constructor(123)";
ExceptionAssert.Throws<JsonSerializationException>(
@"Error converting value ""Constructor"" to type 'Newtonsoft.Json.Tests.TestObjects.Person'. Path '', line 1, position 16.",
() => { JsonConvert.DeserializeObject<Person>(json); });
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<Person>(json); }, @"Error converting value ""Constructor"" to type 'Newtonsoft.Json.Tests.TestObjects.Person'. Path '', line 1, position 16.");
}
[Test]
@@ -2997,9 +2971,7 @@ Path '', line 1, position 1.",
{
string json = @"[new Constructor(123)]";
ExceptionAssert.Throws<JsonSerializationException>(
@"Error converting value ""Constructor"" to type 'Newtonsoft.Json.Tests.TestObjects.Person'. Path '[0]', line 1, position 17.",
() => { JsonConvert.DeserializeObject<List<Person>>(json); });
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<List<Person>>(json); }, @"Error converting value ""Constructor"" to type 'Newtonsoft.Json.Tests.TestObjects.Person'. Path '[0]', line 1, position 17.");
}
[Test]
@@ -3025,9 +2997,7 @@ Path ''"));
{
string json = @"[]";
ExceptionAssert.Throws<JsonSerializationException>(
@"Cannot populate JSON array onto type 'Newtonsoft.Json.Tests.TestObjects.Person'. Path '', line 1, position 1.",
() => { JsonConvert.PopulateObject(json, new Person()); });
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.PopulateObject(json, new Person()); }, @"Cannot populate JSON array onto type 'Newtonsoft.Json.Tests.TestObjects.Person'. Path '', line 1, position 1.");
}
[Test]
@@ -3035,9 +3005,7 @@ Path ''"));
{
string json = @"{}";
ExceptionAssert.Throws<JsonSerializationException>(
@"Cannot populate JSON object onto type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. Path '', line 1, position 2.",
() => { JsonConvert.PopulateObject(json, new List<Person>()); });
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.PopulateObject(json, new List<Person>()); }, @"Cannot populate JSON object onto type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. Path '', line 1, position 2.");
}
[Test]
@@ -3052,77 +3020,69 @@ Path ''"));
[Test]
public void SerializePropertyGetError()
{
ExceptionAssert.Throws<JsonSerializationException>(
@"Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.",
() =>
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
JsonConvert.SerializeObject(new MemoryStream(), new JsonSerializerSettings
{
JsonConvert.SerializeObject(new MemoryStream(), new JsonSerializerSettings
ContractResolver = new DefaultContractResolver
{
ContractResolver = new DefaultContractResolver
{
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
IgnoreSerializableAttribute = true
IgnoreSerializableAttribute = true
#endif
}
});
}
});
}, @"Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.");
}
[Test]
public void DeserializePropertySetError()
{
ExceptionAssert.Throws<JsonSerializationException>(
@"Error setting value to 'ReadTimeout' on 'System.IO.MemoryStream'.",
() =>
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:0}", new JsonSerializerSettings
{
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:0}", new JsonSerializerSettings
ContractResolver = new DefaultContractResolver
{
ContractResolver = new DefaultContractResolver
{
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
IgnoreSerializableAttribute = true
IgnoreSerializableAttribute = true
#endif
}
});
}
});
}, @"Error setting value to 'ReadTimeout' on 'System.IO.MemoryStream'.");
}
[Test]
public void DeserializeEnsureTypeEmptyStringToIntError()
{
ExceptionAssert.Throws<JsonSerializationException>(
@"Error converting value {null} to type 'System.Int32'. Path 'ReadTimeout', line 1, position 15.",
() =>
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:''}", new JsonSerializerSettings
{
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:''}", new JsonSerializerSettings
ContractResolver = new DefaultContractResolver
{
ContractResolver = new DefaultContractResolver
{
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
IgnoreSerializableAttribute = true
IgnoreSerializableAttribute = true
#endif
}
});
}
});
}, @"Error converting value {null} to type 'System.Int32'. Path 'ReadTimeout', line 1, position 15.");
}
[Test]
public void DeserializeEnsureTypeNullToIntError()
{
ExceptionAssert.Throws<JsonSerializationException>(
@"Error converting value {null} to type 'System.Int32'. Path 'ReadTimeout', line 1, position 17.",
() =>
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:null}", new JsonSerializerSettings
{
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:null}", new JsonSerializerSettings
ContractResolver = new DefaultContractResolver
{
ContractResolver = new DefaultContractResolver
{
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
IgnoreSerializableAttribute = true
IgnoreSerializableAttribute = true
#endif
}
});
}
});
}, @"Error converting value {null} to type 'System.Int32'. Path 'ReadTimeout', line 1, position 17.");
}
[Test]
@@ -3523,12 +3483,11 @@ Path ''"));
{
string json = "{'$id':'1',key1:'value1',key2:'value2',key3:'value3'}";
ExceptionAssert.Throws<JsonSerializationException>("Cannot preserve reference to readonly dictionary, or dictionary created from a non-default constructor: Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+DictionaryWithNoDefaultConstructor. Path 'key1', line 1, position 16.",
() => JsonConvert.DeserializeObject<DictionaryWithNoDefaultConstructor>(json, new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All,
MetadataPropertyHandling = MetadataPropertyHandling.Default
}));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<DictionaryWithNoDefaultConstructor>(json, new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All,
MetadataPropertyHandling = MetadataPropertyHandling.Default
}), "Cannot preserve reference to readonly dictionary, or dictionary created from a non-default constructor: Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+DictionaryWithNoDefaultConstructor. Path 'key1', line 1, position 16.");
}
public class DictionaryWithNoDefaultConstructor : Dictionary<string, string>
@@ -3914,16 +3873,14 @@ Path ''"));
{
try
{
ExceptionAssert.Throws<JsonSerializationException>(
@"Type 'Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+ISerializableTestObject' implements ISerializable but cannot be deserialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.
To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.
Path 'booleanValue', line 1, position 14.",
() =>
{
JsonTypeReflector.SetFullyTrusted(false);
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
JsonTypeReflector.SetFullyTrusted(false);
JsonConvert.DeserializeObject<ISerializableTestObject>("{booleanValue:true}");
});
JsonConvert.DeserializeObject<ISerializableTestObject>("{booleanValue:true}");
}, @"Type 'Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+ISerializableTestObject' implements ISerializable but cannot be deserialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.
To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.
Path 'booleanValue', line 1, position 14.");
}
finally
{
@@ -3936,16 +3893,14 @@ Path 'booleanValue', line 1, position 14.",
{
try
{
ExceptionAssert.Throws<JsonSerializationException>(
@"Type 'Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+ISerializableTestObject' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.
To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true. Path ''.",
() =>
{
JsonTypeReflector.SetFullyTrusted(false);
ISerializableTestObject value = new ISerializableTestObject("string!", 0, default(DateTimeOffset), null);
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
JsonTypeReflector.SetFullyTrusted(false);
ISerializableTestObject value = new ISerializableTestObject("string!", 0, default(DateTimeOffset), null);
JsonConvert.SerializeObject(value);
});
JsonConvert.SerializeObject(value);
}, @"Type 'Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+ISerializableTestObject' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.
To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true. Path ''.");
}
finally
{
@@ -4440,32 +4395,28 @@ To fix this error either change the environment to be fully trusted, change the
var json = JsonConvert.SerializeObject(child, Formatting.Indented);
ExceptionAssert.Throws<JsonSerializationException>(
"Additional content found in JSON reference object. A JSON reference object should only have a $ref property. Path 'Father.$id', line 6, position 11.",
() => { JsonConvert.DeserializeObject<Dictionary<string, object>>(json); });
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<Dictionary<string, object>>(json); }, "Additional content found in JSON reference object. A JSON reference object should only have a $ref property. Path 'Father.$id', line 6, position 11.");
}
[Test]
public void SerializeRefBadType()
{
ExceptionAssert.Throws<JsonSerializationException>(
"JSON reference $ref property must have a string or null value. Path 'Father.$ref', line 5, position 14.",
() =>
{
//Additional text found in JSON string after finishing deserializing object.
//Test 1
var reference = new Dictionary<string, object>();
reference.Add("$ref", 1);
reference.Add("$id", 1);
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
//Additional text found in JSON string after finishing deserializing object.
//Test 1
var reference = new Dictionary<string, object>();
reference.Add("$ref", 1);
reference.Add("$id", 1);
var child = new Dictionary<string, object>();
child.Add("_id", 2);
child.Add("Name", "Isabell");
child.Add("Father", reference);
var child = new Dictionary<string, object>();
child.Add("_id", 2);
child.Add("Name", "Isabell");
child.Add("Father", reference);
var json = JsonConvert.SerializeObject(child, Formatting.Indented);
JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
});
var json = JsonConvert.SerializeObject(child, Formatting.Indented);
JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
}, "JSON reference $ref property must have a string or null value. Path 'Father.$ref', line 5, position 14.");
}
[Test]
@@ -4674,9 +4625,7 @@ To fix this error either change the environment to be fully trusted, change the
string json = JsonConvert.SerializeObject(s1, Formatting.Indented);
ExceptionAssert.Throws<JsonSerializationException>(
"Cannot create and populate list type " + classRef + ". Path 'StringDictionaryProperty', line 2, position 32.",
() => { JsonConvert.DeserializeObject<StringDictionaryTestClass>(json); });
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<StringDictionaryTestClass>(json); }, "Cannot create and populate list type " + classRef + ". Path 'StringDictionaryProperty', line 2, position 32.");
}
#endif
@@ -5162,9 +5111,7 @@ To fix this error either change the environment to be fully trusted, change the
[Test]
public void DeserializeNullDateTimeValueTest()
{
ExceptionAssert.Throws<JsonSerializationException>(
"Error converting value {null} to type 'System.DateTime'. Path '', line 1, position 4.",
() => { JsonConvert.DeserializeObject("null", typeof(DateTime)); });
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject("null", typeof(DateTime)); }, "Error converting value {null} to type 'System.DateTime'. Path '', line 1, position 4.");
}
[Test]
@@ -6032,9 +5979,7 @@ To fix this error either change the environment to be fully trusted, change the
null
]";
ExceptionAssert.Throws<JsonSerializationException>(
"Error converting value {null} to type 'System.Int32'. Path '[3]', line 5, position 7.",
() => { List<int> numbers = JsonConvert.DeserializeObject<List<int>>(json); });
ExceptionAssert.Throws<JsonSerializationException>(() => { List<int> numbers = JsonConvert.DeserializeObject<List<int>>(json); }, "Error converting value {null} to type 'System.Int32'. Path '[3]', line 5, position 7.");
}
#if !(PORTABLE || NETFX_CORE)
@@ -6073,9 +6018,7 @@ To fix this error either change the environment to be fully trusted, change the
""NullableInteger2"": null
}";
ExceptionAssert.Throws<JsonSerializationException>(
"Error converting value 1 to type 'Newtonsoft.Json.Tests.ConvertibleInt'. Path 'Integer', line 2, position 15.",
() => JsonConvert.DeserializeObject<ConvertableIntTestClass>(json));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<ConvertableIntTestClass>(json), "Error converting value 1 to type 'Newtonsoft.Json.Tests.ConvertibleInt'. Path 'Integer', line 2, position 15.");
}
#endif
@@ -6104,31 +6047,27 @@ To fix this error either change the environment to be fully trusted, change the
[Test]
public void DeserializeBoolInt()
{
ExceptionAssert.Throws<JsonReaderException>(
"Error reading integer. Unexpected token: Boolean. Path 'PreProperty', line 2, position 22.",
() =>
{
string json = @"{
ExceptionAssert.Throws<JsonReaderException>(() =>
{
string json = @"{
""PreProperty"": true,
""PostProperty"": ""-1""
}";
JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
});
JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
}, "Error reading integer. Unexpected token: Boolean. Path 'PreProperty', line 2, position 22.");
}
[Test]
public void DeserializeUnexpectedEndInt()
{
ExceptionAssert.Throws<JsonException>(
null,
() =>
{
string json = @"{
ExceptionAssert.Throws<JsonException>(() =>
{
string json = @"{
""PreProperty"": ";
JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
});
JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
});
}
[Test]
@@ -6275,25 +6214,19 @@ To fix this error either change the environment to be fully trusted, change the
[Test]
public void DeserializeDoubleFromEmptyString()
{
ExceptionAssert.Throws<JsonSerializationException>(
"No JSON content found and type 'System.Double' is not nullable. Path '', line 0, position 0.",
() => { JsonConvert.DeserializeObject<double>(""); });
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<double>(""); }, "No JSON content found and type 'System.Double' is not nullable. Path '', line 0, position 0.");
}
[Test]
public void DeserializeEnumFromEmptyString()
{
ExceptionAssert.Throws<JsonSerializationException>(
"No JSON content found and type 'System.StringComparison' is not nullable. Path '', line 0, position 0.",
() => { JsonConvert.DeserializeObject<StringComparison>(""); });
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<StringComparison>(""); }, "No JSON content found and type 'System.StringComparison' is not nullable. Path '', line 0, position 0.");
}
[Test]
public void DeserializeInt32FromEmptyString()
{
ExceptionAssert.Throws<JsonSerializationException>(
"No JSON content found and type 'System.Int32' is not nullable. Path '', line 0, position 0.",
() => { JsonConvert.DeserializeObject<int>(""); });
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<int>(""); }, "No JSON content found and type 'System.Int32' is not nullable. Path '', line 0, position 0.");
}
[Test]
@@ -6925,9 +6858,7 @@ To fix this error either change the environment to be fully trusted, change the
settings.CheckAdditionalContent = true;
s = JsonSerializer.Create(settings);
ExceptionAssert.Throws<JsonReaderException>(
"Additional text encountered after finished reading JSON content: {. Path '', line 1, position 7.",
() => { s.Deserialize<Dictionary<string, int>>(new JsonTextReader(new StringReader(json))); });
ExceptionAssert.Throws<JsonReaderException>(() => { s.Deserialize<Dictionary<string, int>>(new JsonTextReader(new StringReader(json))); }, "Additional text encountered after finished reading JSON content: {. Path '', line 1, position 7.");
}
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
@@ -6971,21 +6902,19 @@ To fix this error either change the environment to be fully trusted, change the
[Test]
public void AdditionalContentAfterFinish()
{
ExceptionAssert.Throws<JsonException>(
"Additional text found in JSON string after finishing deserializing object.",
() =>
{
string json = "[{},1]";
ExceptionAssert.Throws<JsonException>(() =>
{
string json = "[{},1]";
JsonSerializer serializer = new JsonSerializer();
serializer.CheckAdditionalContent = true;
JsonSerializer serializer = new JsonSerializer();
serializer.CheckAdditionalContent = true;
var reader = new JsonTextReader(new StringReader(json));
reader.Read();
reader.Read();
var reader = new JsonTextReader(new StringReader(json));
reader.Read();
reader.Read();
serializer.Deserialize(reader, typeof(MyType));
});
serializer.Deserialize(reader, typeof(MyType));
}, "Additional text found in JSON string after finishing deserializing object.");
}
[Test]
@@ -7179,8 +7108,8 @@ To fix this error either change the environment to be fully trusted, change the
Assert.AreEqual(500, obj.Item1);
#else
ExceptionAssert.Throws<JsonSerializationException>(
"Unable to find a constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+MyTuple`1[System.Int32]. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'm_Item1', line 1, position 11.",
doStuff);
doStuff,
"Unable to find a constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+MyTuple`1[System.Int32]. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'm_Item1', line 1, position 11.");
#endif
}
@@ -7196,9 +7125,7 @@ To fix this error either change the environment to be fully trusted, change the
var json = JsonConvert.SerializeObject(tuple);
Assert.AreEqual(@"{""m_Item1"":500}", json);
ExceptionAssert.Throws<JsonSerializationException>(
"Unable to find a constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+MyTuplePartial`1[System.Int32]. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'm_Item1', line 1, position 11.",
() => JsonConvert.DeserializeObject<MyTuplePartial<int>>(json));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<MyTuplePartial<int>>(json), "Unable to find a constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+MyTuplePartial`1[System.Int32]. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'm_Item1', line 1, position 11.");
}
finally
{
@@ -7434,9 +7361,7 @@ To fix this error either change the environment to be fully trusted, change the
[Test]
public void NoConstructorReadOnlyCollectionTest()
{
ExceptionAssert.Throws<JsonSerializationException>(
"Cannot deserialize readonly or fixed size list: Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+NoConstructorReadOnlyCollection`1[System.Int32]. Path '', line 1, position 1.",
() => JsonConvert.DeserializeObject<NoConstructorReadOnlyCollection<int>>("[1]"));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<NoConstructorReadOnlyCollection<int>>("[1]"), "Cannot deserialize readonly or fixed size list: Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+NoConstructorReadOnlyCollection`1[System.Int32]. Path '', line 1, position 1.");
}
#if !(NET40 || NET35 || NET20 || PORTABLE40)
@@ -7451,9 +7376,7 @@ To fix this error either change the environment to be fully trusted, change the
[Test]
public void NoConstructorReadOnlyDictionaryTest()
{
ExceptionAssert.Throws<JsonSerializationException>(
"Cannot deserialize readonly or fixed size dictionary: Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+NoConstructorReadOnlyDictionary`2[System.Int32,System.Int32]. Path '1', line 1, position 5.",
() => JsonConvert.DeserializeObject<NoConstructorReadOnlyDictionary<int, int>>("{'1':1}"));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<NoConstructorReadOnlyDictionary<int, int>>("{'1':1}"), "Cannot deserialize readonly or fixed size dictionary: Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+NoConstructorReadOnlyDictionary`2[System.Int32,System.Int32]. Path '1', line 1, position 5.");
}
#endif
@@ -7467,9 +7390,7 @@ To fix this error either change the environment to be fully trusted, change the
Assert.AreEqual(BigInteger.Parse("999999999999999999999999999999999999999999999999"), l[0]);
ExceptionAssert.Throws<JsonSerializationException>(
"Error converting value 999999999999999999999999999999999999999999999999 to type 'System.Int64'. Path '[0]', line 1, position 49.",
() => JsonConvert.DeserializeObject<IList<long>>(json));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<IList<long>>(json), "Error converting value 999999999999999999999999999999999999999999999999 to type 'System.Int64'. Path '[0]', line 1, position 49.");
}
#endif
@@ -7977,13 +7898,11 @@ To fix this error either change the environment to be fully trusted, change the
[Test]
public void DuplicatePropertiesInNestedObject()
{
ExceptionAssert.Throws<ArgumentException>(
"Can not add property time to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.",
() =>
{
string content = @"{""result"":{""time"":1408188592,""time"":1408188593},""error"":null,""id"":""1""}";
JsonConvert.DeserializeObject<JObject>(content);
});
ExceptionAssert.Throws<ArgumentException>(() =>
{
string content = @"{""result"":{""time"":1408188592,""time"":1408188593},""error"":null,""id"":""1""}";
JsonConvert.DeserializeObject<JObject>(content);
}, "Can not add property time to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.");
}
[Test]
@@ -8247,17 +8166,13 @@ To fix this error either change the environment to be fully trusted, change the
[Test]
public void ErrorCreatingJsonConverter()
{
ExceptionAssert.Throws<JsonException>(
"Error creating 'Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+ErroringJsonConverter'.",
() => JsonConvert.SerializeObject(new ErroringTestClass()));
ExceptionAssert.Throws<JsonException>(() => JsonConvert.SerializeObject(new ErroringTestClass()), "Error creating 'Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+ErroringJsonConverter'.");
}
[Test]
public void DeserializeInvalidOctalRootError()
{
ExceptionAssert.Throws<JsonReaderException>(
"Input string '020474068' is not a valid number. Path '', line 1, position 9.",
() => JsonConvert.DeserializeObject<string>("020474068"));
ExceptionAssert.Throws<JsonReaderException>(() => JsonConvert.DeserializeObject<string>("020474068"), "Input string '020474068' is not a valid number. Path '', line 1, position 9.");
}
[Test]
@@ -99,17 +99,15 @@ namespace Newtonsoft.Json.Tests.Serialization
]
}";
ExceptionAssert.Throws<JsonSerializationException>(
@"Cannot preserve reference to array or readonly list, or list created from a non-default constructor: System.String[][]. Path '$values', line 3, position 15.",
() =>
{
JsonConvert.DeserializeObject<string[][]>(json,
new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All,
MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead
});
});
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
JsonConvert.DeserializeObject<string[][]>(json,
new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All,
MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead
});
}, @"Cannot preserve reference to array or readonly list, or list created from a non-default constructor: System.String[][]. Path '$values', line 3, position 15.");
}
#if !NETFX_CORE
@@ -230,16 +228,14 @@ namespace Newtonsoft.Json.Tests.Serialization
""Manager"": null
}";
ExceptionAssert.Throws<JsonSerializationException>(
"Type specified in JSON 'Newtonsoft.Json.Tests.TestObjects.Employee' was not resolved. Path '$type', line 3, position 56.",
() =>
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
{
JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects,
MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead
});
TypeNameHandling = TypeNameHandling.Objects,
MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead
});
}, "Type specified in JSON 'Newtonsoft.Json.Tests.TestObjects.Employee' was not resolved. Path '$type', line 3, position 56.");
}
[Test]
@@ -537,23 +533,21 @@ namespace Newtonsoft.Json.Tests.Serialization
Assert.AreEqual(5d, actual.Payload);
ExceptionAssert.Throws<JsonSerializationException>(
@"Cannot deserialize the current JSON object (e.g. {""name"":""value""}) into type 'System.Double' because the type requires a JSON primitive value (e.g. string, number, boolean, null) to deserialize correctly.
To fix this error either change the JSON to a JSON primitive value (e.g. string, number, boolean, null) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'Payload.$type', line 3, position 13.",
() =>
{
JsonConvert.DeserializeObject<ItemWithTypedPayload>(@"{
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
JsonConvert.DeserializeObject<ItemWithTypedPayload>(@"{
""Payload"": {
""$type"": ""System.Double, mscorlib"",
""$value"": ""5""
}
}",
new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore
});
});
new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore
});
}, @"Cannot deserialize the current JSON object (e.g. {""name"":""value""}) into type 'System.Double' because the type requires a JSON primitive value (e.g. string, number, boolean, null) to deserialize correctly.
To fix this error either change the JSON to a JSON primitive value (e.g. string, number, boolean, null) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'Payload.$type', line 3, position 13.");
}
[Test]
@@ -63,9 +63,7 @@ namespace Newtonsoft.Json.Tests.Serialization
// ]
//}
ExceptionAssert.Throws<JsonSerializationException>(
@"Could not find member 'Price' on object of type 'ProductShort'. Path 'Price', line 4, position 11.",
() => { ProductShort deserializedProductShort = (ProductShort)JsonConvert.DeserializeObject(output, typeof(ProductShort), new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error }); });
ExceptionAssert.Throws<JsonSerializationException>(() => { ProductShort deserializedProductShort = (ProductShort)JsonConvert.DeserializeObject(output, typeof(ProductShort), new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error }); }, @"Could not find member 'Price' on object of type 'ProductShort'. Path 'Price', line 4, position 11.");
}
[Test]
@@ -128,9 +126,7 @@ namespace Newtonsoft.Json.Tests.Serialization
{
string json = @"{""Missing"":1}";
ExceptionAssert.Throws<JsonSerializationException>(
"Could not find member 'Missing' on object of type 'DoubleClass'. Path 'Missing', line 1, position 11.",
() => { JsonConvert.DeserializeObject<DoubleClass>(json, new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error }); });
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.DeserializeObject<DoubleClass>(json, new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error }); }, "Could not find member 'Missing' on object of type 'DoubleClass'. Path 'Missing', line 1, position 11.");
}
[Test]
@@ -157,8 +157,7 @@ namespace Newtonsoft.Json.Tests.Serialization
[Test]
public void PopulateWithBadJson()
{
ExceptionAssert.Throws<JsonSerializationException>("Unexpected initial token 'Integer' when populating object. Expected JSON object or array. Path '', line 1, position 1.",
() => { JsonConvert.PopulateObject("1", new Person()); });
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.PopulateObject("1", new Person()); }, "Unexpected initial token 'Integer' when populating object. Expected JSON object or array. Path '', line 1, position 1.");
}
}
}
@@ -105,9 +105,7 @@ namespace Newtonsoft.Json.Tests.Serialization
circularList.Add(new CircularList { null });
circularList.Add(new CircularList { new CircularList { circularList } });
ExceptionAssert.Throws<JsonSerializationException>(
"Self referencing loop detected with type '" + classRef + "'. Path '[2][0]'.",
() => { JsonConvert.SerializeObject(circularList, Formatting.Indented); });
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.SerializeObject(circularList, Formatting.Indented); }, "Self referencing loop detected with type '" + classRef + "'. Path '[2][0]'.");
}
[Test]
@@ -240,13 +238,11 @@ namespace Newtonsoft.Json.Tests.Serialization
]
}";
ExceptionAssert.Throws<JsonSerializationException>(
@"Cannot preserve reference to array or readonly list, or list created from a non-default constructor: System.String[][]. Path '$values', line 3, position 15.",
() =>
{
JsonConvert.DeserializeObject<string[][]>(json,
new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All });
});
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
JsonConvert.DeserializeObject<string[][]>(json,
new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All });
}, @"Cannot preserve reference to array or readonly list, or list created from a non-default constructor: System.String[][]. Path '$values', line 3, position 15.");
}
public class CircularDictionary : Dictionary<string, CircularDictionary>
@@ -262,9 +258,7 @@ namespace Newtonsoft.Json.Tests.Serialization
circularDictionary.Add("other", new CircularDictionary { { "blah", null } });
circularDictionary.Add("self", circularDictionary);
ExceptionAssert.Throws<JsonSerializationException>(
@"Self referencing loop detected with type '" + classRef + "'. Path ''.",
() => { JsonConvert.SerializeObject(circularDictionary, Formatting.Indented); });
ExceptionAssert.Throws<JsonSerializationException>(() => { JsonConvert.SerializeObject(circularDictionary, Formatting.Indented); }, @"Self referencing loop detected with type '" + classRef + "'. Path ''.");
}
[Test]
@@ -290,17 +284,15 @@ namespace Newtonsoft.Json.Tests.Serialization
string json = @"{
""$id"":";
ExceptionAssert.Throws<JsonSerializationException>(
@"Unexpected end when deserializing object. Path '$id', line 2, position 9.",
() =>
{
JsonConvert.DeserializeObject<string[][]>(json,
new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All,
MetadataPropertyHandling = MetadataPropertyHandling.Default
});
});
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
JsonConvert.DeserializeObject<string[][]>(json,
new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All,
MetadataPropertyHandling = MetadataPropertyHandling.Default
});
}, @"Unexpected end when deserializing object. Path '$id', line 2, position 9.");
}
public class CircularReferenceClassConverter : JsonConverter
@@ -1065,12 +1057,10 @@ namespace Newtonsoft.Json.Tests.Serialization
}
}";
ExceptionAssert.Throws<JsonSerializationException>(
"Error reading object reference '1'. Path 'Data.Prop2.MyProperty', line 9, position 20.",
() => JsonConvert.DeserializeObject<PropertyItemIsReferenceObject>(json, new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Default
}));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<PropertyItemIsReferenceObject>(json, new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Default
}), "Error reading object reference '1'. Path 'Data.Prop2.MyProperty', line 9, position 20.");
}
}
@@ -186,9 +186,7 @@ namespace Newtonsoft.Json.Tests.Serialization
var settings =
new JsonSerializerSettings();
ExceptionAssert.Throws<JsonSerializationException>(
"Self referencing loop detected with type 'Newtonsoft.Json.Tests.Serialization.ReferenceLoopHandlingTests+MainClass'. Path 'Child'.",
() => JsonConvert.SerializeObject(main, settings));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.SerializeObject(main, settings), "Self referencing loop detected with type 'Newtonsoft.Json.Tests.Serialization.ReferenceLoopHandlingTests+MainClass'. Path 'Child'.");
}
[Test]
@@ -247,9 +245,7 @@ namespace Newtonsoft.Json.Tests.Serialization
var settings = new JsonSerializerSettings();
ExceptionAssert.Throws<JsonSerializationException>(
"Self referencing loop detected with type 'Newtonsoft.Json.Tests.Serialization.ReferenceLoopHandlingTests+DictionaryDynamicObject'. Path 'child'.",
() => JsonConvert.SerializeObject(parent, settings));
ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.SerializeObject(parent, settings), "Self referencing loop detected with type 'Newtonsoft.Json.Tests.Serialization.ReferenceLoopHandlingTests+DictionaryDynamicObject'. Path 'child'.");
}
[Test]
@@ -728,9 +728,7 @@ namespace Newtonsoft.Json.Tests.Serialization
JsonTextReader jReader = new JsonTextReader(new StreamReader(stream));
JsonSerializer s = new JsonSerializer();
ExceptionAssert.Throws<JsonReaderException>(
@"Unterminated string. Expected delimiter: "". Path '', line 1, position 3.",
() => { ErrorTestObject obj = s.Deserialize<ErrorTestObject>(jReader); });
ExceptionAssert.Throws<JsonReaderException>(() => { ErrorTestObject obj = s.Deserialize<ErrorTestObject>(jReader); }, @"Unterminated string. Expected delimiter: "". Path '', line 1, position 3.");
}
public class RootThing
@@ -833,9 +831,7 @@ namespace Newtonsoft.Json.Tests.Serialization
string foo = "{ something: { rootSomethingElse { somethingElse: 0 } } }";
var reader = new System.IO.StringReader(foo);
ExceptionAssert.Throws<Exception>(
"An error occurred.",
() => { serialiser.Deserialize(reader, typeof(Something)); });
ExceptionAssert.Throws<Exception>(() => { serialiser.Deserialize(reader, typeof(Something)); }, "An error occurred.");
}
[Test]
@@ -857,9 +853,7 @@ namespace Newtonsoft.Json.Tests.Serialization
var writer = new System.IO.StringWriter();
ExceptionAssert.Throws<Exception>(
"An error occurred.",
() => { serialiser.Serialize(writer, r); });
ExceptionAssert.Throws<Exception>(() => { serialiser.Serialize(writer, r); }, "An error occurred.");
}
[Test]
@@ -442,9 +442,7 @@ OnSerialized_Derived_Derived", string.Join(Environment.NewLine, e.ToArray()));
}
};
ExceptionAssert.Throws<JsonException>(
"Serialization Callback 'Void Deserialized()' in type 'Newtonsoft.Json.Tests.Serialization.Contract' must have a single parameter of type 'System.Runtime.Serialization.StreamingContext'.",
() => JsonConvert.SerializeObject(d, Formatting.Indented));
ExceptionAssert.Throws<JsonException>(() => JsonConvert.SerializeObject(d, Formatting.Indented), "Serialization Callback 'Void Deserialized()' in type 'Newtonsoft.Json.Tests.Serialization.Contract' must have a single parameter of type 'System.Runtime.Serialization.StreamingContext'.");
}
}
@@ -360,17 +360,15 @@ Newtonsoft.Json Error: 0 : Error!
LevelFilter = TraceLevel.Info
};
ExceptionAssert.Throws<Exception>(
"Could not convert string to integer: hi. Path 'Integer', line 1, position 15.",
() =>
{
JsonConvert.DeserializeObject<IntegerTestClass>(
json,
new JsonSerializerSettings
{
TraceWriter = traceWriter
});
});
ExceptionAssert.Throws<Exception>(() =>
{
JsonConvert.DeserializeObject<IntegerTestClass>(
json,
new JsonSerializerSettings
{
TraceWriter = traceWriter
});
}, "Could not convert string to integer: hi. Path 'Integer', line 1, position 15.");
Assert.AreEqual(2, traceWriter.TraceRecords.Count);
@@ -391,17 +389,15 @@ Newtonsoft.Json Error: 0 : Error!
LevelFilter = TraceLevel.Info
};
ExceptionAssert.Throws<Exception>(
"Could not convert string to integer: two. Path 'IntList[1]', line 1, position 20.",
() =>
{
JsonConvert.DeserializeObject<TraceTestObject>(
json,
new JsonSerializerSettings
{
TraceWriter = traceWriter
});
});
ExceptionAssert.Throws<Exception>(() =>
{
JsonConvert.DeserializeObject<TraceTestObject>(
json,
new JsonSerializerSettings
{
TraceWriter = traceWriter
});
}, "Could not convert string to integer: two. Path 'IntList[1]', line 1, position 20.");
Assert.AreEqual(3, traceWriter.TraceRecords.Count);
@@ -609,17 +605,15 @@ Newtonsoft.Json Error: 0 : Error!
LevelFilter = TraceLevel.Verbose
};
ExceptionAssert.Throws<SerializationException>(
"Member 'ClassName' was not found.",
() =>
{
JsonConvert.DeserializeObject<Exception>(
"{}",
new JsonSerializerSettings
{
TraceWriter = traceWriter
});
});
ExceptionAssert.Throws<SerializationException>(() =>
{
JsonConvert.DeserializeObject<Exception>(
"{}",
new JsonSerializerSettings
{
TraceWriter = traceWriter
});
}, "Member 'ClassName' was not found.");
Assert.IsTrue(traceWriter.TraceRecords[0].Message.StartsWith("Deserializing System.Exception using ISerializable constructor. Path ''"));
Assert.AreEqual(TraceLevel.Info, traceWriter.TraceRecords[0].Level);
@@ -118,13 +118,13 @@ namespace Newtonsoft.Json.Tests.Serialization
sb.Append(@"{""$value"":");
}
ExceptionAssert.Throws<JsonSerializationException>("Unexpected token when deserializing primitive value: StartObject. Path '$value', line 1, position 11.", () =>
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
var reader = new JsonTextReader(new StringReader(sb.ToString()));
var ser = new JsonSerializer();
ser.MetadataPropertyHandling = MetadataPropertyHandling.Default;
ser.Deserialize<bool>(reader);
});
}, "Unexpected token when deserializing primitive value: StartObject. Path '$value', line 1, position 11.");
}
[Test]
@@ -438,15 +438,13 @@ namespace Newtonsoft.Json.Tests.Serialization
""Manager"": null
}";
ExceptionAssert.Throws<JsonSerializationException>(
"Type specified in JSON 'Newtonsoft.Json.Tests.TestObjects.Employee' was not resolved. Path '$type', line 3, position 56.",
() =>
ExceptionAssert.Throws<JsonSerializationException>(() =>
{
JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
{
JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
});
TypeNameHandling = TypeNameHandling.Objects
});
}, "Type specified in JSON 'Newtonsoft.Json.Tests.TestObjects.Employee' was not resolved. Path '$type', line 3, position 56.");
}
public interface ICorrelatedMessage
+1 -21
View File
@@ -196,26 +196,6 @@ namespace Newtonsoft.Json.Tests
public static class ExceptionAssert
{
public static void Throws<TException>(string message, Action action)
where TException : Exception
{
try
{
action();
Assert.Fail("Exception of type {0} expected; got none exception", typeof(TException).Name);
}
catch (TException ex)
{
if (message != null)
Assert.AreEqual(message, ex.Message, "Unexpected exception message." + Environment.NewLine + "Expected: " + message + Environment.NewLine + "Got: " + ex.Message + Environment.NewLine + Environment.NewLine + ex);
}
catch (Exception ex)
{
throw new Exception(string.Format("Exception of type {0} expected; got exception of type {1}.", typeof(TException).Name, ex.GetType().Name), ex);
}
}
public static void Throws<TException>(Action action, params string[] possibleMessages)
where TException : Exception
{
@@ -223,7 +203,7 @@ namespace Newtonsoft.Json.Tests
{
action();
Assert.Fail("Exception of type {0} expected; got none exception", typeof(TException).Name);
Assert.Fail("Exception of type {0} expected. No exception thrown.", typeof(TException).Name);
}
catch (TException ex)
{
@@ -94,69 +94,65 @@ namespace Newtonsoft.Json.Tests.Utilities
[Test]
public void CreateGetWithBadObjectTarget()
{
ExceptionAssert.Throws<InvalidCastException>("Unable to cast object of type 'Newtonsoft.Json.Tests.TestObjects.Person' to type 'Newtonsoft.Json.Tests.TestObjects.Movie'.",
() =>
{
Person p = new Person();
p.Name = "Hi";
ExceptionAssert.Throws<InvalidCastException>(() =>
{
Person p = new Person();
p.Name = "Hi";
Func<object, object> setter = DynamicReflectionDelegateFactory.Instance.CreateGet<object>(typeof(Movie).GetProperty("Name"));
Func<object, object> setter = DynamicReflectionDelegateFactory.Instance.CreateGet<object>(typeof(Movie).GetProperty("Name"));
setter(p);
});
setter(p);
}, "Unable to cast object of type 'Newtonsoft.Json.Tests.TestObjects.Person' to type 'Newtonsoft.Json.Tests.TestObjects.Movie'.");
}
[Test]
public void CreateSetWithBadObjectTarget()
{
ExceptionAssert.Throws<InvalidCastException>("Unable to cast object of type 'Newtonsoft.Json.Tests.TestObjects.Person' to type 'Newtonsoft.Json.Tests.TestObjects.Movie'.",
() =>
{
Person p = new Person();
Movie m = new Movie();
ExceptionAssert.Throws<InvalidCastException>(() =>
{
Person p = new Person();
Movie m = new Movie();
Action<object, object> setter = DynamicReflectionDelegateFactory.Instance.CreateSet<object>(typeof(Movie).GetProperty("Name"));
Action<object, object> setter = DynamicReflectionDelegateFactory.Instance.CreateSet<object>(typeof(Movie).GetProperty("Name"));
setter(m, "Hi");
setter(m, "Hi");
Assert.AreEqual(m.Name, "Hi");
Assert.AreEqual(m.Name, "Hi");
setter(p, "Hi");
setter(p, "Hi");
Assert.AreEqual(p.Name, "Hi");
});
Assert.AreEqual(p.Name, "Hi");
}, "Unable to cast object of type 'Newtonsoft.Json.Tests.TestObjects.Person' to type 'Newtonsoft.Json.Tests.TestObjects.Movie'.");
}
[Test]
public void CreateSetWithBadTarget()
{
ExceptionAssert.Throws<InvalidCastException>("Specified cast is not valid.",
() =>
{
object structTest = new StructTest();
ExceptionAssert.Throws<InvalidCastException>(() =>
{
object structTest = new StructTest();
Action<object, object> setter = DynamicReflectionDelegateFactory.Instance.CreateSet<object>(typeof(StructTest).GetProperty("StringProperty"));
Action<object, object> setter = DynamicReflectionDelegateFactory.Instance.CreateSet<object>(typeof(StructTest).GetProperty("StringProperty"));
setter(structTest, "Hi");
setter(structTest, "Hi");
Assert.AreEqual("Hi", ((StructTest)structTest).StringProperty);
Assert.AreEqual("Hi", ((StructTest)structTest).StringProperty);
setter(new TimeSpan(), "Hi");
});
setter(new TimeSpan(), "Hi");
}, "Specified cast is not valid.");
}
[Test]
public void CreateSetWithBadObjectValue()
{
ExceptionAssert.Throws<InvalidCastException>("Unable to cast object of type 'System.Version' to type 'System.String'.",
() =>
{
Movie m = new Movie();
ExceptionAssert.Throws<InvalidCastException>(() =>
{
Movie m = new Movie();
Action<object, object> setter = DynamicReflectionDelegateFactory.Instance.CreateSet<object>(typeof(Movie).GetProperty("Name"));
Action<object, object> setter = DynamicReflectionDelegateFactory.Instance.CreateSet<object>(typeof(Movie).GetProperty("Name"));
setter(m, new Version("1.1.1.1"));
});
setter(m, new Version("1.1.1.1"));
}, "Unable to cast object of type 'System.Version' to type 'System.String'.");
}
[Test]