-Explicit culture for tests

-Tests
This commit is contained in:
James Newton-King
2014-12-22 00:11:57 +13:00
parent 55ccac4d92
commit e9dc993fc3
23 changed files with 442 additions and 74 deletions
@@ -33,4 +33,4 @@ using System.Runtime.InteropServices;
// by using the '*' as shown below:
// [assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyFileVersion("6.0.7.18007")]
[assembly: AssemblyFileVersion("6.0.7.18022")]
@@ -462,6 +462,85 @@ namespace Newtonsoft.Json.Tests.Converters
Assert.AreEqual("234", ds.Customers[0].CustomerID);
}
[Test]
public void ContractResolverInsideConverter()
{
var test = new MultipleDataTablesJsonTest
{
TableWrapper1 = new DataTableWrapper { DataTableProperty = CreateDataTable(3, "Table1Col") },
TableWrapper2 = new DataTableWrapper { DataTableProperty = CreateDataTable(3, "Table2Col") }
};
string json = JsonConvert.SerializeObject(test, Formatting.Indented, new LowercaseDataTableConverter());
Assert.AreEqual(@"{
""TableWrapper1"": {
""DataTableProperty"": [
{
""table1col1"": ""1"",
""table1col2"": ""2"",
""table1col3"": ""3""
}
],
""StringProperty"": null,
""IntProperty"": 0
},
""TableWrapper2"": {
""DataTableProperty"": [
{
""table2col1"": ""1"",
""table2col2"": ""2"",
""table2col3"": ""3""
}
],
""StringProperty"": null,
""IntProperty"": 0
}
}", json);
}
private static DataTable CreateDataTable(int cols, string colNamePrefix)
{
var table = new DataTable();
for (int i = 1; i <= cols; i++)
{
table.Columns.Add(new DataColumn() { ColumnName = colNamePrefix + i, DefaultValue = i });
}
table.Rows.Add(table.NewRow());
return table;
}
public class DataTableWrapper
{
public DataTable DataTableProperty { get; set; }
public String StringProperty { get; set; }
public Int32 IntProperty { get; set; }
}
public class MultipleDataTablesJsonTest
{
public DataTableWrapper TableWrapper1 { get; set; }
public DataTableWrapper TableWrapper2 { get; set; }
}
public class LowercaseDataTableConverter : DataTableConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dataTableSerializer = new JsonSerializer { ContractResolver = new LowercaseContractResolver() };
base.WriteJson(writer, value, dataTableSerializer);
}
}
public class LowercaseContractResolver : DefaultContractResolver
{
protected internal override string ResolvePropertyName(string propertyName)
{
return propertyName.ToLower();
}
}
}
}
@@ -241,6 +241,7 @@
<Compile Include="Schema\JsonSchemaNodeTests.cs" />
<Compile Include="Schema\JsonSchemaSpecTests.cs" />
<Compile Include="Schema\JsonSchemaTests.cs" />
<Compile Include="Schema\PerformanceTests.cs" />
<Compile Include="Serialization\CamelCasePropertyNamesContractResolverTests.cs" />
<Compile Include="Serialization\ConstructorHandlingTests.cs" />
<Compile Include="Serialization\ContractResolverTests.cs" />
@@ -76,4 +76,4 @@ using System.Security;
// by using the '*' as shown below:
[assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyFileVersion("6.0.7.18007")]
[assembly: AssemblyFileVersion("6.0.7.18022")]
@@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Schema;
using NUnit.Framework;
namespace Newtonsoft.Json.Tests.Schema
{
[TestFixture]
public class PerformanceTests : TestFixtureBase
{
[Test]
public void ReaderPerformance()
{
string json = @"[
{
""id"": 2,
""name"": ""An ice sculpture"",
""price"": 12.50,
""tags"": [""cold"", ""ice""],
""dimensions"": {
""length"": 7.0,
""width"": 12.0,
""height"": 9.5
},
""warehouseLocation"": {
""latitude"": -78.75,
""longitude"": 20.4
}
},
{
""id"": 3,
""name"": ""A blue mouse"",
""price"": 25.50,
""dimensions"": {
""length"": 3.1,
""width"": 1.0,
""height"": 1.0
},
""warehouseLocation"": {
""latitude"": 54.4,
""longitude"": -32.7
}
}
]";
JsonSchema schema = JsonSchema.Parse(@"{
""$schema"": ""http://json-schema.org/draft-04/schema#"",
""title"": ""Product set"",
""type"": ""array"",
""items"": {
""title"": ""Product"",
""type"": ""object"",
""properties"": {
""id"": {
""description"": ""The unique identifier for a product"",
""type"": ""number"",
""required"": true
},
""name"": {
""type"": ""string"",
""required"": true
},
""price"": {
""type"": ""number"",
""minimum"": 0,
""exclusiveMinimum"": true,
""required"": true
},
""tags"": {
""type"": ""array"",
""items"": {
""type"": ""string""
},
""minItems"": 1,
""uniqueItems"": true
},
""dimensions"": {
""type"": ""object"",
""properties"": {
""length"": {""type"": ""number"",""required"": true},
""width"": {""type"": ""number"",""required"": true},
""height"": {""type"": ""number"",""required"": true}
}
},
""warehouseLocation"": {
""description"": ""A geographical coordinate"",
""type"": ""object"",
""properties"": {
""latitude"": { ""type"": ""number"" },
""longitude"": { ""type"": ""number"" }
}
}
}
}
}");
using (var tester = new PerformanceTester("Reader"))
{
for (int i = 0; i < 5000; i++)
{
JsonTextReader reader = new JsonTextReader(new StringReader(json));
JsonValidatingReader validatingReader = new JsonValidatingReader(reader);
validatingReader.Schema = schema;
while (validatingReader.Read())
{
}
}
}
}
}
public class PerformanceTester : IDisposable
{
private readonly Stopwatch _stopwatch = new Stopwatch();
private readonly Action<TimeSpan> _callback;
public PerformanceTester(string description)
: this(ts => Console.WriteLine(description + ": " + ts.TotalSeconds))
{
}
public PerformanceTester(Action<TimeSpan> callback)
{
_callback = callback;
_stopwatch.Start();
}
public static PerformanceTester Start(Action<TimeSpan> callback)
{
return new PerformanceTester(callback);
}
public void Dispose()
{
_stopwatch.Stop();
if (_callback != null)
_callback(Result);
}
public TimeSpan Result
{
get { return _stopwatch.Elapsed; }
}
}
}
@@ -368,6 +368,20 @@ namespace Newtonsoft.Json.Tests.Serialization
Assert.AreEqual("fff", obj.Field1);
}
#endif
[Test]
public void PopulateTest()
{
var test = JsonConvert.DeserializeObject<PopulateWithNullJsonTest>("{\"IntValue\":null}");
Console.WriteLine("IntValue:{0}", test.IntValue);
}
public class PopulateWithNullJsonTest
{
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate, NullValueHandling = NullValueHandling.Ignore)]
[DefaultValue(6)]
public int IntValue { get; set; }
}
}
#if !NET20
@@ -8374,6 +8374,46 @@ Path '', line 1, position 1.");
}
#endif
[Test]
public void ParameterizedConstructorWithBasePrivateProperties()
{
var original = new DerivedConstructorType("Base", "Derived");
var serializerSettings = new JsonSerializerSettings();
var jsonCopy = JsonConvert.SerializeObject(original, serializerSettings);
Console.WriteLine(original);
var clonedObject = JsonConvert.DeserializeObject<DerivedConstructorType>(jsonCopy, serializerSettings);
Assert.AreEqual("Base", clonedObject.BaseProperty);
Assert.AreEqual("Derived", clonedObject.DerivedProperty);
}
public class DerivedConstructorType : BaseConstructorType
{
public DerivedConstructorType(string baseProperty, string derivedProperty)
: base(baseProperty)
{
DerivedProperty = derivedProperty;
}
[JsonProperty]
public string DerivedProperty { get; private set; }
}
public class BaseConstructorType
{
[JsonProperty]
public string BaseProperty { get; private set; }
public BaseConstructorType(string baseProperty)
{
BaseProperty = baseProperty;
}
}
public class ErroringJsonConverter : JsonConverter
{
public ErroringJsonConverter(string s)
@@ -23,6 +23,11 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
#if !(PORTABLE || PORTABLE40)
using System.Collections.ObjectModel;
#if !(NET35 || NET20)
@@ -1836,6 +1841,55 @@ namespace Newtonsoft.Json.Tests.Serialization
Assert.AreEqual(1UL, item.WantedUnitID);
}
#endif
#if !(NET20 || NET35)
[Test]
public void GenericItemTypeCollection()
{
DataType data = new DataType();
data.Rows.Add("key", new List<MyInterfaceImplementationType> { new MyInterfaceImplementationType() { SomeProperty = "property" } });
string serialized = JsonConvert.SerializeObject(data, Formatting.Indented);
StringAssert.AreEqual(@"{
""Rows"": {
""key"": {
""$type"": ""System.Collections.Generic.List`1[[Newtonsoft.Json.Tests.Serialization.MyInterfaceImplementationType, Newtonsoft.Json.Tests]], mscorlib"",
""$values"": [
{
""SomeProperty"": ""property""
}
]
}
}
}", serialized);
DataType deserialized = JsonConvert.DeserializeObject<DataType>(serialized);
Assert.AreEqual("property", deserialized.Rows["key"].First().SomeProperty);
}
#endif
}
public class DataType
{
public DataType()
{
Rows = new Dictionary<string, IEnumerable<IMyInterfaceType>>();
}
[JsonProperty(ItemTypeNameHandling = TypeNameHandling.Auto, TypeNameHandling = TypeNameHandling.Auto)]
public Dictionary<string, IEnumerable<IMyInterfaceType>> Rows { get; private set; }
}
public interface IMyInterfaceType
{
string SomeProperty { get; set; }
}
public class MyInterfaceImplementationType : IMyInterfaceType
{
public string SomeProperty { get; set; }
}
#if !(NETFX_CORE || ASPNETCORE50)
+5 -2
View File
@@ -261,11 +261,14 @@ namespace Newtonsoft.Json.Tests
protected void TestSetup()
#endif
{
//#if !NETFX_CORE
#if !NETFX_CORE
// CultureInfo turkey = CultureInfo.CreateSpecificCulture("tr");
// Thread.CurrentThread.CurrentCulture = turkey;
// Thread.CurrentThread.CurrentUICulture = turkey;
//#endif
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
#endif
JsonConvert.DefaultSettings = null;
}
@@ -79,7 +79,7 @@ namespace Newtonsoft.Json.Converters
case JsonToken.StartArray:
return ReadList(reader);
default:
if (JsonReader.IsPrimitiveToken(reader.TokenType))
if (JsonTokenUtils.IsPrimitiveToken(reader.TokenType))
return reader.Value;
throw JsonSerializationException.Create(reader, "Unexpected token when converting ExpandoObject: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
+3 -34
View File
@@ -251,7 +251,7 @@ namespace Newtonsoft.Json
get
{
int depth = _stack.Count;
if (IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None)
if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None)
return depth;
else
return depth + 1;
@@ -712,7 +712,7 @@ namespace Newtonsoft.Json
if (t == JsonToken.Null)
return null;
if (IsPrimitiveToken(t))
if (JsonTokenUtils.IsPrimitiveToken(t))
{
if (Value != null)
{
@@ -823,7 +823,7 @@ namespace Newtonsoft.Json
if (TokenType == JsonToken.PropertyName)
Read();
if (IsStartToken(TokenType))
if (JsonTokenUtils.IsStartToken(TokenType))
{
int depth = Depth;
@@ -963,37 +963,6 @@ namespace Newtonsoft.Json
_currentState = State.Finished;
}
internal static bool IsPrimitiveToken(JsonToken token)
{
switch (token)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Undefined:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.Bytes:
return true;
default:
return false;
}
}
internal static bool IsStartToken(JsonToken token)
{
switch (token)
{
case JsonToken.StartObject:
case JsonToken.StartArray:
case JsonToken.StartConstructor:
return true;
default:
return false;
}
}
private JsonContainerType GetTypeForCloseToken(JsonToken token)
{
switch (token)
+1 -1
View File
@@ -37,7 +37,7 @@ using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data.
/// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data.
/// </summary>
public class JsonTextWriter : JsonWriter
{
+2 -2
View File
@@ -461,7 +461,7 @@ namespace Newtonsoft.Json
JsonSchemaModelBuilder builder = new JsonSchemaModelBuilder();
_model = builder.Build(_schema);
if (!JsonWriter.IsStartToken(_reader.TokenType))
if (!JsonTokenUtils.IsStartToken(_reader.TokenType))
Push(new SchemaScope(JTokenType.None, CurrentMemberSchemas));
}
@@ -578,7 +578,7 @@ namespace Newtonsoft.Json
{
if (schemaScope.CurrentItemWriter == null)
{
if (JsonWriter.IsEndToken(_reader.TokenType))
if (JsonTokenUtils.IsEndToken(_reader.TokenType))
continue;
schemaScope.CurrentItemWriter = new JTokenWriter();
+3 -29
View File
@@ -41,7 +41,7 @@ using System.Linq;
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data.
/// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data.
/// </summary>
public abstract class JsonWriter : IDisposable
{
@@ -477,7 +477,7 @@ namespace Newtonsoft.Json
if (reader.TokenType == JsonToken.None)
initialDepth = -1;
else if (!IsStartToken(reader.TokenType))
else if (!JsonTokenUtils.IsStartToken(reader.TokenType))
initialDepth = reader.Depth + 1;
else
initialDepth = reader.Depth;
@@ -496,7 +496,7 @@ namespace Newtonsoft.Json
WriteTokenInternal(reader.TokenType, reader.Value);
} while (
// stop if we have reached the end of the token being read
initialDepth - 1 < reader.Depth - (IsEndToken(reader.TokenType) ? 1 : 0)
initialDepth - 1 < reader.Depth - (JsonTokenUtils.IsEndToken(reader.TokenType) ? 1 : 0)
&& writeChildren
&& reader.Read());
}
@@ -614,32 +614,6 @@ namespace Newtonsoft.Json
WriteValue(date);
}
internal static bool IsEndToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
case JsonToken.EndArray:
case JsonToken.EndConstructor:
return true;
default:
return false;
}
}
internal static bool IsStartToken(JsonToken token)
{
switch (token)
{
case JsonToken.StartObject:
case JsonToken.StartArray:
case JsonToken.StartConstructor:
return true;
default:
return false;
}
}
private void WriteEnd(JsonContainerType type)
{
switch (type)
@@ -136,6 +136,7 @@
<Compile Include="Utilities\DynamicUtils.cs" />
<Compile Include="Utilities\ExpressionReflectionDelegateFactory.cs" />
<Compile Include="Utilities\ImmutableCollectionsUtils.cs" />
<Compile Include="Utilities\JsonTokenUtils.cs" />
<Compile Include="Utilities\LinqBridge.cs" />
<Compile Include="Linq\JPropertyDescriptor.cs" />
<Compile Include="Linq\JRaw.cs" />
@@ -244,6 +244,7 @@
<Compile Include="Utilities\FSharpUtils.cs" />
<Compile Include="Utilities\ILGeneratorExtensions.cs" />
<Compile Include="Utilities\ImmutableCollectionsUtils.cs" />
<Compile Include="Utilities\JsonTokenUtils.cs" />
<Compile Include="Utilities\LinqBridge.cs" />
<Compile Include="Utilities\PropertyNameTable.cs" />
<Compile Include="Utilities\ReflectionDelegateFactory.cs" />
@@ -244,6 +244,7 @@
<Compile Include="Utilities\FSharpUtils.cs" />
<Compile Include="Utilities\ILGeneratorExtensions.cs" />
<Compile Include="Utilities\ImmutableCollectionsUtils.cs" />
<Compile Include="Utilities\JsonTokenUtils.cs" />
<Compile Include="Utilities\LinqBridge.cs" />
<Compile Include="Utilities\PropertyNameTable.cs" />
<Compile Include="Utilities\ReflectionDelegateFactory.cs" />
@@ -216,6 +216,7 @@
<Compile Include="Utilities\ILGeneratorExtensions.cs" />
<Compile Include="Utilities\ImmutableCollectionsUtils.cs" />
<Compile Include="Utilities\JavaScriptUtils.cs" />
<Compile Include="Utilities\JsonTokenUtils.cs" />
<Compile Include="Utilities\LateBoundReflectionDelegateFactory.cs" />
<Compile Include="Utilities\LinqBridge.cs" />
<Compile Include="Utilities\MathUtils.cs" />
@@ -220,6 +220,7 @@
<Compile Include="Utilities\FSharpUtils.cs" />
<Compile Include="Utilities\ILGeneratorExtensions.cs" />
<Compile Include="Utilities\JavaScriptUtils.cs" />
<Compile Include="Utilities\JsonTokenUtils.cs" />
<Compile Include="Utilities\LateBoundReflectionDelegateFactory.cs" />
<Compile Include="Utilities\LinqBridge.cs" />
<Compile Include="Utilities\MathUtils.cs" />
@@ -213,6 +213,7 @@
<Compile Include="Utilities\DynamicProxyMetaObject.cs" />
<Compile Include="Utilities\DynamicReflectionDelegateFactory.cs" />
<Compile Include="Utilities\DynamicUtils.cs" />
<Compile Include="Utilities\JsonTokenUtils.cs" />
<Compile Include="Utilities\PropertyNameTable.cs" />
<Compile Include="Utilities\ReflectionObject.cs" />
<Compile Include="Utilities\EnumUtils.cs" />
@@ -92,5 +92,5 @@ using System.Security;
// by using the '*' as shown below:
[assembly: AssemblyVersion("6.0.0.0")]
[assembly: AssemblyFileVersion("6.0.7.18007")]
[assembly: AssemblyFileVersion("6.0.7.18022")]
[assembly: CLSCompliant(true)]
@@ -967,7 +967,7 @@ namespace Newtonsoft.Json.Serialization
// test tokentype here because default value might not be convertable to actual type, e.g. default of "" for DateTime
if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore)
&& !HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate)
&& JsonReader.IsPrimitiveToken(tokenType)
&& JsonTokenUtils.IsPrimitiveToken(tokenType)
&& MiscellaneousUtils.ValueEquals(reader.Value, property.GetResolvedDefaultValue()))
return true;
@@ -1563,7 +1563,7 @@ namespace Newtonsoft.Json.Serialization
}
else
{
Type t = (JsonReader.IsPrimitiveToken(reader.TokenType)) ? reader.ValueType : typeof(IDynamicMetaObjectProvider);
Type t = (JsonTokenUtils.IsPrimitiveToken(reader.TokenType)) ? reader.ValueType : typeof(IDynamicMetaObjectProvider);
JsonContract dynamicMemberContract = GetContractSafe(t);
JsonConverter dynamicMemberConverter = GetConverter(dynamicMemberContract, null, null, member);
@@ -0,0 +1,77 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Text;
namespace Newtonsoft.Json.Utilities
{
internal static class JsonTokenUtils
{
internal static bool IsEndToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
case JsonToken.EndArray:
case JsonToken.EndConstructor:
return true;
default:
return false;
}
}
internal static bool IsStartToken(JsonToken token)
{
switch (token)
{
case JsonToken.StartObject:
case JsonToken.StartArray:
case JsonToken.StartConstructor:
return true;
default:
return false;
}
}
internal static bool IsPrimitiveToken(JsonToken token)
{
switch (token)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Undefined:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.Bytes:
return true;
default:
return false;
}
}
}
}