This commit is contained in:
Eugene Sadovoi 2017-10-06 19:49:10 -04:00
Родитель 770f898d52
Коммит f501b048dc
38 изменённых файлов: 1437 добавлений и 208 удалений

Просмотреть файл

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Migrated rules for Unity.Interception.ruleset" Description="This rule set was created from the CodeAnalysisRules property for the &quot;Debug (Any CPU)&quot; configuration in project &quot;C:\prj\Unity\Unity\Source\Unity\Unity.Interception\Src\Unity.Interception.csproj&quot;." ToolsVersion="11.0">
<IncludeAll Action="Warning" />
<Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed">
<Rule Id="CA1004" Action="None" />
<Rule Id="CA1014" Action="None" />
<Rule Id="CA2210" Action="None" />
</Rules>
</RuleSet>

Просмотреть файл

@ -26,21 +26,17 @@
</PropertyGroup>
<PropertyGroup>
<DebugType Condition="'$(TargetFramework)' != '' AND !$(TargetFramework.StartsWith('netcoreapp'))">Full</DebugType>
<DebugType>Full</DebugType>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)' != '' AND '$(TargetFramework)' != 'net40' ">
<Compile Remove="net40\**" />
<EmbeddedResource Remove="net40\**" />
<None Remove="net40\**" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' != '' AND '$(TargetFramework)' == 'net40' ">
<Compile Remove="Utilities\StaticReflection.cs" />
<Compile Remove="Utilities\net 4.0\**" />
<EmbeddedResource Remove="Utilities\net 4.0\**" />
<None Remove="Utilities\net 4.0\**" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Unity\Unity.csproj" />
<ProjectReference Include="..\..\Unity\src\Unity.csproj" />
</ItemGroup>
<ItemGroup>

Просмотреть файл

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="CommonServiceLocator" version="1.3" targetFramework="net45" />
</packages>

Просмотреть файл

@ -1,15 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net45</TargetFramework>
<TargetFramework>net47</TargetFramework>
<IsPackable>false</IsPackable>
<RootNamespace>Unity.Interception.Tests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Remove="MatchingRules\AssemblyMatchingRuleFixture.2008.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0" />
<PackageReference Include="MSTest.TestAdapter" Version="1.1.18" />
@ -17,8 +13,8 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Unity.Interception\Unity.Interception.csproj" />
<ProjectReference Include="..\..\src\Unity\Unity.csproj" />
<ProjectReference Include="..\..\Unity\src\Unity.csproj" />
<ProjectReference Include="..\src\Unity.Interception.csproj" />
</ItemGroup>
</Project>

Просмотреть файл

@ -1,70 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Practices.Unity.InterceptionExtension.Tests.MatchingRules
{
// Tests on assembly matching rules that only work in VS 2008/.NET 3.5
public partial class AssemblyMatchingRuleFixture
{
[TestMethod]
public void CanMatchAssemblyNameByNameAndVersion()
{
AssemblyMatchingRule matchingRule = new AssemblyMatchingRule("mscorlib, Version=2.0.0.0");
Assert.IsTrue(matchingRule.Matches(objectToStringMethod));
}
[TestMethod]
public void CanMatchAssemblyNameByNameVersionAndKey()
{
AssemblyMatchingRule matchingRule = new AssemblyMatchingRule("mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089");
Assert.IsTrue(matchingRule.Matches(objectToStringMethod));
}
[TestMethod]
public void CanMatchAssemblyNameByNameVersionAndCulture()
{
AssemblyMatchingRule matchingRule = new AssemblyMatchingRule("mscorlib, Version=2.0.0.0, Culture=neutral");
Assert.IsTrue(matchingRule.Matches(objectToStringMethod));
}
[TestMethod]
public void CanMatchAssemblyByFullyQualifiedName()
{
AssemblyMatchingRule matchingRule = new AssemblyMatchingRule("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
Assert.IsTrue(matchingRule.Matches(objectToStringMethod));
}
[TestMethod]
public void CanExplicitlyDenyMatchOnNoKey()
{
AssemblyMatchingRule matchingRule = new AssemblyMatchingRule("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=(null)");
Assert.IsFalse(matchingRule.Matches(objectToStringMethod));
}
[TestMethod]
public void CanExplicitlyDenyMatchOnSpecificKey()
{
AssemblyMatchingRule matchingRule = new AssemblyMatchingRule("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
Assert.IsFalse(matchingRule.Matches(objectToStringMethod));
}
[TestMethod]
public void CanExplicitlyDenyMatchOnSpecificCulture()
{
AssemblyMatchingRule matchingRule = new AssemblyMatchingRule("mscorlib, Version=2.0.0.0, Culture=nl-NL, PublicKeyToken=b77a5c561934e089");
Assert.IsFalse(matchingRule.Matches(objectToStringMethod));
}
[TestMethod]
public void CanMatchAssemblyNameUsingArbitraryAmountOfSpaces()
{
AssemblyMatchingRule matchingRule = new AssemblyMatchingRule("mscorlib,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
Assert.IsTrue(matchingRule.Matches(objectToStringMethod));
}
}
}

Просмотреть файл

@ -1,70 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Practices.Unity.InterceptionExtension.Tests.MatchingRules
{
// Tests on assembly matching rules that only work in VS 2010/.NET 4.0
public partial class AssemblyMatchingRuleFixture
{
[TestMethod]
public void CanMatchAssemblyNameByNameAndVersion()
{
AssemblyMatchingRule matchingRule = new AssemblyMatchingRule("mscorlib, Version=4.0.0.0");
Assert.IsTrue(matchingRule.Matches(objectToStringMethod));
}
[TestMethod]
public void CanMatchAssemblyNameByNameVersionAndKey()
{
AssemblyMatchingRule matchingRule = new AssemblyMatchingRule("mscorlib, Version=4.0.0.0, PublicKeyToken=b77a5c561934e089");
Assert.IsTrue(matchingRule.Matches(objectToStringMethod));
}
[TestMethod]
public void CanMatchAssemblyNameByNameVersionAndCulture()
{
AssemblyMatchingRule matchingRule = new AssemblyMatchingRule("mscorlib, Version=4.0.0.0, Culture=neutral");
Assert.IsTrue(matchingRule.Matches(objectToStringMethod));
}
[TestMethod]
public void CanMatchAssemblyByFullyQualifiedName()
{
AssemblyMatchingRule matchingRule = new AssemblyMatchingRule("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
Assert.IsTrue(matchingRule.Matches(objectToStringMethod));
}
[TestMethod]
public void CanExplicitlyDenyMatchOnNoKey()
{
AssemblyMatchingRule matchingRule = new AssemblyMatchingRule("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=(null)");
Assert.IsFalse(matchingRule.Matches(objectToStringMethod));
}
[TestMethod]
public void CanExplicitlyDenyMatchOnSpecificKey()
{
AssemblyMatchingRule matchingRule = new AssemblyMatchingRule("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
Assert.IsFalse(matchingRule.Matches(objectToStringMethod));
}
[TestMethod]
public void CanExplicitlyDenyMatchOnSpecificCulture()
{
AssemblyMatchingRule matchingRule = new AssemblyMatchingRule("mscorlib, Version=4.0.0.0, Culture=nl-NL, PublicKeyToken=b77a5c561934e089");
Assert.IsFalse(matchingRule.Matches(objectToStringMethod));
}
[TestMethod]
public void CanMatchAssemblyNameUsingArbitraryAmountOfSpaces()
{
AssemblyMatchingRule matchingRule = new AssemblyMatchingRule("mscorlib,Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
Assert.IsTrue(matchingRule.Matches(objectToStringMethod));
}
}
}

Просмотреть файл

@ -1,38 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
// 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("Tests.Unity.Interception")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Tests.Unity.Interception")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011,2012")]
[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)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8fea423a-5107-4a95-8391-57c468e04d7e")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -0,0 +1,70 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.Practices.Unity.InterceptionExtension;
namespace Microsoft.Practices.Unity.TestSupport
{
public class AdditionalInterfaceBehavior : IInterceptionBehavior
{
private static readonly MethodInfo DoNothingMethod = typeof(IAdditionalInterface).GetMethod("DoNothing");
private bool implicitlyAddInterface = true;
public AdditionalInterfaceBehavior()
{
implicitlyAddInterface = true;
}
public AdditionalInterfaceBehavior(bool implicitlyAddInterface)
{
this.implicitlyAddInterface = implicitlyAddInterface;
}
/// <summary>
/// Implement this method to execute your behavior processing.
/// </summary>
/// <param name="input">Inputs to the current call to the target.</param>
/// <param name="getNext">Delegate to execute to get the next delegate in the behavior chain.</param>
/// <returns>Return value from the target.</returns>
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
if (input.MethodBase == DoNothingMethod)
{
return ExecuteDoNothing(input);
}
return getNext()(input, getNext);
}
private IMethodReturn ExecuteDoNothing(IMethodInvocation input)
{
IMethodReturn returnValue = input.CreateMethodReturn(10);
return returnValue;
}
/// <summary>
/// Returns the interfaces required by the behavior for the objects it intercepts.
/// </summary>
/// <returns>The required interfaces.</returns>
public IEnumerable<Type> GetRequiredInterfaces()
{
if (implicitlyAddInterface)
{
return new[] { typeof(IAdditionalInterface) };
}
return Type.EmptyTypes;
}
/// <summary>
/// Returns a flag indicating if this behavior will actually do anything when invoked.
/// </summary>
/// <remarks>This is used to optimize interception. If the behaviors won't actually
/// do anything (for example, PIAB where no policies match) then the interception
/// mechanism can be skipped completely.</remarks>
public bool WillExecute
{
get { return true; }
}
}
}

Просмотреть файл

@ -0,0 +1,24 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Reflection;
using Microsoft.Practices.Unity.InterceptionExtension;
namespace Microsoft.Practices.Unity.TestSupport
{
/// <summary>
/// A simple matching rule class that always matches. Useful when you want
/// a policy to apply across the board.
/// </summary>
public class AlwaysMatchingRule : IMatchingRule
{
[InjectionConstructor]
public AlwaysMatchingRule()
{
}
public bool Matches(MethodBase member)
{
return true;
}
}
}

Просмотреть файл

@ -0,0 +1,45 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Reflection;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#elif __IOS__
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
namespace Microsoft.Practices.Unity.TestSupport
{
public static class AssertExtensions
{
public static void AssertException<TException>(Action action)
where TException : Exception
{
AssertException<TException>(action, (e) => { });
}
public static void AssertException<TException>(Action action, Action<TException> callback)
where TException : Exception
{
try
{
action();
Assert.Fail("Expected exception of type {0}", typeof(TException).GetTypeInfo().Name);
}
catch (TException e)
{
callback(e);
}
}
public static void IsInstanceOfType(object value, Type expectedType)
{
Assert.IsNotNull(value, "value should not be null");
Assert.IsNotNull(value, "expectedType should not be null");
Assert.IsTrue(expectedType.GetTypeInfo().IsAssignableFrom(value.GetType().GetTypeInfo()));
}
}
}

Просмотреть файл

@ -0,0 +1,43 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using Microsoft.Practices.Unity.InterceptionExtension;
namespace Microsoft.Practices.Unity.TestSupport
{
public class CallCountHandler : ICallHandler
{
private int callCount;
private int order = 0;
[InjectionConstructor]
public CallCountHandler()
{
}
/// <summary>
/// Gets or sets the order in which the handler will be executed
/// </summary>
public int Order
{
get
{
return order;
}
set
{
order = value;
}
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
++callCount;
return getNext()(input, getNext);
}
public int CallCount
{
get { return callCount; }
}
}
}

Просмотреть файл

@ -0,0 +1,40 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using Microsoft.Practices.Unity.InterceptionExtension;
namespace Microsoft.Practices.Unity.TestSupport
{
public class CallCountInterceptionBehavior : IInterceptionBehavior
{
private int callCount;
[InjectionConstructor]
public CallCountInterceptionBehavior()
{
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
++callCount;
return getNext()(input, getNext);
}
public int CallCount
{
get { return callCount; }
}
public IEnumerable<Type> GetRequiredInterfaces()
{
return Type.EmptyTypes;
}
public bool WillExecute
{
get { return true; }
}
}
}

Просмотреть файл

@ -0,0 +1,115 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#elif __IOS__
using NUnit.Framework;
using AssertFailedException = NUnit.Framework.AssertionException;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
namespace Microsoft.Practices.Unity.TestSupport
{
public static class CollectionAssertExtensions
{
public static void AreEqual(ICollection expected, ICollection actual)
{
CollectionAssertExtensions.AreEqual(expected, actual, new DefaultComparer());
}
public static void AreEqual(ICollection expected, ICollection actual, IComparer comparer)
{
CollectionAssertExtensions.AreEqual(expected, actual, comparer, string.Empty);
}
public static void AreEqual(ICollection expected, ICollection actual, string message)
{
CollectionAssertExtensions.AreEqual(expected, actual, new DefaultComparer(), message);
}
public static void AreEqual(ICollection expected, ICollection actual, IComparer comparer, string message)
{
string reason;
if (!CollectionAssertExtensions.AreCollectionsEqual(expected, actual, comparer, out reason))
{
throw new AssertFailedException(string.Format(CultureInfo.CurrentCulture, "{0}({1})", message, reason));
}
}
public static void AreEquivalent(ICollection expected, ICollection actual)
{
if (expected == actual)
{
return;
}
if (expected.Count != actual.Count)
{
throw new AssertFailedException("collections differ in size");
}
var expectedCounts = expected.Cast<object>().GroupBy(e => e).ToDictionary(g => g.Key, g => g.Count());
var actualCounts = actual.Cast<object>().GroupBy(e => e).ToDictionary(g => g.Key, g => g.Count());
foreach (var kvp in expectedCounts)
{
int actualCount = 0;
if (actualCounts.TryGetValue(kvp.Key, out actualCount))
{
if (actualCount != kvp.Value)
{
throw new AssertFailedException(string.Format(System.Globalization.CultureInfo.InvariantCulture, "collections have different count for element {0}", kvp.Key));
}
}
else
{
throw new AssertFailedException(string.Format(System.Globalization.CultureInfo.InvariantCulture, "actual does not contain element {0}", kvp.Key));
}
}
}
private static bool AreCollectionsEqual(ICollection expected, ICollection actual, IComparer comparer, out string reason)
{
if (expected == actual)
{
reason = null;
return true;
}
if (expected.Count != actual.Count)
{
reason = "collections differ in size";
return false;
}
var expectedEnum = expected.GetEnumerator();
var actualEnum = actual.GetEnumerator();
for (int i = 0; expectedEnum.MoveNext() && actualEnum.MoveNext(); i++)
{
if (comparer.Compare(expectedEnum.Current, actualEnum.Current) != 0)
{
reason = string.Format(CultureInfo.CurrentCulture, "collections differ at index {0}", i);
return false;
}
}
reason = null;
return true;
}
private class DefaultComparer : IComparer
{
public int Compare(object x, object y)
{
return x.Equals(y) ? 0 : -1;
}
}
}
}

Просмотреть файл

@ -0,0 +1,49 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.Practices.Unity.InterceptionExtension;
namespace Microsoft.Practices.Unity.TestSupport
{
public class DelegateInterceptionBehavior : IInterceptionBehavior
{
public static readonly Func<IEnumerable<Type>> NoRequiredInterfaces = () => Type.EmptyTypes;
private readonly Func<IMethodInvocation, GetNextInterceptionBehaviorDelegate, IMethodReturn> invoke;
private readonly Func<IEnumerable<Type>> requiredInterfaces;
public DelegateInterceptionBehavior(Func<IMethodInvocation, GetNextInterceptionBehaviorDelegate, IMethodReturn> invoke)
: this(invoke, NoRequiredInterfaces)
{ }
public DelegateInterceptionBehavior(
Func<IMethodInvocation, GetNextInterceptionBehaviorDelegate, IMethodReturn> invoke,
Func<IEnumerable<Type>> requiredInterfaces)
{
this.invoke = invoke;
this.requiredInterfaces = requiredInterfaces;
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
return this.invoke(input, getNext);
}
public IEnumerable<Type> GetRequiredInterfaces()
{
return this.requiredInterfaces();
}
/// <summary>
/// Returns a flag indicating if this behavior will actually do anything when invoked.
/// </summary>
/// <remarks>This is used to optimize interception. If the behaviors won't actually
/// do anything (for example, PIAB where no policies match) then the interception
/// mechanism can be skipped completely.</remarks>
public bool WillExecute
{
get { return true; }
}
}
}

Просмотреть файл

@ -0,0 +1,58 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#elif __IOS__
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
namespace Microsoft.Practices.Unity.TestSupport
{
public static class EnumerableAssertionExtensions
{
public static void AssertContainsExactly<TItem>(this IEnumerable<TItem> items, params TItem[] expected)
{
CollectionAssertExtensions.AreEqual(expected, items.ToArray());
}
public static void AssertContainsInAnyOrder<TItem>(this IEnumerable<TItem> items, params TItem[] expected)
{
CollectionAssertExtensions.AreEquivalent(expected, items.ToArray());
}
public static void AssertTrueForAll<TItem>(this IEnumerable<TItem> items, Func<TItem, bool> predicate)
{
Assert.IsTrue(items.All(predicate));
}
public static void AssertTrueForAny<TItem>(this IEnumerable<TItem> items, Func<TItem, bool> predicate)
{
Assert.IsTrue(items.Any(predicate));
}
public static void AssertFalseForAll<TItem>(this IEnumerable<TItem> items, Func<TItem, bool> predicate)
{
Assert.IsFalse(items.All(predicate));
}
public static void AssertFalseForAny<TItem>(this IEnumerable<TItem> items, Func<TItem, bool> predicate)
{
Assert.IsFalse(items.Any(predicate));
}
public static void AssertHasItems<TItem>(this IEnumerable<TItem> items)
{
Assert.IsTrue(items.Any());
}
public static void AssertHasNoItems<TItem>(this IEnumerable<TItem> items)
{
Assert.IsFalse(items.Any());
}
}
}

Просмотреть файл

@ -0,0 +1,36 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace Microsoft.Practices.Unity.TestSupport
{
public interface IConfigOne : IUnityContainerExtensionConfigurator
{
IConfigOne SetText(string text);
}
public interface IConfigTwo : IUnityContainerExtensionConfigurator
{
IConfigTwo SetMessage(string text);
}
public class ExtensibilityTestExtension : UnityContainerExtension, IConfigOne, IConfigTwo
{
public string ConfigOneText { get; private set; }
public string ConfigTwoText { get; private set; }
protected override void Initialize()
{
}
public IConfigOne SetText(string text)
{
this.ConfigOneText = text;
return this;
}
public IConfigTwo SetMessage(string text)
{
this.ConfigTwoText = text;
return this;
}
}
}

Просмотреть файл

@ -0,0 +1,73 @@
// 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 Microsoft.Practices.Unity.InterceptionExtension;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Practices.Unity.TestSupport
{
public class GlobalCountCallHandler : ICallHandler
{
public static Dictionary<string, int> Calls = new Dictionary<string, int>();
private string callHandlerName;
private int order = 0;
[InjectionConstructor]
public GlobalCountCallHandler()
: this("default")
{
}
public GlobalCountCallHandler(string callHandlerName)
{
this.callHandlerName = callHandlerName;
}
#region ICallHandler Members
/// <summary>
/// Gets or sets the order in which the handler will be executed
/// </summary>
public int Order
{
get
{
return order;
}
set
{
order = value;
}
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
if (!Calls.ContainsKey(callHandlerName))
{
Calls.Add(callHandlerName, 0);
}
Calls[callHandlerName]++;
return getNext().Invoke(input, getNext);
}
#endregion
}
public class GlobalCountCallHandlerAttribute : HandlerAttribute
{
public override ICallHandler CreateHandler(IUnityContainer ignored)
{
return new GlobalCountCallHandler(this.handlerName);
}
private string handlerName;
public string HandlerName
{
get { return this.handlerName; }
set { this.handlerName = value; }
}
}
}

Просмотреть файл

@ -0,0 +1,43 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.Practices.Unity.InterceptionExtension;
namespace Microsoft.Practices.Unity.TestSupport
{
public class GlobalCountInterceptionBehavior : IInterceptionBehavior
{
public static Dictionary<string, int> Calls = new Dictionary<string, int>();
private string callHandlerName;
[InjectionConstructor]
public GlobalCountInterceptionBehavior()
: this("default")
{
}
public GlobalCountInterceptionBehavior(string callHandlerName)
{
this.callHandlerName = callHandlerName;
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
if (!Calls.ContainsKey(callHandlerName))
{
Calls.Add(callHandlerName, 0);
}
Calls[callHandlerName]++;
return getNext().Invoke(input, getNext);
}
public IEnumerable<Type> GetRequiredInterfaces()
{
return Type.EmptyTypes;
}
public bool WillExecute { get { return true; } }
}
}

Просмотреть файл

@ -0,0 +1,14 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Microsoft.Practices.Unity.TestSupport
{
public interface IAdditionalInterface
{
int DoNothing();
}
}

Просмотреть файл

@ -0,0 +1,8 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace Microsoft.Practices.Unity.TestSupport
{
public interface ILogger
{
}
}

Просмотреть файл

@ -0,0 +1,165 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.Practices.ObjectBuilder2;
namespace Microsoft.Practices.Unity.TestSupport
{
public class MockBuilderContext : IBuilderContext
{
private ILifetimeContainer lifetime = new LifetimeContainer();
private NamedTypeBuildKey originalBuildKey = null;
private IPolicyList persistentPolicies;
private IPolicyList policies;
private StrategyChain strategies = new StrategyChain();
private CompositeResolverOverride resolverOverrides = new CompositeResolverOverride();
private NamedTypeBuildKey buildKey = null;
private object existing = null;
private IRecoveryStack recoveryStack = new RecoveryStack();
public MockBuilderContext()
{
this.persistentPolicies = new PolicyList();
this.policies = new PolicyList(persistentPolicies);
}
public ILifetimeContainer Lifetime
{
get { return lifetime; }
}
public NamedTypeBuildKey OriginalBuildKey
{
get { return originalBuildKey; }
}
public IPolicyList PersistentPolicies
{
get { return persistentPolicies; }
}
public IPolicyList Policies
{
get { return policies; }
}
public IRecoveryStack RecoveryStack
{
get { return recoveryStack; }
}
public StrategyChain Strategies
{
get { return strategies; }
}
IStrategyChain IBuilderContext.Strategies
{
get { return strategies; }
}
public NamedTypeBuildKey BuildKey
{
get { return buildKey; }
set { buildKey = value; }
}
public object Existing
{
get { return existing; }
set { existing = value; }
}
public bool BuildComplete { get; set; }
public object CurrentOperation { get; set; }
public IBuilderContext ChildContext { get; set; }
public void AddResolverOverrides(IEnumerable<ResolverOverride> newOverrides)
{
resolverOverrides.AddRange(newOverrides);
}
public IDependencyResolverPolicy GetOverriddenResolver(Type dependencyType)
{
return resolverOverrides.GetResolver(this, dependencyType);
}
public IBuilderContext CloneForNewBuild(NamedTypeBuildKey newBuildKey, object newExistingObject)
{
var newContext = new MockBuilderContext
{
strategies = strategies,
persistentPolicies = persistentPolicies,
policies = policies,
lifetime = lifetime,
originalBuildKey = buildKey,
buildKey = newBuildKey,
existing = newExistingObject
};
newContext.resolverOverrides.Add(resolverOverrides);
return newContext;
}
/// <summary>
/// A convenience method to do a new buildup operation on an existing context.
/// </summary>
/// <param name="newBuildKey">Key to use to build up.</param>
/// <returns>Created object.</returns>
public object NewBuildUp(NamedTypeBuildKey newBuildKey)
{
var clone = CloneForNewBuild(newBuildKey, null);
return clone.Strategies.ExecuteBuildUp(clone);
}
/// <summary>
/// A convenience method to do a new buildup operation on an existing context. This
/// overload allows you to specify extra policies which will be in effect for the duration
/// of the build.
/// </summary>
/// <param name="newBuildKey">Key defining what to build up.</param>
/// <param name="childCustomizationBlock">A delegate that takes a <see cref="IBuilderContext"/>. This
/// is invoked with the new child context before the build up process starts. This gives callers
/// the opportunity to customize the context for the build process.</param>
/// <returns>Created object.</returns>
public object NewBuildUp(NamedTypeBuildKey newBuildKey, Action<IBuilderContext> childCustomizationBlock)
{
var newContext = new MockBuilderContext
{
strategies = strategies,
persistentPolicies = persistentPolicies,
policies = new PolicyList(persistentPolicies),
lifetime = lifetime,
originalBuildKey = buildKey,
buildKey = newBuildKey,
existing = null
};
newContext.resolverOverrides.Add(resolverOverrides);
childCustomizationBlock(newContext);
return strategies.ExecuteBuildUp(newContext);
}
public object ExecuteBuildUp(NamedTypeBuildKey buildKey, object existing)
{
this.BuildKey = buildKey;
this.Existing = existing;
return Strategies.ExecuteBuildUp(this);
}
public object ExecuteTearDown(object existing)
{
this.BuildKey = null;
this.Existing = existing;
Strategies.Reverse().ExecuteTearDown(this);
return existing;
}
}
}

Просмотреть файл

@ -0,0 +1,28 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace Microsoft.Practices.Unity.TestSupport
{
public class MockContainerExtension : UnityContainerExtension, IMockConfiguration
{
private bool initializeWasCalled = false;
public bool InitializeWasCalled
{
get { return this.initializeWasCalled; }
}
public new ExtensionContext Context
{
get { return base.Context; }
}
protected override void Initialize()
{
this.initializeWasCalled = true;
}
}
public interface IMockConfiguration : IUnityContainerExtensionConfigurator
{
}
}

Просмотреть файл

@ -0,0 +1,35 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace Microsoft.Practices.Unity.TestSupport
{
public class MockDatabase
{
private string connectionString;
private bool defaultConstructorCalled;
public MockDatabase()
{
defaultConstructorCalled = true;
}
public MockDatabase(string connectionString)
{
this.connectionString = connectionString;
}
public static MockDatabase Create(string connectionString)
{
return new MockDatabase(connectionString);
}
public string ConnectionString
{
get { return connectionString; }
}
public bool DefaultConstructorCalled
{
get { return defaultConstructorCalled; }
}
}
}

Просмотреть файл

@ -0,0 +1,8 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace Microsoft.Practices.Unity.TestSupport
{
public class MockLogger : ILogger
{
}
}

Просмотреть файл

@ -0,0 +1,101 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using Microsoft.Practices.Unity.InterceptionExtension;
namespace Microsoft.Practices.Unity.TestSupport
{
public class NaiveINotifyPropertyChangedInterceptionBehavior : IInterceptionBehavior
{
private readonly object handlerLock = new object();
private PropertyChangedEventHandler handler;
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
var methodReturn = InvokeINotifyPropertyChangedMethod(input);
if (methodReturn != null)
{
return methodReturn;
}
methodReturn = getNext()(input, getNext);
if (methodReturn.Exception == null && input.MethodBase.IsSpecialName)
{
var property = GetPropertyInfoForSetMethod(input);
if (property != null)
{
var currentHandler = this.handler;
if (currentHandler != null)
{
try
{
currentHandler(input.Target, new PropertyChangedEventArgs(property.Name));
}
catch (Exception e)
{
return input.CreateExceptionMethodReturn(e);
}
}
}
}
return methodReturn;
}
private IMethodReturn InvokeINotifyPropertyChangedMethod(IMethodInvocation input)
{
if (input.MethodBase.DeclaringType == typeof(INotifyPropertyChanged))
{
switch (input.MethodBase.Name)
{
case "add_PropertyChanged":
lock (handlerLock)
{
handler = (PropertyChangedEventHandler)Delegate.Combine(handler, (Delegate)input.Arguments[0]);
}
break;
case "remove_PropertyChanged":
lock (handlerLock)
{
handler = (PropertyChangedEventHandler)Delegate.Remove(handler, (Delegate)input.Arguments[0]);
}
break;
default:
return input.CreateExceptionMethodReturn(new InvalidOperationException());
}
return input.CreateMethodReturn(null);
}
return null;
}
private static PropertyInfo GetPropertyInfoForSetMethod(IMethodInvocation input)
{
foreach (var property in input.MethodBase.DeclaringType.GetProperties())
{
if (input.MethodBase == property.GetSetMethod())
{
return property;
}
}
return null;
}
public IEnumerable<Type> GetRequiredInterfaces()
{
return new[] { typeof(INotifyPropertyChanged) };
}
public bool WillExecute { get { return true; } }
}
}

Просмотреть файл

@ -0,0 +1,92 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.ComponentModel;
using System.Globalization;
namespace Microsoft.Practices.Unity.TestSupport
{
/// <summary>
/// A faked up type converter that converts integers, then returns the
/// negative value. Used to test the instances registration in config.
/// </summary>
internal class NegativeTypeConverter : TypeConverter
{
/// <summary>
/// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context.
/// </summary>
///
/// <returns>
/// true if this converter can perform the conversion; otherwise, false.
/// </returns>
///
/// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"></see> that provides a format context. </param>
/// <param name="sourceType">A <see cref="T:System.Type"></see> that represents the type you want to convert from. </param>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
/// <summary>
/// Returns whether this converter can convert the object to the specified type, using the specified context.
/// </summary>
///
/// <returns>
/// true if this converter can perform the conversion; otherwise, false.
/// </returns>
///
/// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"></see> that provides a format context. </param>
/// <param name="destinationType">A <see cref="T:System.Type"></see> that represents the type you want to convert to. </param>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
/// <summary>
/// Converts the given object to the type of this converter, using the specified context and culture information.
/// </summary>
///
/// <returns>
/// An <see cref="T:System.Object"></see> that represents the converted value.
/// </returns>
///
/// <param name="culture">The <see cref="T:System.Globalization.CultureInfo"></see> to use as the current culture. </param>
/// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"></see> that provides a format context. </param>
/// <param name="value">The <see cref="T:System.Object"></see> to convert. </param>
/// <exception cref="T:System.NotSupportedException">The conversion cannot be performed. </exception>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string)
{
int result = int.Parse(value.ToString());
return -result;
}
return base.ConvertFrom(context, culture, value);
}
/// <summary>
/// Converts the given value object to the specified type, using the specified context and culture information.
/// </summary>
///
/// <returns>
/// An <see cref="T:System.Object"></see> that represents the converted value.
/// </returns>
///
/// <param name="culture">A <see cref="T:System.Globalization.CultureInfo"></see>. If null is passed, the current culture is assumed. </param>
/// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"></see> that provides a format context. </param>
/// <param name="destinationType">The <see cref="T:System.Type"></see> to convert the value parameter to. </param>
/// <param name="value">The <see cref="T:System.Object"></see> to convert. </param>
/// <exception cref="T:System.NotSupportedException">The conversion cannot be performed. </exception>
/// <exception cref="T:System.ArgumentNullException">The destinationType parameter is null. </exception>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,
Type destinationType)
{
if (destinationType == typeof(string))
{
int intValue = (int)value;
return (-intValue).ToString();
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
}

Просмотреть файл

@ -0,0 +1,16 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace Microsoft.Practices.Unity.TestSupport
{
public class ObjectUsingLogger
{
private ILogger logger;
[Dependency]
public ILogger Logger
{
get { return logger; }
set { logger = value; }
}
}
}

Просмотреть файл

@ -0,0 +1,24 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace Microsoft.Practices.Unity.TestSupport
{
public class ObjectWithInjectionMethod
{
public string ConnectionString { get; private set; }
public ILogger Logger { get; private set; }
public object MoreData { get; private set; }
public void Initialize(string connectionString, ILogger logger)
{
ConnectionString = connectionString;
Logger = logger;
}
public void MoreInitialization(object data)
{
MoreData = data;
}
}
}

Просмотреть файл

@ -0,0 +1,19 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace Microsoft.Practices.Unity.TestSupport
{
public class ObjectWithOneConstructorDependency
{
private ILogger logger;
public ObjectWithOneConstructorDependency(ILogger logger)
{
this.logger = logger;
}
public ILogger Logger
{
get { return logger; }
}
}
}

Просмотреть файл

@ -0,0 +1,28 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using Microsoft.Practices.Unity.TestSupport;
namespace Microsoft.Practices.Unity.TestSupport
{
public class ObjectWithTwoConstructorParameters
{
private string connectionString;
private ILogger logger;
public ObjectWithTwoConstructorParameters(string connectionString, ILogger logger)
{
this.connectionString = connectionString;
this.logger = logger;
}
public string ConnectionString
{
get { return connectionString; }
}
public ILogger Logger
{
get { return logger; }
}
}
}

Просмотреть файл

@ -0,0 +1,39 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#elif __IOS__
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
namespace Microsoft.Practices.Unity.TestSupport
{
public class ObjectWithTwoProperties
{
private object obj1;
private object obj2;
[Dependency]
public object Obj1
{
get { return obj1; }
set { obj1 = value; }
}
[Dependency]
public object Obj2
{
get { return obj2; }
set { obj2 = value; }
}
public void Validate()
{
Assert.IsNotNull(obj1);
Assert.IsNotNull(obj2);
Assert.AreNotSame(obj1, obj2);
}
}
}

Просмотреть файл

@ -0,0 +1,23 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Practices.Unity.TestSupport
{
public class RegistrationsToAssertOn
{
public readonly IEnumerable<ContainerRegistration> Registrations;
public RegistrationsToAssertOn(IEnumerable<ContainerRegistration> registrations)
{
this.Registrations = registrations;
}
public void HasLifetime<TLifetime>() where TLifetime : LifetimeManager
{
Assert.IsTrue(Registrations.All(r => r.LifetimeManagerType == typeof(TLifetime)));
}
}
}

Просмотреть файл

@ -0,0 +1,98 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Microsoft.Practices.ObjectBuilder2;
namespace Microsoft.Practices.Unity.TestSupport
{
[TypeConverter(typeof(SessionKeyTypeConverter))]
public class SessionLifetimeManager : LifetimeManager
{
private readonly string sessionKey;
public static string LastUsedSessionKey;
public SessionLifetimeManager(string sessionKey)
{
this.sessionKey = sessionKey;
}
public string SessionKey
{
get { return this.sessionKey; }
}
public override object GetValue()
{
LastUsedSessionKey = this.sessionKey;
return null;
}
public override void SetValue(object newValue)
{
}
public override void RemoveValue()
{
}
}
public class SessionKeyTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType.GetType() == typeof(string);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
public override object ConvertFrom(
ITypeDescriptorContext context, CultureInfo culture, object value)
{
return new SessionLifetimeManager((string)value);
}
public override object ConvertTo(
ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
return ((SessionLifetimeManager)value).SessionKey;
}
}
public class ReversedSessionKeyTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
public override object ConvertFrom(
ITypeDescriptorContext context, CultureInfo culture, object value)
{
string key = Reverse((string)value);
return new SessionLifetimeManager(key);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
string key = Reverse(((SessionLifetimeManager)value).SessionKey);
return key;
}
private static string Reverse(IEnumerable<char> s)
{
var chars = new Stack<char>(s);
return string.Join(string.Empty, chars);
}
}
}

Просмотреть файл

@ -0,0 +1,8 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace Microsoft.Practices.Unity.TestSupport
{
public class SpecialLogger : ILogger
{
}
}

Просмотреть файл

@ -0,0 +1,21 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Practices.Unity.TestSupport
{
public static class TypeReflectionExtensions
{
public static ConstructorInfo GetMatchingConstructor(this Type type, Type[] constructorParamTypes)
{
return type.GetTypeInfo().DeclaredConstructors
.Where(c => c.GetParameters().Select(p => p.ParameterType).SequenceEqual(constructorParamTypes))
.FirstOrDefault();
}
}
}

Просмотреть файл

@ -0,0 +1,17 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Microsoft.Practices.Unity.TestSupport
{
public partial class Wrappable : MarshalByRefObject
{
}
public partial class WrappableWithProperty : MarshalByRefObject
{
}
}

Просмотреть файл

@ -0,0 +1,88 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
namespace Microsoft.Practices.Unity.TestSupport
{
public class WrappableThroughInterface : Interface, InterfaceA
{
public void Method() { }
public void Method3() { }
public void MethodA() { }
}
public class WrappableThroughInterfaceWithAttributes : Interface
{
[GlobalCountCallHandler(HandlerName = "WrappableThroughInterfaceWithAttributes-Method")]
public void Method() { }
[GlobalCountCallHandler(HandlerName = "WrappableThroughInterfaceWithAttributes-Method3")]
public void Method3() { }
}
public interface Interface : InterfaceBase
{
void Method();
}
public interface InterfaceA
{
void MethodA();
}
public interface InterfaceBase
{
void Method3();
}
public class DerivedWrappable : Wrappable
{
public void Method4() { }
}
public partial class Wrappable : Interface, InterfaceA
{
public virtual void Method() { }
public virtual void Method2() { }
public virtual void Method3() { }
public virtual void MethodA() { }
public virtual void MethodRef(ref object parameter)
{
parameter = "parameter";
}
public virtual void MethodRefValue(ref int parameter)
{
parameter = 42;
}
public virtual void MethodOut(out object parameter)
{
parameter = "parameter";
}
public virtual void MethodOutValue(out int parameter)
{
parameter = 42;
}
}
public partial class WrappableWithProperty
{
public virtual void Method() { }
private Wrappable wrappable;
public virtual Wrappable Wrappable
{
get { return wrappable; }
set { wrappable = value; }
}
}
}

Просмотреть файл

@ -789,7 +789,7 @@ namespace Microsoft.Practices.Unity.InterceptionExtension.Tests.VirtualMethodInt
{
char[] chars = obj.ToString().ToCharArray();
Array.Reverse(chars);
return chars.JoinStrings(String.Empty);
return string.Join(string.Empty, chars);
}
}