Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,78 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Drawing;
using System.Globalization;
using Xunit;
namespace System.Web.Helpers.Test
{
public class ConversionUtilTest
{
[Fact]
public void ConversionUtilReturnsStringTypes()
{
// Arrange
string original = "Foo";
// Act
object result;
bool success = ConversionUtil.TryFromString(typeof(String), original, out result);
// Assert
Assert.True(success);
Assert.Equal(original, result);
}
[Fact]
public void ConversionUtilConvertsStringsToColor()
{
// Arrange
string original = "Blue";
// Act
object result;
bool success = ConversionUtil.TryFromString(typeof(Color), original, out result);
// Assert
Assert.True(success);
Assert.Equal(Color.Blue, result);
}
[Fact]
public void ConversionUtilConvertsEnumValues()
{
// Arrange
string original = "Weekday";
// Act
object result;
bool success = ConversionUtil.TryFromString(typeof(TestEnum), original, out result);
// Assert
Assert.True(success);
Assert.Equal(TestEnum.Weekday, result);
}
[Fact]
public void ConversionUtilUsesTypeConverterToConvertArbitraryTypes()
{
// Arrange
var date = new DateTime(2010, 01, 01);
string original = date.ToString(CultureInfo.InvariantCulture);
// Act
object result;
bool success = ConversionUtil.TryFromString(typeof(DateTime), original, out result);
// Assert
Assert.True(success);
Assert.Equal(date, result);
}
private enum TestEnum
{
Weekend,
Weekday
}
}
}

View File

@ -0,0 +1,172 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Helpers.Test
{
/// <summary>
///This is a test class for CryptoTest and is intended
///to contain all CryptoTest Unit Tests
///</summary>
public class CryptoTest
{
[Fact]
public void SHA256HashTest_ReturnsValidData()
{
string data = "foo bar";
string expected = "FBC1A9F858EA9E177916964BD88C3D37B91A1E84412765E29950777F265C4B75";
string actual;
actual = Crypto.SHA256(data);
Assert.Equal(expected, actual);
actual = Crypto.Hash(Encoding.UTF8.GetBytes(data));
Assert.Equal(expected, actual);
}
[Fact]
public void GenerateSaltTest()
{
string salt = Crypto.GenerateSalt();
salt = Crypto.GenerateSalt(64);
Assert.Equal(24, Crypto.GenerateSalt().Length);
Assert.Equal(12, Crypto.GenerateSalt(8).Length);
Assert.Equal(88, Crypto.GenerateSalt(64).Length);
Assert.Equal(44, Crypto.GenerateSalt(32).Length);
}
[Fact]
public void HashPassword_PasswordGeneration()
{
// Act - call helper directly
string generatedHash = Crypto.HashPassword("my-password");
byte[] salt = new byte[16];
Buffer.BlockCopy(Convert.FromBase64String(generatedHash), 1, salt, 0, 16); // extract salt from generated hash
// Act - perform PBKDF2 directly
string generatedHash2;
using (var ms = new MemoryStream())
{
using (var bw = new BinaryWriter(ms))
{
using (var deriveBytes = new Rfc2898DeriveBytes("my-password", salt, iterations: 1000))
{
bw.Write((byte)0x00); // version identifier
bw.Write(salt); // salt
bw.Write(deriveBytes.GetBytes(32)); // subkey
}
generatedHash2 = Convert.ToBase64String(ms.ToArray());
}
}
// Assert
Assert.Equal(generatedHash2, generatedHash);
}
[Fact]
public void HashPassword_RoundTripping()
{
// Act & assert
string password = "ImPepper";
Assert.True(Crypto.VerifyHashedPassword(Crypto.HashPassword(password), password));
Assert.False(Crypto.VerifyHashedPassword(Crypto.HashPassword(password), "ImSalt"));
Assert.False(Crypto.VerifyHashedPassword(Crypto.HashPassword("Impepper"), password));
}
[Fact]
public void VerifyHashedPassword_CorrectPassword_ReturnsTrue()
{
// Arrange
string hashedPassword = "ALyuoraY/cIWD1hjo+K81/pf83qo6Q6T+UBYcXN9P3A9WHLvEY10f+lwW5qPG6h9xw=="; // this is for 'my-password'
// Act
bool retVal = Crypto.VerifyHashedPassword(hashedPassword, "my-password");
// Assert
Assert.True(retVal);
}
[Fact]
public void VerifyHashedPassword_IncorrectPassword_ReturnsFalse()
{
// Arrange
string hashedPassword = "ALyuoraY/cIWD1hjo+K81/pf83qo6Q6T+UBYcXN9P3A9WHLvEY10f+lwW5qPG6h9xw=="; // this is for 'my-password'
// Act
bool retVal = Crypto.VerifyHashedPassword(hashedPassword, "some-other-password");
// Assert
Assert.False(retVal);
}
[Fact]
public void VerifyHashedPassword_InvalidPasswordHash_ReturnsFalse()
{
// Arrange
string hashedPassword = "AAECAw=="; // this is an invalid password hash
// Act
bool retVal = Crypto.VerifyHashedPassword(hashedPassword, "hello-world");
// Assert
Assert.False(retVal);
}
[Fact]
public void MD5HashTest_ReturnsValidData()
{
string data = "foo bar";
string expected = "327B6F07435811239BC47E1544353273";
string actual;
actual = Crypto.Hash(data, algorithm: "md5");
Assert.Equal(expected, actual);
actual = Crypto.Hash(Encoding.UTF8.GetBytes(data), algorithm: "MD5");
Assert.Equal(expected, actual);
}
[Fact]
public void SHA1HashTest_ReturnsValidData()
{
string data = "foo bar";
string expected = "3773DEA65156909838FA6C22825CAFE090FF8030";
string actual;
actual = Crypto.SHA1(data);
Assert.Equal(expected, actual);
actual = Crypto.Hash(Encoding.UTF8.GetBytes(data), algorithm: "sha1");
Assert.Equal(expected, actual);
}
[Fact]
public void SHA1HashTest_WithNull_ThrowsException()
{
Assert.Throws<ArgumentNullException>(() => Crypto.SHA1((string)null));
Assert.Throws<ArgumentNullException>(() => Crypto.Hash((byte[])null, algorithm: "SHa1"));
}
[Fact]
public void SHA256HashTest_WithNull_ThrowsException()
{
Assert.Throws<ArgumentNullException>(() => Crypto.SHA256((string)null));
Assert.Throws<ArgumentNullException>(() => Crypto.Hash((byte[])null, algorithm: "sHa256"));
}
[Fact]
public void MD5HashTest_WithNull_ThrowsException()
{
Assert.Throws<ArgumentNullException>(() => Crypto.Hash((string)null, algorithm: "mD5"));
Assert.Throws<ArgumentNullException>(() => Crypto.Hash((byte[])null, algorithm: "mD5"));
}
[Fact]
public void HashWithUnknownAlg_ThrowsException()
{
Assert.Throws<InvalidOperationException>(() => Crypto.Hash("sdflksd", algorithm: "hao"), "The hash algorithm 'hao' is not supported, valid values are: sha256, sha1, md5");
}
}
}

View File

@ -0,0 +1,105 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Dynamic;
using System.Linq.Expressions;
using System.Reflection;
namespace System.Web.Helpers.Test
{
/// <summary>
/// Dynamic object implementation over a dictionary that doesn't implement anything but the interface.
/// Used for testing our types that consume dynamic objects to make sure they don't make any assumptions on the implementation.
/// </summary>
public class DynamicDictionary : IDynamicMetaObjectProvider
{
private readonly Dictionary<string, object> _values = new Dictionary<string, object>();
public object this[string name]
{
get
{
object result;
_values.TryGetValue(name, out result);
return result;
}
set { _values[name] = value; }
}
public DynamicMetaObject GetMetaObject(Expression parameter)
{
return new DynamicDictionaryMetaObject(parameter, this);
}
private class DynamicDictionaryMetaObject : DynamicMetaObject
{
private static readonly PropertyInfo ItemPropery = typeof(DynamicDictionary).GetProperty("Item");
public DynamicDictionaryMetaObject(Expression expression, object value)
: base(expression, BindingRestrictions.Empty, value)
{
}
private IDictionary<string, object> WrappedDictionary
{
get { return ((DynamicDictionary)Value)._values; }
}
private Expression GetDynamicExpression()
{
return Expression.Convert(Expression, typeof(DynamicDictionary));
}
private Expression GetIndexExpression(string key)
{
return Expression.MakeIndex(
GetDynamicExpression(),
ItemPropery,
new[]
{
Expression.Constant(key)
}
);
}
private Expression GetSetValueExpression(string key, object value)
{
return Expression.Assign(
GetIndexExpression(key),
Expression.Convert(Expression.Constant(value),
typeof(object))
);
}
public override DynamicMetaObject BindGetMember(GetMemberBinder binder)
{
var binderDefault = binder.FallbackGetMember(this);
var expression = Expression.Convert(GetIndexExpression(binder.Name),
typeof(object));
var dynamicSuggestion = new DynamicMetaObject(expression, BindingRestrictions.GetTypeRestriction(Expression, LimitType)
.Merge(binderDefault.Restrictions));
return binder.FallbackGetMember(this, dynamicSuggestion);
}
public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value)
{
var binderDefault = binder.FallbackSetMember(this, value);
Expression expression = GetSetValueExpression(binder.Name, value.Value);
var dynamicSuggestion = new DynamicMetaObject(expression, BindingRestrictions.GetTypeRestriction(Expression, LimitType)
.Merge(binderDefault.Restrictions));
return binder.FallbackSetMember(this, value, dynamicSuggestion);
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return WrappedDictionary.Keys;
}
}
}
}

View File

@ -0,0 +1,39 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Dynamic;
using Microsoft.Internal.Web.Utils;
using Xunit;
namespace System.Web.Helpers.Test
{
public class DynamicHelperTest
{
[Fact]
public void TryGetMemberValueReturnsValueIfBinderIsNotCSharp()
{
// Arrange
var mockMemberBinder = new MockMemberBinder("Foo");
var dynamic = new DynamicWrapper(new { Foo = "Bar" });
// Act
object value;
bool result = DynamicHelper.TryGetMemberValue(dynamic, mockMemberBinder, out value);
// Assert
Assert.Equal(value, "Bar");
}
private class MockMemberBinder : GetMemberBinder
{
public MockMemberBinder(string name)
: base(name, false)
{
}
public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
{
throw new NotImplementedException();
}
}
}
}

View File

@ -0,0 +1,82 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace System.Web.Helpers.Test
{
/// <summary>
/// Dynamic object implementation over a regualar CLR object. Getmember accesses members through reflection.
/// </summary>
public class DynamicWrapper : IDynamicMetaObjectProvider
{
private object _object;
public DynamicWrapper(object obj)
{
_object = obj;
}
public DynamicMetaObject GetMetaObject(Expression parameter)
{
return new DynamicWrapperMetaObject(parameter, this);
}
private class DynamicWrapperMetaObject : DynamicMetaObject
{
public DynamicWrapperMetaObject(Expression expression, object value)
: base(expression, BindingRestrictions.Empty, value)
{
}
private object WrappedObject
{
get { return ((DynamicWrapper)Value)._object; }
}
private Expression GetDynamicExpression()
{
return Expression.Convert(Expression, typeof(DynamicWrapper));
}
private Expression GetWrappedObjectExpression()
{
FieldInfo fieldInfo = typeof(DynamicWrapper).GetField("_object", BindingFlags.NonPublic | BindingFlags.Instance);
Debug.Assert(fieldInfo != null);
return Expression.Convert(
Expression.Field(GetDynamicExpression(), fieldInfo),
WrappedObject.GetType());
}
private Expression GetMemberAccessExpression(string memberName)
{
return Expression.Property(
GetWrappedObjectExpression(),
memberName);
}
public override DynamicMetaObject BindGetMember(GetMemberBinder binder)
{
var binderDefault = binder.FallbackGetMember(this);
var expression = Expression.Convert(GetMemberAccessExpression(binder.Name), typeof(object));
var dynamicSuggestion = new DynamicMetaObject(expression, BindingRestrictions.GetTypeRestriction(Expression, LimitType)
.Merge(binderDefault.Restrictions));
return binder.FallbackGetMember(this, dynamicSuggestion);
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return (from p in WrappedObject.GetType().GetProperties()
orderby p.Name
select p.Name).ToArray();
}
}
}
}

View File

@ -0,0 +1,74 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.IO;
using System.Web.WebPages;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Helpers.Test
{
/// <summary>
///This is a test class for Util is intended
///to contain all HelperResult Unit Tests
///</summary>
public class HelperResultTest
{
[Fact]
public void HelperResultConstructorNullTest()
{
Assert.ThrowsArgumentNull(() => { var helper = new HelperResult(null); }, "action");
}
[Fact]
public void ToStringTest()
{
var text = "Hello";
Action<TextWriter> action = tw => tw.Write(text);
var helper = new HelperResult(action);
Assert.Equal(text, helper.ToString());
}
[Fact]
public void WriteToTest()
{
var text = "Hello";
Action<TextWriter> action = tw => tw.Write(text);
var helper = new HelperResult(action);
var writer = new StringWriter();
helper.WriteTo(writer);
Assert.Equal(text, writer.ToString());
}
[Fact]
public void ToHtmlStringDoesNotEncode()
{
// Arrange
string text = "<strong>This is a test & it uses html.</strong>";
Action<TextWriter> action = writer => writer.Write(text);
HelperResult helperResult = new HelperResult(action);
// Act
string result = helperResult.ToHtmlString();
// Assert
Assert.Equal(result, text);
}
[Fact]
public void ToHtmlStringReturnsSameResultAsWriteTo()
{
// Arrange
string text = "<strong>This is a test & it uses html.</strong>";
Action<TextWriter> action = writer => writer.Write(text);
HelperResult helperResult = new HelperResult(action);
StringWriter stringWriter = new StringWriter();
// Act
string htmlString = helperResult.ToHtmlString();
helperResult.WriteTo(stringWriter);
// Assert
Assert.Equal(htmlString, stringWriter.ToString());
}
}
}

View File

@ -0,0 +1,371 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Dynamic;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Helpers.Test
{
public class JsonTest
{
[Fact]
public void EncodeWithDynamicObject()
{
// Arrange
dynamic obj = new DummyDynamicObject();
obj.Name = "Hello";
obj.Age = 1;
obj.Grades = new[] { "A", "B", "C" };
// Act
string json = Json.Encode(obj);
// Assert
Assert.Equal("{\"Name\":\"Hello\",\"Age\":1,\"Grades\":[\"A\",\"B\",\"C\"]}", json);
}
[Fact]
public void EncodeArray()
{
// Arrange
object input = new string[] { "one", "2", "three", "4" };
// Act
string json = Json.Encode(input);
// Assert
Assert.Equal("[\"one\",\"2\",\"three\",\"4\"]", json);
}
[Fact]
public void EncodeDynamicJsonArrayEncodesAsArray()
{
// Arrange
dynamic array = Json.Decode("[1,2,3]");
// Act
string json = Json.Encode(array);
// Assert
Assert.Equal("[1,2,3]", json);
}
[Fact]
public void DecodeDynamicObject()
{
// Act
var obj = Json.Decode("{\"Name\":\"Hello\",\"Age\":1,\"Grades\":[\"A\",\"B\",\"C\"]}");
// Assert
Assert.Equal("Hello", obj.Name);
Assert.Equal(1, obj.Age);
Assert.Equal(3, obj.Grades.Length);
Assert.Equal("A", obj.Grades[0]);
Assert.Equal("B", obj.Grades[1]);
Assert.Equal("C", obj.Grades[2]);
}
[Fact]
public void DecodeDynamicObjectImplicitConversionToDictionary()
{
// Act
IDictionary<string, object> values = Json.Decode("{\"Name\":\"Hello\",\"Age\":1}");
// Assert
Assert.Equal("Hello", values["Name"]);
Assert.Equal(1, values["Age"]);
}
[Fact]
public void DecodeArrayImplicitConversionToArrayAndObjectArray()
{
// Act
Array array = Json.Decode("[1,2,3]");
object[] objArray = Json.Decode("[1,2,3]");
IEnumerable<dynamic> dynamicEnumerable = Json.Decode("[{a:1}]");
// Assert
Assert.NotNull(array);
Assert.NotNull(objArray);
Assert.NotNull(dynamicEnumerable);
}
[Fact]
public void DecodeArrayImplicitConversionToArrayArrayValuesAreDynamic()
{
// Act
dynamic[] objArray = Json.Decode("[{\"A\":1}]");
// Assert
Assert.NotNull(objArray);
Assert.Equal(1, objArray[0].A);
}
[Fact]
public void DecodeDynamicObjectAccessPropertiesByIndexer()
{
// Arrange
var obj = Json.Decode("{\"Name\":\"Hello\",\"Age\":1,\"Grades\":[\"A\",\"B\",\"C\"]}");
// Assert
Assert.Equal("Hello", obj["Name"]);
Assert.Equal(1, obj["Age"]);
Assert.Equal(3, obj["Grades"].Length);
Assert.Equal("A", obj["Grades"][0]);
Assert.Equal("B", obj["Grades"][1]);
Assert.Equal("C", obj["Grades"][2]);
}
[Fact]
public void DecodeDynamicObjectAccessPropertiesByNullIndexerReturnsNull()
{
// Arrange
var obj = Json.Decode("{\"Name\":\"Hello\",\"Age\":1,\"Grades\":[\"A\",\"B\",\"C\"]}");
// Assert
Assert.Null(obj[null]);
}
[Fact]
public void DecodeDateTime()
{
// Act
DateTime dateTime = Json.Decode("\"\\/Date(940402800000)\\/\"");
// Assert
Assert.Equal(1999, dateTime.Year);
Assert.Equal(10, dateTime.Month);
Assert.Equal(20, dateTime.Day);
}
[Fact]
public void DecodeNumber()
{
// Act
int number = Json.Decode("1");
// Assert
Assert.Equal(1, number);
}
[Fact]
public void DecodeString()
{
// Act
string @string = Json.Decode("\"1\"");
// Assert
Assert.Equal("1", @string);
}
[Fact]
public void DecodeArray()
{
// Act
var values = Json.Decode("[11,12,13,14,15]");
// Assert
Assert.Equal(5, values.Length);
Assert.Equal(11, values[0]);
Assert.Equal(12, values[1]);
Assert.Equal(13, values[2]);
Assert.Equal(14, values[3]);
Assert.Equal(15, values[4]);
}
[Fact]
public void DecodeObjectWithArrayProperty()
{
// Act
var obj = Json.Decode("{\"A\":1,\"B\":[1,3,4]}");
object[] bValues = obj.B;
// Assert
Assert.Equal(1, obj.A);
Assert.Equal(1, bValues[0]);
Assert.Equal(3, bValues[1]);
Assert.Equal(4, bValues[2]);
}
[Fact]
public void DecodeArrayWithObjectValues()
{
// Act
var obj = Json.Decode("[{\"A\":1},{\"B\":3, \"C\": \"hello\"}]");
// Assert
Assert.Equal(2, obj.Length);
Assert.Equal(1, obj[0].A);
Assert.Equal(3, obj[1].B);
Assert.Equal("hello", obj[1].C);
}
[Fact]
public void DecodeArraySetValues()
{
// Arrange
var values = Json.Decode("[1,2,3,4,5]");
for (int i = 0; i < values.Length; i++)
{
values[i]++;
}
// Assert
Assert.Equal(5, values.Length);
Assert.Equal(2, values[0]);
Assert.Equal(3, values[1]);
Assert.Equal(4, values[2]);
Assert.Equal(5, values[3]);
Assert.Equal(6, values[4]);
}
[Fact]
public void DecodeArrayPassToMethodThatTakesArray()
{
// Arrange
var values = Json.Decode("[3,2,1]");
// Act
int index = Array.IndexOf(values, 2);
// Assert
Assert.Equal(1, index);
}
[Fact]
public void DecodeArrayGetEnumerator()
{
// Arrange
var values = Json.Decode("[1,2,3]");
// Assert
int val = 1;
foreach (var value in values)
{
Assert.Equal(val, val);
val++;
}
}
[Fact]
public void DecodeObjectPropertyAccessIsSameObjectInstance()
{
// Arrange
var obj = Json.Decode("{\"Name\":{\"Version:\":4.0, \"Key\":\"Key\"}}");
// Assert
Assert.Same(obj.Name, obj.Name);
}
[Fact]
public void DecodeArrayAccessingMembersThatDontExistReturnsNull()
{
// Act
var obj = Json.Decode("[\"a\", \"b\"]");
// Assert
Assert.Null(obj.PropertyThatDoesNotExist);
}
[Fact]
public void DecodeObjectSetProperties()
{
// Act
var obj = Json.Decode("{\"A\":{\"B\":100}}");
obj.A.B = 20;
// Assert
Assert.Equal(20, obj.A.B);
}
[Fact]
public void DecodeObjectSettingObjectProperties()
{
// Act
var obj = Json.Decode("{\"A\":1}");
obj.A = new { B = 1, D = 2 };
// Assert
Assert.Equal(1, obj.A.B);
Assert.Equal(2, obj.A.D);
}
[Fact]
public void DecodeObjectWithArrayPropertyPassPropertyToMethodThatTakesArray()
{
// Arrange
var obj = Json.Decode("{\"A\":[3,2,1]}");
// Act
Array.Sort(obj.A);
// Assert
Assert.Equal(1, obj.A[0]);
Assert.Equal(2, obj.A[1]);
Assert.Equal(3, obj.A[2]);
}
[Fact]
public void DecodeObjectAccessingMembersThatDontExistReturnsNull()
{
// Act
var obj = Json.Decode("{\"A\":1}");
// Assert
Assert.Null(obj.PropertyThatDoesntExist);
}
[Fact]
public void DecodeObjectWithSpecificType()
{
// Act
var person = Json.Decode<Person>("{\"Name\":\"David\", \"Age\":2}");
// Assert
Assert.Equal("David", person.Name);
Assert.Equal(2, person.Age);
}
[Fact]
public void DecodeObjectWithImplicitConversionToNonDynamicTypeThrows()
{
// Act & Assert
Assert.Throws<InvalidOperationException>(() => { Person person = Json.Decode("{\"Name\":\"David\", \"Age\":2, \"Address\":{\"Street\":\"Bellevue\"}}"); }, "Unable to convert to \"System.Web.Helpers.Test.JsonTest+Person\". Use Json.Decode<T> instead.");
}
private class DummyDynamicObject : DynamicObject
{
private IDictionary<string, object> _values = new Dictionary<string, object>();
public override IEnumerable<string> GetDynamicMemberNames()
{
return _values.Keys;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_values[binder.Name] = value;
return true;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return _values.TryGetValue(binder.Name, out result);
}
}
private class Person
{
public string Name { get; set; }
public int Age { get; set; }
public int GPA { get; set; }
public Address Address { get; set; }
}
private class Address
{
public string Street { get; set; }
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,43 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Linq;
using Moq;
using Xunit;
namespace System.Web.Helpers.Test
{
public class PreComputedGridDataSourceTest
{
[Fact]
public void PreSortedDataSourceReturnsRowCountItWasSpecified()
{
// Arrange
int rows = 20;
var dataSource = new PreComputedGridDataSource(new WebGrid(GetContext()), values: Enumerable.Range(0, 10).Cast<dynamic>(), totalRows: rows);
// Act and Assert
Assert.Equal(rows, dataSource.TotalRowCount);
}
[Fact]
public void PreSortedDataSourceReturnsAllRows()
{
// Arrange
var grid = new WebGrid(GetContext());
var dataSource = new PreComputedGridDataSource(grid: grid, values: Enumerable.Range(0, 10).Cast<dynamic>(), totalRows: 10);
// Act
var rows = dataSource.GetRows(new SortInfo { SortColumn = String.Empty }, 0);
// Assert
Assert.Equal(rows.Count, 10);
Assert.Equal(rows.First().Value, 0);
Assert.Equal(rows.Last().Value, 9);
}
private HttpContextBase GetContext()
{
return new Mock<HttpContextBase>().Object;
}
}
}

View File

@ -0,0 +1,36 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("System.Web.Helpers.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MSIT")]
[assembly: AssemblyProduct("System.Web.Helpers.Test")]
[assembly: AssemblyCopyright("Copyright © MSIT 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,165 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.WebPages.TestUtils;
using Moq;
using Xunit;
namespace System.Web.Helpers.Test
{
public class InfoTest
{
[Fact]
public void ConfigurationReturnsExpectedInfo()
{
var configInfo = ServerInfo.Configuration();
// verification
// checks only subset of values
Assert.NotNull(configInfo);
VerifyKey(configInfo, "Machine Name");
VerifyKey(configInfo, "OS Version");
VerifyKey(configInfo, "ASP.NET Version");
VerifyKey(configInfo, "ASP.NET Web Pages Version");
}
[Fact]
public void EnvironmentVariablesReturnsExpectedInfo()
{
var envVariables = ServerInfo.EnvironmentVariables();
// verification
// checks only subset of values
Assert.NotNull(envVariables);
VerifyKey(envVariables, "Path");
VerifyKey(envVariables, "SystemDrive");
}
[Fact]
public void ServerVariablesReturnsExpectedInfoWithNoContext()
{
var serverVariables = ServerInfo.ServerVariables();
// verification
// since there is no HttpContext this will be empty
Assert.NotNull(serverVariables);
}
[Fact]
public void ServerVariablesReturnsExpectedInfoWthContext()
{
var serverVariables = new NameValueCollection();
serverVariables.Add("foo", "bar");
var request = new Mock<HttpRequestBase>();
request.Setup(c => c.ServerVariables).Returns(serverVariables);
var context = new Mock<HttpContextBase>();
context.Setup(c => c.Request).Returns(request.Object);
// verification
Assert.NotNull(serverVariables);
IDictionary<string, string> returnedValues = ServerInfo.ServerVariables(context.Object);
Assert.Equal(serverVariables.Count, returnedValues.Count);
foreach (var item in returnedValues)
{
Assert.Equal(serverVariables[item.Key], item.Value);
}
}
[Fact]
public void HttpRuntimeInfoReturnsExpectedInfo()
{
var httpRuntimeInfo = ServerInfo.HttpRuntimeInfo();
// verification
// checks only subset of values
Assert.NotNull(httpRuntimeInfo);
VerifyKey(httpRuntimeInfo, "CLR Install Directory");
VerifyKey(httpRuntimeInfo, "Asp Install Directory");
VerifyKey(httpRuntimeInfo, "On UNC Share");
}
[Fact]
public void ServerInfoDoesNotProduceLegacyCasForHomogenousAppDomain()
{
// Act and Assert
Action action = () =>
{
IDictionary<string, string> configValue = ServerInfo.LegacyCAS(AppDomain.CurrentDomain);
Assert.NotNull(configValue);
Assert.Equal(0, configValue.Count);
};
AppDomainUtils.RunInSeparateAppDomain(GetAppDomainSetup(legacyCasEnabled: false), action);
}
[Fact]
public void ServerInfoProducesLegacyCasForNonHomogenousAppDomain()
{
// Arrange
Action action = () =>
{
// Act and Assert
IDictionary<string, string> configValue = ServerInfo.LegacyCAS(AppDomain.CurrentDomain);
// Assert
Assert.True(configValue.ContainsKey("Legacy Code Access Security"));
Assert.Equal(configValue["Legacy Code Access Security"], "Legacy Code Access Security has been detected on your system. Microsoft WebPage features require the ASP.NET 4 Code Access Security model. For information about how to resolve this, contact your server administrator.");
};
AppDomainUtils.RunInSeparateAppDomain(GetAppDomainSetup(legacyCasEnabled: true), action);
}
//[Fact]
//public void SqlServerInfoReturnsExpectedInfo() {
// var sqlInfo = ServerInfo.SqlServerInfo();
// // verification
// // just verifies that we don't get any unexpected exceptions
// Assert.NotNull(sqlInfo);
//}
[Fact]
public void RenderResultContainsExpectedTags()
{
var htmlString = ServerInfo.GetHtml().ToString();
// just verify that the final HTML produced contains some expected info
Assert.True(htmlString.Contains("<table class=\"server-info\" dir=\"ltr\">"));
Assert.True(htmlString.Contains("</style>"));
Assert.True(htmlString.Contains("Server Configuration"));
}
[Fact]
public void RenderGeneratesValidXhtml()
{
// Result does not validate against XHTML 1.1 and HTML5 because ServerInfo generates
// <style> inside <body>. This is by design however since we only use ServerInfo
// as debugging aid, not something to be permanently added to a web page.
XhtmlAssert.Validate1_0(
ServerInfo.GetHtml(),
addRoot: true
);
}
private void VerifyKey(IDictionary<string, string> info, string key)
{
Assert.True(info.ContainsKey(key));
Assert.False(String.IsNullOrEmpty(info[key]));
}
private AppDomainSetup GetAppDomainSetup(bool legacyCasEnabled)
{
var setup = new AppDomainSetup();
if (legacyCasEnabled)
{
setup.SetCompatibilitySwitches(new[] { "NetFx40_LegacySecurityPolicy" });
}
return setup;
}
}
}

View File

@ -0,0 +1,106 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\tools\WebStack.settings.targets" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{D3313BDF-8071-4AC8-9D98-ABF7F9E88A57}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>System.Web.Helpers.Test</RootNamespace>
<AssemblyName>System.Web.Helpers.Test</AssemblyName>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>$(WebStackRootPath)\bin\Debug\Test\</OutputPath>
<DefineConstants>TRACE;DEBUG</DefineConstants>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>$(WebStackRootPath)\bin\Release\Test\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'CodeCoverage' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>$(WebStackRootPath)\bin\CodeCoverage\Test\</OutputPath>
<DefineConstants>TRACE;DEBUG</DefineConstants>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="Moq, Version=4.0.10827.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL">
<HintPath>..\..\packages\Moq.4.0.10827\lib\NET40\Moq.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Web" />
<Reference Include="System.Web.DataVisualization" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.XML" />
<Reference Include="xunit">
<HintPath>..\..\packages\xunit.1.9.0.1566\lib\xunit.dll</HintPath>
</Reference>
<Reference Include="xunit.extensions">
<HintPath>..\..\packages\xunit.extensions.1.9.0.1566\lib\xunit.extensions.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="ChartTest.cs" />
<Compile Include="ConversionUtilTest.cs" />
<Compile Include="CryptoTest.cs" />
<Compile Include="DynamicDictionary.cs" />
<Compile Include="DynamicHelperTest.cs" />
<Compile Include="DynamicWrapper.cs" />
<Compile Include="JsonTest.cs" />
<Compile Include="ObjectInfoTest.cs" />
<Compile Include="PreComputedGridDataSourceTest.cs" />
<Compile Include="WebCacheTest.cs" />
<Compile Include="HelperResultTest.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ServerInfoTest.cs" />
<Compile Include="WebGridDataSourceTest.cs" />
<Compile Include="WebGridTest.cs" />
<Compile Include="WebImageTest.cs" />
<Compile Include="WebMailTest.cs" />
<Compile Include="XhtmlAssert.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\System.Web.WebPages\System.Web.WebPages.csproj">
<Project>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</Project>
<Name>System.Web.WebPages</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\System.Web.Helpers\System.Web.Helpers.csproj">
<Project>{9B7E3740-6161-4548-833C-4BBCA43B970E}</Project>
<Name>System.Web.Helpers</Name>
</ProjectReference>
<ProjectReference Include="..\Microsoft.TestCommon\Microsoft.TestCommon.csproj">
<Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>
<Name>Microsoft.TestCommon</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="TestFiles\HiRes.jpg" />
<EmbeddedResource Include="TestFiles\LambdaFinal.jpg" />
<EmbeddedResource Include="TestFiles\logo.bmp" />
<EmbeddedResource Include="TestFiles\NETLogo.png" />
<EmbeddedResource Include="TestFiles\xhtml11-flat.dtd" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

View File

@ -0,0 +1 @@
9f32884f792d9f65c5ac913688a58812ee347c82

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

View File

@ -0,0 +1 @@
b9f5881eac021f2076ba4c826247884cf6842224

View File

@ -0,0 +1,118 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Helpers.Test
{
public class WebCacheTest
{
[Fact]
public void GetReturnsExpectedValueTest()
{
string key = DateTime.UtcNow.Ticks.ToString() + "_GetTest";
List<string> expected = new List<string>();
WebCache.Set(key, expected);
var actual = WebCache.Get(key);
Assert.Equal(expected, actual);
Assert.Equal(0, actual.Count);
}
[Fact]
public void RemoveRemovesRightValueTest()
{
string key = DateTime.UtcNow.Ticks.ToString() + "_RemoveTest";
List<string> expected = new List<string>();
WebCache.Set(key, expected);
var actual = WebCache.Remove(key);
Assert.Equal(expected, actual);
Assert.Equal(0, actual.Count);
}
[Fact]
public void RemoveRemovesValueFromCacheTest()
{
string key = DateTime.UtcNow.Ticks.ToString() + "_RemoveTest2";
List<string> expected = new List<string>();
WebCache.Set(key, expected);
var removed = WebCache.Remove(key);
Assert.Null(WebCache.Get(key));
}
[Fact]
public void SetWithAbsoluteExpirationDoesNotThrow()
{
string key = DateTime.UtcNow.Ticks.ToString() + "SetWithAbsoluteExpirationDoesNotThrow_SetTest";
object expected = new object();
int minutesToCache = 10;
bool slidingExpiration = false;
WebCache.Set(key, expected, minutesToCache, slidingExpiration);
object actual = WebCache.Get(key);
Assert.True(expected == actual);
}
[Fact]
public void CanSetWithSlidingExpiration()
{
string key = DateTime.UtcNow.Ticks.ToString() + "_CanSetWithSlidingExpiration_SetTest";
object expected = new object();
WebCache.Set(key, expected, slidingExpiration: true);
object actual = WebCache.Get(key);
Assert.True(expected == actual);
}
[Fact]
public void SetWithSlidingExpirationForNegativeTime()
{
string key = DateTime.UtcNow.Ticks.ToString() + "_SetWithSlidingExpirationForNegativeTime_SetTest";
object expected = new object();
Assert.ThrowsArgumentGreaterThan(() => WebCache.Set(key, expected, -1), "minutesToCache", "0");
}
[Fact]
public void SetWithSlidingExpirationForZeroTime()
{
string key = DateTime.UtcNow.Ticks.ToString() + "_SetWithSlidingExpirationForZeroTime_SetTest";
object expected = new object();
Assert.ThrowsArgumentGreaterThan(() => WebCache.Set(key, expected, 0), "minutesToCache", "0");
}
[Fact]
public void SetWithSlidingExpirationForYear()
{
string key = DateTime.UtcNow.Ticks.ToString() + "_SetWithSlidingExpirationForYear_SetTest";
object expected = new object();
WebCache.Set(key, expected, 365 * 24 * 60, true);
object actual = WebCache.Get(key);
Assert.True(expected == actual);
}
[Fact]
public void SetWithSlidingExpirationForMoreThanYear()
{
string key = DateTime.UtcNow.Ticks.ToString() + "_SetWithSlidingExpirationForMoreThanYear_SetTest";
object expected = new object();
Assert.ThrowsArgumentLessThanOrEqualTo(() => WebCache.Set(key, expected, 365 * 24 * 60 + 1, true), "minutesToCache", (365 * 24 * 60).ToString());
}
[Fact]
public void SetWithAbsoluteExpirationForMoreThanYear()
{
string key = DateTime.UtcNow.Ticks.ToString() + "_SetWithAbsoluteExpirationForMoreThanYear_SetTest";
object expected = new object();
WebCache.Set(key, expected, 365 * 24 * 60, true);
object actual = WebCache.Get(key);
Assert.True(expected == actual);
}
}
}

View File

@ -0,0 +1,306 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using Moq;
using Xunit;
namespace System.Web.Helpers.Test
{
public class WebGridDataSourceTest
{
[Fact]
public void WebGridDataSourceReturnsNumberOfItemsAsTotalRowCount()
{
// Arrange
var rows = GetValues();
var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: GetValues(), elementType: typeof(Person), canPage: false, canSort: false);
// Act and Assert
Assert.Equal(rows.Count(), dataSource.TotalRowCount);
}
[Fact]
public void WebGridDataSourceReturnsUnsortedListIfSortColumnIsNull()
{
// Arrange
var values = GetValues();
var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: GetValues(), elementType: typeof(Person), canPage: false, canSort: true);
// Act
var rows = dataSource.GetRows(new SortInfo { SortColumn = null }, 0);
// Assert
Assert.True(Enumerable.SequenceEqual<object>(values.ToList(), rows.Select(r => r.Value).ToList(), new PersonComparer()));
}
[Fact]
public void WebGridDataSourceReturnsUnsortedListIfSortColumnIsEmpty()
{
// Arrange
var values = GetValues();
var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: GetValues(), elementType: typeof(Person), canPage: false, canSort: true);
// Act
var rows = dataSource.GetRows(new SortInfo { SortColumn = String.Empty }, 0);
// Assert
Assert.True(Enumerable.SequenceEqual<object>(values.ToList(), rows.Select(r => r.Value).ToList(), new PersonComparer()));
}
[Fact]
public void WebGridDataSourceReturnsUnsortedListIfSortCannotBeInferred()
{
// Arrange
var values = GetValues();
var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: GetValues(), elementType: typeof(Person), canPage: false, canSort: true);
// Act
var rows = dataSource.GetRows(new SortInfo { SortColumn = "Does-not-exist" }, 0);
// Assert
Assert.True(Enumerable.SequenceEqual<object>(values.ToList(), rows.Select(r => r.Value).ToList(), new PersonComparer()));
}
[Fact]
public void WebGridDataSourceReturnsUnsortedListIfDefaultSortCannotBeInferred()
{
// Arrange
var values = GetValues();
var defaultSort = new SortInfo { SortColumn = "cannot-be-inferred" };
var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: GetValues(), elementType: typeof(Person), canSort: true, canPage: false) { DefaultSort = defaultSort };
// Act
var rows = dataSource.GetRows(new SortInfo { SortColumn = "Does-not-exist" }, 0);
// Assert
Assert.True(Enumerable.SequenceEqual<object>(values.ToList(), rows.Select(r => r.Value).ToList(), new PersonComparer()));
}
[Fact]
public void WebGridDataSourceUsesDefaultSortWhenCurrentSortCannotBeInferred()
{
// Arrange
var values = GetValues();
var defaultSort = new SortInfo { SortColumn = "FirstName" };
var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: GetValues(), elementType: typeof(Person), canSort: true, canPage: false) { DefaultSort = defaultSort };
// Act
var rows = dataSource.GetRows(new SortInfo { SortColumn = "Does-not-exist" }, 0);
// Assert
Assert.True(Enumerable.SequenceEqual<object>(values.OrderBy(p => p.FirstName).ToList(), rows.Select(r => r.Value).ToList(), new PersonComparer()));
}
[Fact]
public void WebGridDataSourceSortsUsingSpecifiedSort()
{
// Arrange
var defaultSort = new SortInfo { SortColumn = "FirstName", SortDirection = SortDirection.Ascending };
IEnumerable<dynamic> values = new[] { new Person { LastName = "Z" }, new Person { LastName = "X" }, new Person { LastName = "Y" } };
var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: values, elementType: typeof(Person), canSort: true, canPage: false) { DefaultSort = defaultSort };
// Act
var rows = dataSource.GetRows(new SortInfo { SortColumn = "LastName" }, 0);
// Assert
Assert.Equal(rows.ElementAt(0).Value.LastName, "X");
Assert.Equal(rows.ElementAt(1).Value.LastName, "Y");
Assert.Equal(rows.ElementAt(2).Value.LastName, "Z");
}
[Fact]
public void WebGridDataSourceSortsDynamicType()
{
// Arrange
IEnumerable<dynamic> values = new[] { new TestDynamicType("col", "val1"), new TestDynamicType("col", "val2"), new TestDynamicType("col", "val3") };
var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: values, elementType: typeof(TestDynamicType), canSort: true, canPage: false);
// Act
var rows = dataSource.GetRows(new SortInfo { SortColumn = "col", SortDirection = SortDirection.Descending }, 0);
// Assert
Assert.Equal(rows.ElementAt(0).Value.col, "val3");
Assert.Equal(rows.ElementAt(1).Value.col, "val2");
Assert.Equal(rows.ElementAt(2).Value.col, "val1");
}
[Fact]
public void WebGridDataSourceWithNestedPropertySortsCorrectly()
{
// Arrange
var element1 = new { Foo = new { Bar = "val2" } };
var element2 = new { Foo = new { Bar = "val1" } };
var element3 = new { Foo = new { Bar = "val3" } };
IEnumerable<dynamic> values = new[] { element1, element2, element3 };
var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: values, elementType: element1.GetType(), canSort: true, canPage: false);
// Act
var rows = dataSource.GetRows(new SortInfo { SortColumn = "Foo.Bar", SortDirection = SortDirection.Descending }, 0);
// Assert
Assert.Equal(rows.ElementAt(0).Value.Foo.Bar, "val3");
Assert.Equal(rows.ElementAt(1).Value.Foo.Bar, "val2");
Assert.Equal(rows.ElementAt(2).Value.Foo.Bar, "val1");
}
[Fact]
public void WebGridDataSourceSortsDictionaryBasedDynamicType()
{
// Arrange
var value1 = new DynamicDictionary();
value1["col"] = "val1";
var value2 = new DynamicDictionary();
value2["col"] = "val2";
var value3 = new DynamicDictionary();
value3["col"] = "val3";
IEnumerable<dynamic> values = new[] { value1, value2, value3 };
var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: values, elementType: typeof(TestDynamicType), canSort: true, canPage: false);
// Act
var rows = dataSource.GetRows(new SortInfo { SortColumn = "col", SortDirection = SortDirection.Descending }, 0);
// Assert
Assert.Equal(rows.ElementAt(0).Value.col, "val3");
Assert.Equal(rows.ElementAt(1).Value.col, "val2");
Assert.Equal(rows.ElementAt(2).Value.col, "val1");
}
[Fact]
public void WebGridDataSourceReturnsOriginalDataSourceIfValuesCannotBeSorted()
{
// Arrange
IEnumerable<dynamic> values = new object[] { new TestDynamicType("col", "val1"), new TestDynamicType("col", "val2"), new TestDynamicType("col", DBNull.Value) };
var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: values, elementType: typeof(TestDynamicType), canSort: true, canPage: false);
// Act
var rows = dataSource.GetRows(new SortInfo { SortColumn = "col", SortDirection = SortDirection.Descending }, 0);
// Assert
Assert.Equal(rows.ElementAt(0).Value.col, "val1");
Assert.Equal(rows.ElementAt(1).Value.col, "val2");
Assert.Equal(rows.ElementAt(2).Value.col, DBNull.Value);
}
[Fact]
public void WebGridDataSourceReturnsPagedResultsIfRowsPerPageIsSpecified()
{
// Arrange
IEnumerable<dynamic> values = GetValues();
var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: values, elementType: typeof(Person), canSort: false, canPage: true) { RowsPerPage = 2 };
// Act
var rows = dataSource.GetRows(new SortInfo(), 0);
// Assert
Assert.Equal(rows.Count, 2);
Assert.Equal(rows.ElementAt(0).Value.LastName, "B2");
Assert.Equal(rows.ElementAt(1).Value.LastName, "A2");
}
[Fact]
public void WebGridDataSourceReturnsPagedSortedResultsIfRowsPerPageAndSortAreSpecified()
{
// Arrange
IEnumerable<dynamic> values = GetValues();
var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: values, elementType: typeof(Person), canSort: true, canPage: true) { RowsPerPage = 2 };
// Act
var rows = dataSource.GetRows(new SortInfo { SortColumn = "LastName", SortDirection = SortDirection.Descending }, 0);
// Assert
Assert.Equal(rows.Count, 2);
Assert.Equal(rows.ElementAt(0).Value.LastName, "E2");
Assert.Equal(rows.ElementAt(1).Value.LastName, "D2");
}
[Fact]
public void WebGridDataSourceReturnsFewerThanRowsPerPageIfNumberOfItemsIsInsufficient()
{
// Arrange
IEnumerable<dynamic> values = GetValues();
var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: values, elementType: typeof(Person), canSort: true, canPage: true) { RowsPerPage = 3 };
// Act
var rows = dataSource.GetRows(new SortInfo(), 1);
// Assert
Assert.Equal(rows.Count, 2);
Assert.Equal(rows.ElementAt(0).Value.LastName, "C2");
Assert.Equal(rows.ElementAt(1).Value.LastName, "E2");
}
[Fact]
public void WebGridDataSourceDoesNotThrowIfValuesAreNull()
{
// Arrange
IEnumerable<dynamic> values = new object[] { String.Empty, null, DBNull.Value, null };
var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: values, elementType: typeof(object), canSort: true, canPage: true) { RowsPerPage = 2 };
// Act
var rows = dataSource.GetRows(new SortInfo(), 0);
// Assert
Assert.Equal(rows.Count, 2);
Assert.Equal(rows.ElementAt(0).Value, String.Empty);
Assert.Null(rows.ElementAt(1).Value);
}
private IEnumerable<Person> GetValues()
{
return new[]
{
new Person { FirstName = "B1", LastName = "B2" },
new Person { FirstName = "A1", LastName = "A2" },
new Person { FirstName = "D1", LastName = "D2" },
new Person { FirstName = "C1", LastName = "C2" },
new Person { FirstName = "E1", LastName = "E2" },
};
}
private class PersonComparer : IEqualityComparer<object>
{
public new bool Equals(object x, object y)
{
dynamic xDynamic = x;
dynamic yDynamic = y;
return (String.Equals(xDynamic.FirstName, yDynamic.FirstName, StringComparison.OrdinalIgnoreCase)
&& String.Equals(xDynamic.LastName, yDynamic.LastName, StringComparison.OrdinalIgnoreCase));
}
public int GetHashCode(dynamic obj)
{
return 4; // Random dice roll
}
}
private class TestDynamicType : DynamicObject
{
public Dictionary<string, object> _values = new Dictionary<string, object>();
public TestDynamicType(string a, object b)
{
_values[a] = b;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return _values.TryGetValue(binder.Name, out result);
}
}
private class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
private HttpContextBase GetContext()
{
return new Mock<HttpContextBase>().Object;
}
}
}

Some files were not shown because too many files have changed in this diff Show More