Code Monkey home page Code Monkey logo

pose's People

Contributors

dr-beat avatar tonerdo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pose's Issues

Shim for an open generic?

I would like to Shim calls to an open generic method on a static class, with a signature like:

public static void Throws<T>(Func<T> func)

I can't figure out how to do it (without explicitly specifying the T type, which I don't want to do as this is going to be hidden in library code). Is there a way to shim it?

Allow to isolate a parent property on a child instance

Version: Nuget Pose 1.2.0.

Trying to shim an instance property of a parent class on an instance of a derived class silently fails.
Shimming the same property on an instance of the parent class works great.

Repro test:

class Sut
{
	private string _text;
	public string text { get => _text; set => _text = "unshimmed " + value; }
}
class ChildSut : Sut { }

[Fact]
public void PropertySetterShimWorksOnParent()
{
	var sut = new ChildSut();
	string capturedText = null;
	var shimText = Shim.Replace(() => sut.text, true).With((ChildSut @this, string value) => { capturedText = value; });
	PoseContext.Isolate(() =>
	{
		sut.text = "test";
	}, shimText);

	Assert.Null(sut.text);
	Assert.Equal("test", capturedText);
}

Assert fails with Actual: unshimmed test

System.InvalidProgramException when trying to shim DateTime.Now

Write the following program:

using System;
using Pose;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            var dt = DateTime.Now;
            Shim dateTimeShim = Shim.Replace(() => DateTime.Now).With(() => new DateTime(2004, 4, 4));
            PoseContext.Isolate(() =>
                {
                    var time = DateTime.Now;
                    Console.WriteLine(time);
                },
                dateTimeShim);
        }
    }
}

Compile it with netcoreapp2.0 and run with .NET Core ⇒ throws an exception:

Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidProgramException: Common Language
 Runtime detected an invalid program.
   at dynamic_System.Text.Encoding_.ctor(Encoding , Int32 )
   at stub_ctor_System.Text.Encoding_.ctor(Encoding , Int32 , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Text.OSEncoding_.ctor(OSEncoding , Int32 )
   at stub_ctor_System.Text.OSEncoding_.ctor(Int32 , RuntimeMethodHandle , RuntimeTypeHandle )
   at stub_System.Text.EncodingHelper_GetSupportedConsoleEncoding(Int32 , RuntimeMethodHandle , RuntimeTypeHandle )
   at stub_System.ConsolePal_get_OutputEncoding(RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Threading.LazyInitializer_EnsureInitializedCore(Encoding& , Object& , Func`1 )
   at stub_System.Threading.LazyInitializer_EnsureInitializedCore(Encoding& , Object& , Func`1 , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Threading.LazyInitializer_EnsureInitialized(Encoding& , Object& , Func`1 )
   at stub_System.Threading.LazyInitializer_EnsureInitialized(Encoding& , Object& , Func`1 , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Console_EnsureInitialized(Encoding& , Func`1 )
   at stub_System.Console_EnsureInitialized(Encoding& , Func`1 , RuntimeMethodHandle , RuntimeTypeHandle )
   at stub_System.Console_get_OutputEncoding(RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.ConsolePal_GetUseFileAPIs(Int32 )
   at stub_System.ConsolePal_GetUseFileAPIs(Int32 , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.ConsolePal_GetStandardFile(Int32 , FileAccess )
   at stub_System.ConsolePal_GetStandardFile(Int32 , FileAccess , RuntimeMethodHandle , RuntimeTypeHandle )
   at stub_System.ConsolePal_OpenStandardOutput(RuntimeMethodHandle , RuntimeTypeHandle )
   at stub_System.Console_OpenStandardOutput(RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Console+<>c_<get_Out>b__25_0(<>c )
   at dynamic_System.Threading.LazyInitializer_EnsureInitializedCore(TextWriter& , Object& , Func`1 )
   at stub_System.Threading.LazyInitializer_EnsureInitializedCore(TextWriter& , Object& , Func`1 , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Threading.LazyInitializer_EnsureInitialized(TextWriter& , Object& , Func`1 )
   at stub_System.Threading.LazyInitializer_EnsureInitialized(TextWriter& , Object& , Func`1 , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Console_EnsureInitialized(TextWriter& , Func`1 )
   at stub_System.Console_EnsureInitialized(TextWriter& , Func`1 , RuntimeMethodHandle , RuntimeTypeHandle )
   at stub_System.Console_get_Out(RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Console_WriteLine(Object )
   at stub_System.Console_WriteLine(Object , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_ConsoleApp4.Program+<>c_<Main>b__0_2(<>c )
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at Pose.PoseContext.Isolate(Action entryPoint, Shim[] shims)
   at ConsoleApp4.Program.Main(String[] args) in T:\Temp\ConsoleApp4\ConsoleApp4\Program.cs:line 12

NullReferenceException in Pose.Helpers.StubHelper.GetMatchingShimIndex

Using Pose in a fairly complex test I've been getting this exception. It seems to be trying to find a shim for method(s) that haven't been shimmed. Unfortunately I've not been able to reproduce this in a simple example and can't post the full code from my product.

The test project is using an in-memory ASP.NET Core server (https://docs.microsoft.com/en-us/aspnet/core/testing/integration-testing) and the method I'm shimming is called from the Controller, not directly from the unit test itself. I expect this is the underlying problem as I'm calling PoseContext.Isolate from the "client" and expecting it to maintain that isolation on the "server" side.

Anyway, I'm posting this anyway in case you have any suggestions.

Unit test:

#if !NET462
        [Fact]
        public void When_person_exists_in_db()
        {
            var sqlMapperShim = Shim.Replace(() => SqlMapper.QueryAsync<Applicant>(Is.A<IDbConnection>(), Is.A<CommandDefinition>()))
                .With(
                    delegate (IDbConnection dbConnection, CommandDefinition commandDefinition)
                    {
                        return Task.FromResult(SqlMapper.Query<Applicant>(dbConnection, commandDefinition));
                    });

            Default<ApplicantListViewModel> response = null;

            PoseContext.Isolate(() =>
            {
                var httpResponse = this.Read($"organisations/{TestConstants.OrganisationIdentifier}/applicants");
                response = httpResponse.Content.ReadAsAsync<Default<ApplicantListViewModel>>().Result;
            },
            sqlMapperShim);

            // Assert
            response.ShouldNotBe(null);
        }
#endif

Test results:

Test run for C:\Code\MyCompany\MyProduct\test\MyCompany.MyProduct.Specs\bin\Debug\netcoreapp2.0\MyCompany.MyProduct.Specs.dll(.NETCoreApp,Version=v2.0)
Microsoft (R) Test Execution Command Line Tool Version 15.3.0-preview-20170628-02
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
[xUnit.net 00:00:01.4649449]   Discovering: MyCompany.MyProduct.Specs
[xUnit.net 00:00:01.5546231]   Discovered:  MyCompany.MyProduct.Specs
[xUnit.net 00:00:01.5617069]   Starting:    MyCompany.MyProduct.Specs
[xUnit.net 00:00:53.7768297]     MyCompany.MyProduct.Specs.ApplicantsSpecs.ApplicantListSpecs.When_person_exists_in_db2 [FAIL]
[xUnit.net 00:00:53.7786980]       System.NullReferenceException : Object reference not set to an instance of an object.
[xUnit.net 00:00:53.7800539]       Stack Trace:
[xUnit.net 00:00:53.7811621]         C:\Code\MyCompany\MyProduct\test\MyCompany.MyProduct.Specs\Pose\IL\MethodRewriter.cs(27,0): at Pose.IL.MethodRewriter.Rewrite()
[xUnit.net 00:00:53.7813452]            at stub_System.Net.Http.Headers.HttpHeaders_ParseRawHeaderValues(HttpHeaders , String , HeaderStoreItemInfo , Boolean , RuntimeMethodHandle , RuntimeTypeHandle )
[xUnit.net 00:00:53.7814211]            at dynamic_System.Net.Http.Headers.HttpHeaders_AddHeaders(HttpHeaders , HttpHeaders )
[xUnit.net 00:00:53.7814574]            at stub_System.Net.Http.Headers.HttpHeaders_AddHeaders(HttpHeaders , HttpHeaders , RuntimeMethodHandle , RuntimeTypeHandle )
[xUnit.net 00:00:53.7814902]            at dynamic_System.Net.Http.Headers.HttpRequestHeaders_AddHeaders(HttpRequestHeaders , HttpHeaders )
[xUnit.net 00:00:53.7815276]            at stub_System.Net.Http.Headers.HttpHeaders_AddHeaders(HttpHeaders , HttpHeaders , RuntimeMethodHandle , RuntimeTypeHandle )
[xUnit.net 00:00:53.7815669]            at stub_System.Net.Http.HttpClient_PrepareRequestMessage(HttpClient , HttpRequestMessage , RuntimeMethodHandle , RuntimeTypeHandle )
[xUnit.net 00:00:53.7816352]            at dynamic_System.Net.Http.HttpClient_SendAsync(HttpClient , HttpRequestMessage , HttpCompletionOption , CancellationToken )
[xUnit.net 00:00:53.7816805]            at stub_System.Net.Http.HttpClient_SendAsync(HttpClient , HttpRequestMessage , HttpCompletionOption , CancellationToken , RuntimeMethodHandle , RuntimeTypeHandle )
[xUnit.net 00:00:53.7817409]            at dynamic_System.Net.Http.HttpClient_GetAsync(HttpClient , Uri , HttpCompletionOption , CancellationToken )
[xUnit.net 00:00:53.7817783]            at stub_System.Net.Http.HttpClient_GetAsync(HttpClient , Uri , HttpCompletionOption , CancellationToken , RuntimeMethodHandle , RuntimeTypeHandle )
[xUnit.net 00:00:53.7818927]            at dynamic_System.Net.Http.HttpClient_GetAsync(HttpClient , Uri , HttpCompletionOption )
[xUnit.net 00:00:53.7819275]            at stub_System.Net.Http.HttpClient_GetAsync(HttpClient , Uri , HttpCompletionOption , RuntimeMethodHandle , RuntimeTypeHandle )
[xUnit.net 00:00:53.7820015]            at dynamic_System.Net.Http.HttpClient_GetAsync(HttpClient , Uri )
[xUnit.net 00:00:53.7820570]            at stub_System.Net.Http.HttpClient_GetAsync(HttpClient , Uri , RuntimeMethodHandle , RuntimeTypeHandle )
[xUnit.net 00:00:53.7821121]            at stub_System.Net.Http.HttpClient_GetAsync(HttpClient , String , RuntimeMethodHandle , RuntimeTypeHandle )
[xUnit.net 00:00:53.7821604]            at dynamic_MyCompany.MyProduct.Specs.BehavesLikeApi_Read(BehavesLikeApi , String , Dictionary`2 , Dictionary`2 )
[xUnit.net 00:00:53.7822409]            at stub_MyCompany.MyProduct.Specs.BehavesLikeApi_Read(BehavesLikeApi , String , Dictionary`2 , Dictionary`2 , RuntimeMethodHandle , RuntimeTypeHandle )
[xUnit.net 00:00:53.7823764]            at dynamic_MyCompany.MyProduct.Specs.ApplicantsSpecs.ApplicantListSpecs+<>c__DisplayClass3_0_<When_person_exists_in_db2>b__1(<>c__DisplayClass3_0 )
Failed   MyCompany.MyProduct.Specs.ApplicantsSpecs.ApplicantListSpecs.When_person_exists_in_db2
Error Message:
 System.NullReferenceException : Object reference not set to an instance of an object.
Stack Trace:
   at Pose.IL.MethodRewriter.Rewrite() in C:\Code\MyCompany\MyProduct\test\MyCompany.MyProduct.Specs\Pose\IL\MethodRewriter.cs:line 27
   at stub_System.Net.Http.Headers.HttpHeaders_ParseRawHeaderValues(HttpHeaders , String , HeaderStoreItemInfo , Boolean , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Net.Http.Headers.HttpHeaders_AddHeaders(HttpHeaders , HttpHeaders )
   at stub_System.Net.Http.Headers.HttpHeaders_AddHeaders(HttpHeaders , HttpHeaders , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Net.Http.Headers.HttpRequestHeaders_AddHeaders(HttpRequestHeaders , HttpHeaders )
   at stub_System.Net.Http.Headers.HttpHeaders_AddHeaders(HttpHeaders , HttpHeaders , RuntimeMethodHandle , RuntimeTypeHandle )
   at stub_System.Net.Http.HttpClient_PrepareRequestMessage(HttpClient , HttpRequestMessage , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Net.Http.HttpClient_SendAsync(HttpClient , HttpRequestMessage , HttpCompletionOption , CancellationToken )
   at stub_System.Net.Http.HttpClient_SendAsync(HttpClient , HttpRequestMessage , HttpCompletionOption , CancellationToken , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Net.Http.HttpClient_GetAsync(HttpClient , Uri , HttpCompletionOption , CancellationToken )
   at stub_System.Net.Http.HttpClient_GetAsync(HttpClient , Uri , HttpCompletionOption , CancellationToken , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Net.Http.HttpClient_GetAsync(HttpClient , Uri , HttpCompletionOption )
   at stub_System.Net.Http.HttpClient_GetAsync(HttpClient , Uri , HttpCompletionOption , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Net.Http.HttpClient_GetAsync(HttpClient , Uri )
   at stub_System.Net.Http.HttpClient_GetAsync(HttpClient , Uri , RuntimeMethodHandle , RuntimeTypeHandle )
   at stub_System.Net.Http.HttpClient_GetAsync(HttpClient , String , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_MyCompany.MyProduct.Specs.BehavesLikeApi_Read(BehavesLikeApi , String , Dictionary`2 , Dictionary`2 )
   at stub_MyCompany.MyProduct.Specs.BehavesLikeApi_Read(BehavesLikeApi , String , Dictionary`2 , Dictionary`2 , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_MyCompany.MyProduct.Specs.ApplicantsSpecs.ApplicantListSpecs+<>c__DisplayClass3_0_<When_person_exists_in_db2>b__1(<>c__DisplayClass3_0 )
[xUnit.net 00:01:10.9337665]   Finished:    MyCompany.MyProduct.Specs

Total tests: 47. Passed: 46. Failed: 1. Skipped: 0.
Test Run Failed.

System.BadImageFormatException when using

Hi @tonerdo,

I'm having this exception

System.BadImageFormatException: 
An attempt was made to load a program with an incorrect format.
(Exception from HRESULT: 0x8007000B)

The Shim is created with

Shim shimExecutor = Shim.Replace(() => 
    Is.A<QueryExecutor>().ExecuteAsync<T>(Is.A<string>(), Is.A<object>()))
    .With(delegate (QueryExecutor @this, string rawQuery, object parameters) 
    {
        return default(Task<IEnumerable<T>>);
    });

And I use context like this

IEnumerable<BaseReadModel> results = null;
PoseContext.Isolate(() =>
{
    results = executor.Execute<BaseReadModel>("lorem_ipsum");
}, shimExecutor);

I obtain exception when invoke Isolate.

The target framework is netcoreapp2.2 and I have installed version 2.2.102 on my machine, the version of Pose is 1.2.1.

Doesn't work in Unity 3D on Mac OS

Hi I tried the examples in Unity3D 2019.1.9f1 on Mac OS 10.13.6 under .NET 4.x player settings, using https://github.com/jbevain/mono.reflection for the using Mono.Reflection clauses in Pose, but I can't get anything at all to work:

public class MyClass
{
	public void DoSomething()
	{
		Debug.Log("DoSomething()");
	}
}

// try shimming class method:

MyClass myClass = new MyClass();

myClass.DoSomething();

Shim classShim = Shim.Replace(() => Is.A<MyClass>().DoSomething()).With(
				delegate(MyClass @this) { Debug.Log("doing something else with myClass"); });

myClass.DoSomething();

// try shimming instance method:

MyClass myClass = new MyClass();

myClass.DoSomething();

Shim myClassShim = Shim.Replace(() => myClass.DoSomething()).With(
				delegate(MyClass @this) { Debug.Log("doing something else with myClass"); });

myClass.DoSomething();

No matter what I try, I always see:

DoSomething()
DoSomething()

I'm wondering if this is due more to running on Mac OS than using Unity. Or perhaps that Mono.Reflection repo just doesn't work.

If nothing comes to mind, I can maybe put together an example Unity project that at least shows the Pose issue.


BONUS

Also while I have you here, do you know if Pose shims work on iOS and Android? It's looking like the technique of swapping the IL code might not work on mobile because they are sticklers about using immutable code only (at least for Harmony, which uses similar techniques):

pardeike/Harmony#196

I can maybe use https://github.com/jbevain/cecil but it might have similar issues.

I'm trying to extend a sealed class so that I can have a delegate fire whenever a class instance method is called or a property is changed, in order to implement reactive programming techniques. Without that functionality, I'll have no choice but to tell users to remember to call MyClass.SomethingChanged(sealedClass), which isn't future-proof so will inevitably lead to bugs, especially when new developers use the class and forget to call that. So far I've wasted upwards of a week chasing this, and it's been one of the first great disappointments I've encountered in C#.

I tried building a dynamic class with https://github.com/meziantou/Meziantou.Framework/blob/master/src/Meziantou.Framework/ReflectionDynamicObject.cs to pass any method calls through to the sealed class, but I was unable to get the implicit cast operator working, so I couldn't pass the dynamic class off as the original type back to Unity (it caused a stack overflow trying to return and cast itself infinitely). Which means that users would have to cast the sealed class to the dynamic class themselves which defeats the whole purpose.

This is a really big problem that severely limits Unity to cookie cutter solutions since we can't override builtin functionality. Of course most people have no idea what I'm talking about, so just tell me I'm doing it wrong. I'm hoping someone with your depth of understanding on these issues might have an idea for how to override/inherit sealed class methods or add INotifyPropertyChanged or shim a sealed class instance, and be able to run that type of code in production.


Thanks!

Null Reference Exception when Replacing ShowDialog() on a WinForm

I was playing with Pose and ran into a null reference exception when trying to replace the ShowDialog method on a Windows Form.

This is a .net 4.6.1 assembly using MSTest as the test runner.

The code under test is:

public class FormShower
{
    public void ShowTheForm()
    {
        Form1 f = new Form1();
        f.ShowDialog();
    }
}

The Test code is

Shim s = Shim.Replace(() => Is.A<PosePlayground.Form1>().ShowDialog())
            .With(delegate (Form1 @this) { Console.WriteLine("hello"); return DialogResult.OK; });

FormShower fs = new FormShower();
PoseContext.Isolate(() =>
{
    fs.ShowTheForm();
}, s);

Using this code, I get the following exception:

Result StackTrace:	
at Pose.Helpers.StubHelper.GetIndexOfMatchingShim(MethodBase methodBase, Type type, Object obj)
   at stub_virt_System.Configuration.Internal.IInternalConfigSystem_GetSection(IInternalConfigSystem , String , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Configuration.ConfigurationManager_GetSection(String )
   at stub_System.Configuration.ConfigurationManager_GetSection(String , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Configuration.ConfigurationManager_get_AppSettings()
   at stub_System.Configuration.ConfigurationManager_get_AppSettings(RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Windows.Forms.DpiHelper_Initialize()
   at stub_System.Windows.Forms.DpiHelper_Initialize(RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Windows.Forms.DpiHelper_InitializeDpiHelperForWinforms()
   at stub_System.Windows.Forms.DpiHelper_InitializeDpiHelperForWinforms(RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Windows.Forms.Control_.ctor(Control , Boolean )
   at stub_ctor_System.Windows.Forms.Control_.ctor(Control , Boolean , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Windows.Forms.Control_.ctor(Control )
   at stub_ctor_System.Windows.Forms.Control_.ctor(Control , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Windows.Forms.ScrollableControl_.ctor(ScrollableControl )
   at stub_ctor_System.Windows.Forms.ScrollableControl_.ctor(ScrollableControl , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Windows.Forms.ContainerControl_.ctor(ContainerControl )
   at stub_ctor_System.Windows.Forms.ContainerControl_.ctor(ContainerControl , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Windows.Forms.Form_.ctor(Form )
   at stub_ctor_System.Windows.Forms.Form_.ctor(Form , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_PosePlayground.Form1_.ctor(Form1 )
   at stub_ctor_PosePlayground.Form1_.ctor(RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_PosePlayground.FormShower_ShowTheForm(FormShower )
   at stub_virt_PosePlayground.FormShower_ShowTheForm(FormShower , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_UnitTestProject1.UnitTest1+<>c__DisplayClass0_0_<TestMethod1>b__2(<>c__DisplayClass0_0 )
--- End of inner exception stack trace ---
    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at Pose.PoseContext.Isolate(Action entryPoint, Shim[] shims)
   at UnitTestProject1.UnitTest1.TestMethod1() in C:\Users\koernej\source\repos\PosePlayground\UnitTestProject1\UnitTest1.cs:line 18
Result Message:	
Test method UnitTestProject1.UnitTest1.TestMethod1 threw exception: 
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.

If I replace the constructor of Form1 then everything works as expected.

Shim ctorShim = Shim.Replace(() => new Form1()).With(() => new Form1());

Is this expected? I am currently evaluating pose as a replacement to an existing isolation/replacement testing framework and I am trying to understand the basic use cases and how we can migrate our code if it fits our needs.

Isolated call with linq method throws exception

Hello,

I get the following exception with version 1.2.0 of pose while shimming a method which has an extension method. This worked in v1.0.1

PoseTest.Test.TestShim3 [FAIL]
  System.NullReferenceException : Object reference not set to an instance of an object.
  Stack Trace:
       at Pose.Helpers.StubHelper.GetIndexOfMatchingShim(MethodBase methodBase, Type type, Object obj)
       at stub_virt_System.Collections.Generic.ICollection`1[System.String]_get_Count(ICollection`1 , RuntimeMethodHandle , RuntimeTypeHandle )
       at dynamic_System.Linq.Enumerable_LastOrDefault(IEnumerable`1 )
       at stub_System.Linq.Enumerable_LastOrDefault(IEnumerable`1 , RuntimeMethodHandle , RuntimeTypeHandle )
       at dynamic_PoseTest.Program_LinqFn(Program )
       at stub_virt_PoseTest.Program_LinqFn(Program , RuntimeMethodHandle , RuntimeTypeHandle )
       at dynamic_PoseTest.Test+<>c__DisplayClass2_0_<TestShim3>b__1(<>c__DisplayClass2_0 )

Sample project: PoseTest.zip

code extract:

var target = new Program();
var shim = Shim.Replace(() => target.Work())
    .With((Program @this) => "Changed");
PoseContext.Isolate(() => work = target.LinqFn(), shim);

// ...
public string LinqFn()
{
    var items = new[] { Work() };
    var item = items.LastOrDefault();
    return item;
}

Isolating async calls

How on earth are you meant to isolate async calls? I've tried working round the issue with PoseContext.Isolate(async () => {}) and PoseContext.Isolate(() => Task.Run(async () => {})); but both throw compiler errors.

Any guidance/thoughts?

Question - debugging?

I wrote a Pose test, but when i put breakpoints inside the action i pass to Pose or inside the code under test, none of my breakpoints are hit. (both using Resharper runner and VS built in runner)

I am using .Net core 2.0.

Is this expected?

System.MethodAccessException in NET47

Using Pose NuGet Package 1.0.0 with XUnit 2.2.0 in .NET 4.7.
Get the following error trying to execute the test method.

Test Name: GetInformationalVersionTest_CurrentAssembly_NullAttribute
Test FullName: Bigcomp.Tests.Reflection.ReflectionExtensionsTests.GetInformationalVersionTest_CurrentAssembly_NullAttribute
Test Outcome: Failed
Test Duration: 0:00:00.303

Result StackTrace: at dynamic_Bigcomp.Tests.Reflection.ReflectionExtensionsTests+<>c_<GetInformationalVersionTest_CurrentAssembly_NullAttribute>b__2_1(<>c )
Result Message: System.MethodAccessException : Attempt by method 'DynamicClass.dynamic_Bigcomp.Tests.Reflection.ReflectionExtensionsTests+<>c_<GetInformationalVersionTest_CurrentAssembly_NullAttribute>b__2_1(<>c)' to access method 'DynamicClass.dynamic_Bigcomp.Tests.Reflection.ReflectionExtensionsTests+<>c_<GetInformationalVersionTest_CurrentAssembly_NullAttribute>b__2_1(<>c)' failed.

       [Fact]
        public void GetInformationalVersionTest_CurrentAssembly_NullAttribute()
        {
            Shim attShim = Shim.Replace(() => Attribute.GetCustomAttribute(Is.A<Assembly>(), Is.A<Type>()))
                .With<Assembly, Type, Attribute>(
                    (assy, t) =>
                    {
                        Attribute item = null;
                        return item;
                    });

            PoseContext.Isolate(
                () =>
                {
                    Assembly assy = Assembly.GetExecutingAssembly();
                    var att =
                        Attribute.GetCustomAttribute(assy, typeof(AssemblyInformationalVersionAttribute)) as
                            AssemblyInformationalVersionAttribute;
                    string result = att?.InformationalVersion;

                    Assert.Null(result);
                }, attShim);
        }

how to shim a constructor with parameters?

i see the sample :
Shim ctorShim = Shim.Replace(() => new MyClass()).With(() => new MyClass() { MyProperty = 10 });

what if the constructor has input parameters, is the following correct?

Shim ctorShim = Shim.Replace(() => new MyClass(Is.A)).With((string conn) => new MyClass(conn) { });

Question - correct syntaxes

I have 2 use cases that are not immediately clear from the description:

  1. Replacing multiple methods (both static and instance). Do i keep creating Shims for each of the methods, and pass a bunch of them to pose context?

  2. Replacing a method with params argument.

System.InvalidProgram Exception when using XmlSerializer

[TestMethod]
public void TestReplaceWebClientDownloadString()
{
    var webClientDownloadStringShim = Shim.Replace(() => Is.A<WebClient>().DownloadString(Is.A<string>()))
        .With((WebClient client, string url) => @"
<?xml version=""1.0""?>
<client>
<id>foobar</id>
<key>fizzbuzz</key>
</client>
");

    PoseContext.Isolate(() =>
    {
        using (var client = new WebClient())
        {
            var rawResponse = client.DownloadString("http://www.google.com");
            var serializer = new XmlSerializer(typeof(Foobar));
            var response = serializer.Deserialize(rawResponse.Trim().ToStream()) as Foobar;
        }
    }, webClientDownloadStringShim);
}
[Serializable, XmlRoot("client")]
public class Foobar
{
    [XmlElement(ElementName = "id")]
    public string Id { get; set; }
    [XmlElement(ElementName = "key")]
    public string Key { get; set; }
}

internal static class ParseExtensions
{
    public static Stream ToStream(this string value)
    {
        var stream = new MemoryStream();
        var writer = new StreamWriter(stream);
        writer.Write(value);
        writer.Flush();
        stream.Position = 0;
        return stream;
    }
}
Test method Pose.Tests.ShimTests.TestReplaceWebClientDownloadString threw exception: 
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidProgramException: Common Language Runtime detected an invalid program.
    at dynamic_System.Collections.Generic.ObjectEqualityComparer`1[System.RuntimeType]_GetHashCode(ObjectEqualityComparer`1 , RuntimeType )
   at stub_virt_System.Collections.Generic.IEqualityComparer`1[System.RuntimeType]_GetHashCode(IEqualityComparer`1 , RuntimeType , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Collections.Generic.Dictionary`2[System.RuntimeType,System.RuntimeType]_FindEntry(Dictionary`2 , RuntimeType )
   at stub_System.Collections.Generic.Dictionary`2[System.RuntimeType,System.RuntimeType]_FindEntry(Dictionary`2 , RuntimeType , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Collections.Generic.Dictionary`2[System.RuntimeType,System.RuntimeType]_ContainsKey(Dictionary`2 , RuntimeType )
   at stub_virt_System.Collections.Generic.Dictionary`2[System.RuntimeType,System.RuntimeType]_ContainsKey(Dictionary`2 , RuntimeType , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Reflection.PseudoCustomAttribute_GetCustomAttributes(RuntimeType , RuntimeType , Boolean , Int32& )
   at stub_System.Reflection.PseudoCustomAttribute_GetCustomAttributes(RuntimeType , RuntimeType , Boolean , Int32& , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Reflection.CustomAttribute_GetCustomAttributes(RuntimeType , RuntimeType , Boolean )
   at stub_System.Reflection.CustomAttribute_GetCustomAttributes(RuntimeType , RuntimeType , Boolean , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.RuntimeType_GetCustomAttributes(RuntimeType , Type , Boolean )
   at stub_virt_System.Reflection.MemberInfo_GetCustomAttributes(MemberInfo , Type , Boolean , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Xml.Serialization.TempAssembly_LoadGeneratedAssembly(Type , String , XmlSerializerImplementation& )
   at stub_System.Xml.Serialization.TempAssembly_LoadGeneratedAssembly(Type , String , XmlSerializerImplementation& , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Xml.Serialization.XmlSerializer_.ctor(XmlSerializer , Type , String )
   at stub_ctor_System.Xml.Serialization.XmlSerializer_.ctor(XmlSerializer , Type , String , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Xml.Serialization.XmlSerializer_.ctor(XmlSerializer , Type )
   at stub_ctor_System.Xml.Serialization.XmlSerializer_.ctor(Type , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_Pose.Tests.ShimTests+<>c_<TestReplaceWebClientDownloadString>b__7_2(<>c )
--- End of inner exception stack trace ---
    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at Pose.PoseContext.Isolate(Action entryPoint, Shim[] shims) in xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Ignore methods during isolation

I was having an issue with calling a certain static method which called other methods downstream (one of which was LINQ and EntityFramework) where using Pose.Isolate(...) it would fail.

My basic question is: is there a way I can tell it to not traverse through a certain method call recursively (short-circuit it)

I took the source and made a simple/hack way to do this that works, but wondering if there is a way without customizing the source:

    PoseContext.Ignore(@"^System\.");
    Shim shimCheckVal = Shim.Replace(() => CheckVal(Is.A<int>())).With((Func<int, int>)(x => { return 2; }));
    PoseContext.Isolate(() =>
    {
        person = Fetch(id);
    }, shimCheckVal);

In this example, I am using a regex pattern to ignore any method in the System namespace.

To make this work, I just changed the EmitILForMethod implementation and added the check at the top:

        private void EmitILForMethod(ILGenerator ilGenerator, Instruction instruction, MemberInfo memberInfo)
        {
            if (PoseContext.CheckIgnore($"{memberInfo.DeclaringType.FullName}.{memberInfo.Name}"))
            {
                ilGenerator.Emit(instruction.OpCode, memberInfo as MethodInfo);
                return;
            }
            ...

The PoseContext class just has some methods for setting up the ignore patterns and checking them:

        internal static List<Regex> Ignores { private set; get; } = new List<Regex>();

        public static void IgnoreClear()
        {
            Ignores.Clear();
        }

        public static void Ignore(string pattern)
        {
            if (string.IsNullOrEmpty(pattern))
            {
                throw new ArgumentNullException(nameof(pattern));
            }
            Ignores.Add(new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled));
        }

        public static bool CheckIgnore(string value)
        {
            foreach (var ignore in Ignores)
            {
                if (ignore.IsMatch(value))
                {
                    return true;
                }
            }
            return false;
        }

Running with opencover

We get the following exception when we run our xunit tests wrapped in an open cover:

    CustomControls.TreeListView.TreeListViewTests.BringIntoObject [FAIL]
      System.NotSupportedException : Specified method is not supported.
      Stack Trace:
           at Pose.IL.MethodRewriter.Rewrite()
           at stub_System.CannotUnloadAppDomainException_VisitedCritical(Int32 , RuntimeMethodHandle , RuntimeTypeHandle )
           at dynamic_System.CannotUnloadAppDomainException_SafeVisited(Int32 )
           at stub_System.CannotUnloadAppDomainException_SafeVisited(Int32 , RuntimeMethodHandle , RuntimeTypeHandle )
           at dynamic_CustomControls.TreeListView_OnInputRequest(TreeListView , InputRequest )
           at stub_virt_CustomControls.TreeListView_OnInputRequest(TreeListView , InputRequest , RuntimeMethodHandle , RuntimeTypeHandle )
           at dynamic_CustomControls.TreeListView.TreeListViewTests+<>c__DisplayClass0_0_<BringIntoObject>b__0(<>c__DisplayClass0_0 )

If we run the same set of tests without open cover, the desired methods appear to be shimmed just fine. I attempted to reproduce this in a minimal project to no success yet, and it also shims just fine with open cover enabled. Let me know if more effort is needed to attempt to reproduce.

TargetInvocationException: Common Language Runtime detected an invalid program thrown with DateTime.Now replacement

Code been used

    class SimpleTest
    {
        public DateTime YearBeforeNow()
        {
            return DateTime.Now.AddYears(-1);
        }
    }

   [Test]
    public void Pose_DateTimeTest()
    {
        // Arrange 
        Shim shim = Shim.Replace(() => DateTime.Now).With(() => new DateTime(2000, 1, 1));
        var test = new SimpleTest();

        PoseContext.Isolate(() =>
        {
            // Act
            var result = test.YearBeforeNow();

            // Assert
            var expected = new DateTime(1999, 1, 1);
            Assert.AreEqual(expected, result);
        }, shim);
    }

Exception Details

System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
----> System.InvalidProgramException : Common Language Runtime detected an invalid program.
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at Ssg.RiskAssessment.UnitTest.DateTimeTests.Pose()
--InvalidProgramException
at dynamic_System.DateTime_IsLeapYear(Int32 )
at stub_System.DateTime_IsLeapYear(Int32 , RuntimeMethodHandle , RuntimeTypeHandle )
at dynamic_System.DateTime_DaysInMonth(Int32 , Int32 )
at stub_System.DateTime_DaysInMonth(Int32 , Int32 , RuntimeMethodHandle , RuntimeTypeHandle )
at dynamic_System.DateTime_AddMonths(DateTime& , Int32 )
at stub_System.DateTime_AddMonths(DateTime& , Int32 , RuntimeMethodHandle , RuntimeTypeHandle )
at stub_System.DateTime_AddYears(DateTime& , Int32 , RuntimeMethodHandle , RuntimeTypeHandle )
at dynamic_Ssg.RiskAssessment.UnitTest.DateTimeTests+SimpleTest_YearBeforeNow(SimpleTest )
at stub_virt_Ssg.RiskAssessment.UnitTest.DateTimeTests+SimpleTest_YearBeforeNow(SimpleTest , RuntimeMethodHandle , RuntimeTypeHandle )
at dynamic_Ssg.RiskAssessment.UnitTest.DateTimeTests+<>c__DisplayClass2_0_b__2(<>c__DisplayClass2_0 )

Replace full classes

Hi Toni,

Let me first thank you for this wonderfull piece of work. It's just what I was looking for.

I would like to create some additonal functionality and would like your thoughts. The idea is to replace full classes instead single methods/properties.

One first idea is to make it in the following format:

Mock mock = new Mock().Replace<MyClass, ShimMyClass>();

And a full example:


    [TestClass]
    public class ShimTests1
    {
        public class MyClass
        {
            public int MyProperty { get; set; }
            public void DoSomething() => Console.WriteLine("doing someting");
            public void DoMore() => Console.WriteLine("doing more");
        }

        public class ShimMyClass
        {
            public int MyProperty
            {
                get { return 100; }
                set { }
            }

            public void DoSomething() => Console.WriteLine("doing someting else");
        }

        public void DoIt()
        {
            Mock mock = new Mock().Replace<MyClass, ShimMyClass>();

            PoseContext.Isolate(() =>
                {
                    // test it
                }, mock);
        }
    }

    public class Mock
    {
        public Mock Replace<T, TM>() => null;
        public Mock Replace<T, TM>(TM m) => null;
    }

I would like to try and create the code based on your work. But I would love it if you buy in to the idea and later merge it in your base.

Please let me know what you think.

Kind regards,
Daan

"InvalidProgramException: Common Language Runtime detected an invalid program." for .NetCore

Hello, I'm trying to use Pose to mock the property "Entitites" in the folowing class:

image

In my test, I'm doing the setup as follows:

image

But it throws the exception: System.InvalidProgramException : Common Language Runtime detected an invalid program

I've seen that other people has gone to the same problem, but usually involving DateTime.Now or something like it, and, still, could not find any solution. Do you guys are currently working on this?

Can use Pole in solution with .NET 4.6.1

Hi,
I am try to install NuGet package from Visual Studio Nuget manager but I have this error:

Could not install package 'Pose 1.2.1'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.6.1', but the package does not contain any assembly references or content files that are compatible with that framework..

It's possible to do ?

PoseContext.Isolate throws exceptions when used with net462

I discovered this after using Pose from a test project that's targetting net462 and it can be reproduced by changing Pose.Tests.csproj to use <TargetFramework>net462</TargetFramework>.

I'm not sure if this is expected or not but I thought it worth mentioning in case there's a workaround or fix.

C:\Code\tonerdo\pose\src\Pose\Pose.csproj : warning NU1701: Package 'Mono.Reflection 1.1.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETStandard,Version=v2.0'.
This package may not be fully compatible with your project. [C:\Code\tonerdo\pose\test\Pose.Tests\Pose.Tests.csproj]
Build started, please wait...
C:\Code\tonerdo\pose\src\Pose\Pose.csproj : warning NU1701: Package 'Mono.Reflection 1.1.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETStandard,Version=v2.0'.
This package may not be fully compatible with your project.
Build completed.

Test run for C:\Code\tonerdo\pose\test\Pose.Tests\bin\Debug\net462\Pose.Tests.dll(.NETFramework,Version=v4.6.2)
Microsoft (R) Test Execution Command Line Tool Version 15.3.0-preview-20170628-02
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
Failed   Pose.Tests.StubHelperTests.TestGetShimInstance
Error Message:
 Test method Pose.Tests.StubHelperTests.TestGetShimInstance threw exception:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.MethodAccessException: Attempt by method 'DynamicClass.dynamic_Pose.Tests.StubHelperTests+<>c_<T
estGetShimInstance>b__1_1(<>c)' to access method 'DynamicClass.dynamic_Pose.Tests.StubHelperTests+<>c_<TestGetShimInstance>b__1_1(<>c)' failed.
Stack Trace:
    at dynamic_Pose.Tests.StubHelperTests+<>c_<TestGetShimInstance>b__1_1(<>c )
--- End of inner exception stack trace ---
    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at System.Delegate.DynamicInvoke(Object[] args)
   at Pose.PoseContext.Isolate(Action entryPoint, Shim[] shims)
   at Pose.Tests.StubHelperTests.TestGetShimInstance() in C:\Code\tonerdo\pose\test\Pose.Tests\Helpers\StubHelperTests.cs:line 32

Failed   Pose.Tests.StubHelperTests.TestGetShimReplacementMethod
Error Message:
 Test method Pose.Tests.StubHelperTests.TestGetShimReplacementMethod threw exception:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.MethodAccessException: Attempt by method 'DynamicClass.dynamic_Pose.Tests.StubHelperTests+<>c_<T
estGetShimReplacementMethod>b__2_1(<>c)' to access method 'DynamicClass.dynamic_Pose.Tests.StubHelperTests+<>c_<TestGetShimReplacementMethod>b__2_1(<>c)' failed.
Stack Trace:
    at dynamic_Pose.Tests.StubHelperTests+<>c_<TestGetShimReplacementMethod>b__2_1(<>c )
--- End of inner exception stack trace ---
    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at System.Delegate.DynamicInvoke(Object[] args)
   at Pose.PoseContext.Isolate(Action entryPoint, Shim[] shims)
   at Pose.Tests.StubHelperTests.TestGetShimReplacementMethod() in C:\Code\tonerdo\pose\test\Pose.Tests\Helpers\StubHelperTests.cs:line 43

Failed   Pose.Tests.StubHelperTests.TestGetMatchingShimIndex
Error Message:
 Test method Pose.Tests.StubHelperTests.TestGetMatchingShimIndex threw exception:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.MethodAccessException: Attempt by method 'DynamicClass.dynamic_Pose.Tests.StubHelperTests+<>c_<T
estGetMatchingShimIndex>b__3_2(<>c)' to access method 'DynamicClass.dynamic_Pose.Tests.StubHelperTests+<>c_<TestGetMatchingShimIndex>b__3_2(<>c)' failed.
Stack Trace:
    at dynamic_Pose.Tests.StubHelperTests+<>c_<TestGetMatchingShimIndex>b__3_2(<>c )
--- End of inner exception stack trace ---
    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at System.Delegate.DynamicInvoke(Object[] args)
   at Pose.PoseContext.Isolate(Action entryPoint, Shim[] shims)
   at Pose.Tests.StubHelperTests.TestGetMatchingShimIndex() in C:\Code\tonerdo\pose\test\Pose.Tests\Helpers\StubHelperTests.cs:line 59

Failed   Pose.Tests.MethodRewriterTests.TestStaticMethodRewrite
Error Message:
 Test method Pose.Tests.MethodRewriterTests.TestStaticMethodRewrite threw exception:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.MethodAccessException: Attempt by method 'DynamicClass.stub_System.RuntimeMethodHandle_GetFuncti
onPointer(System.RuntimeMethodHandle ByRef, System.RuntimeMethodHandle, System.RuntimeTypeHandle)' to access method 'Pose.Helpers.StubHelper.GetMatchingShimIndex(System.Reflection.MethodInfo, System.Object)' fai
led.
Stack Trace:
    at stub_System.RuntimeMethodHandle_GetFunctionPointer(RuntimeMethodHandle& , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_Pose.Helpers.StubHelper_GetMethodPointer(MethodBase )
--- End of inner exception stack trace ---
    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at System.Delegate.DynamicInvoke(Object[] args)
   at Pose.Tests.MethodRewriterTests.TestStaticMethodRewrite() in C:\Code\tonerdo\pose\test\Pose.Tests\IL\MethodRewriterTests.cs:line 23

Failed   Pose.Tests.MethodRewriterTests.TestInstanceMethodRewrite
Error Message:
 Test method Pose.Tests.MethodRewriterTests.TestInstanceMethodRewrite threw exception:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.FieldAccessException: Attempt by method 'DynamicClass.dynamic_System.Collections.Generic.List`1[
System.String]_Add(System.Collections.Generic.List`1<System.String>, System.String)' to access field 'System.Collections.Generic.List`1<System.__Canon>._size' failed.
Stack Trace:
    at dynamic_System.Collections.Generic.List`1[System.String]_Add(List`1 , String )
--- End of inner exception stack trace ---
    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at System.Delegate.DynamicInvoke(Object[] args)
   at Pose.Tests.MethodRewriterTests.TestInstanceMethodRewrite() in C:\Code\tonerdo\pose\test\Pose.Tests\IL\MethodRewriterTests.cs:line 36


Total tests: 27. Passed: 22. Failed: 5. Skipped: 0.
Test Run Failed.
Test execution time: 1.1821 Seconds
.NET Command Line Tools (2.0.2)

Product Information:
 Version:            2.0.2
 Commit SHA-1 hash:  a04b4bf512

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.15063
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\2.0.2\

Microsoft .NET Core Shared Framework Host

  Version  : 2.0.0
  Build    : e8b8861ac7faf042c87a5c2f9f2d04c98b69f28d

Exception in shim delegate doesn't respect try/catch in isolated method

Here is some code where MethodA calls MethodB - if there is no exception, MethodA returns "0" otherwise it returns "1". However, if I make a shim for MethodB that calls an exception, Pose execution stops and the exception isn't caught in MethodA.

Is there a way to throw exceptions in shims that are caught in the isolated method?

        [Fact]
        public void Test()
        {
            int i = MethodA();
            Assert.Equal(0, i);

            PoseContext.Isolate(() =>
            {
                i = MethodA();
            }, Shim.Replace(() => MethodB()).With(() => { throw new Exception("test"); }));
            Assert.Equal(1, i);
        }

        public static int MethodA()
        {
            try
            {
                MethodB();
            }
            catch
            {
                return 1;
            }
            return 0;
        }

        public static void MethodB()
        {
        }

Invalid Operation Exception when Testing Code that Uses Assembly.GetExecutingAssembly

This is a .net 4.6.1 assembly using MSTest as the test runner.

I have the following code under test:

public class Mirror
{
    public void DoSomeReflection()
    {
        var asm = Assembly.GetExecutingAssembly();
        Console.WriteLine("hello world");
    }
}

With the following test:

[TestMethod]
public void TestMethod2()
{
    Shim s = Shim.Replace(() => Console.WriteLine(Is.A<string>())).With((string input) => Console.WriteLine("Yo!"));
    PoseContext.Isolate(() =>
    {
        var m = new Mirror();
        m.DoSomeReflection();
    }, s);
}

This code fails with the exception:

Test Name:	TestMethod2
Test FullName:	UnitTestProject1.UnitTest1.TestMethod2
Test Source:	C:\Users\koernej\source\repos\PosePlayground\UnitTestProject1\UnitTest1.cs : line 26
Test Outcome:	Failed
Test Duration:	0:00:00.1989306

Result StackTrace:	
at dynamic_System.Runtime.CompilerServices.JitHelpers_UnsafeCastToStackPointer(StackCrawlMark& )
   at stub_System.Runtime.CompilerServices.JitHelpers_UnsafeCastToStackPointer(StackCrawlMark& , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Runtime.CompilerServices.JitHelpers_GetStackCrawlMarkHandle(StackCrawlMark& )
   at stub_System.Runtime.CompilerServices.JitHelpers_GetStackCrawlMarkHandle(StackCrawlMark& , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Reflection.RuntimeAssembly_GetExecutingAssembly(StackCrawlMark& )
   at stub_System.Reflection.RuntimeAssembly_GetExecutingAssembly(StackCrawlMark& , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Reflection.Assembly_GetExecutingAssembly()
   at stub_System.Reflection.Assembly_GetExecutingAssembly(RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_PosePlayground.FormShower_DoSomeReflection(FormShower )
   at stub_virt_PosePlayground.FormShower_DoSomeReflection(FormShower , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_UnitTestProject1.UnitTest1+<>c_<TestMethod2>b__1_2(<>c )
--- End of inner exception stack trace ---
    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at Pose.PoseContext.Isolate(Action entryPoint, Shim[] shims)
   at UnitTestProject1.UnitTest1.TestMethod2() in C:\Users\koernej\source\repos\PosePlayground\UnitTestProject1\UnitTest1.cs:line 29
Result Message:	
Test method UnitTestProject1.UnitTest1.TestMethod2 threw exception: 
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: Operation is not valid due to the current state of the object.

I ran into this while porting existing tests and the code above is a minimal example to demonstrate the issue I was seeing.

Isolation Enums fail

The following test will not be able to pass due to the Enum.IsDefined function

shims.Add(Shim.Replace(() => DateTime.Now).With(() => new DateTime(2004, 4, 4, 11, 50, 0)));

            //act
            string actual = null;
            PoseContext.Isolate(() => {
                Enum.IsDefined(typeof(DayOfWeek), 4); // error
                actual = DateTime.Now.ToString();
            }, shims.ToArray());
Result Message:	
Test method TestMethod1 threw exception: 
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: Operation is not valid due to the current state of the object.

Result StackTrace:	
at dynamic_System.Runtime.CompilerServices.JitHelpers_UnsafeCastToStackPointer(RuntimeType& )
   at stub_System.Runtime.CompilerServices.JitHelpers_UnsafeCastToStackPointer(RuntimeType& , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Runtime.CompilerServices.JitHelpers_GetObjectHandleOnStack(RuntimeType& )
   at stub_System.Runtime.CompilerServices.JitHelpers_GetObjectHandleOnStack(RuntimeType& , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.ModuleHandle_GetModuleType(RuntimeModule )
   at stub_System.ModuleHandle_GetModuleType(RuntimeModule , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Reflection.RuntimeModule_get_RuntimeType(RuntimeModule )
   at stub_virt_System.Reflection.RuntimeModule_get_RuntimeType(RuntimeModule , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.RuntimeType+RuntimeTypeCache_.ctor(RuntimeTypeCache , RuntimeType )
   at stub_ctor_System.RuntimeType+RuntimeTypeCache_.ctor(RuntimeType , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.RuntimeType_get_Cache(RuntimeType )
   at stub_System.RuntimeType_get_Cache(RuntimeType , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.RuntimeType_get_GenericCache(RuntimeType )
   at stub_virt_System.RuntimeType_get_GenericCache(RuntimeType , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Enum_GetCachedValuesAndNames(RuntimeType , Boolean )
   at stub_System.Enum_GetCachedValuesAndNames(RuntimeType , Boolean , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Enum_InternalGetValues(RuntimeType )
   at stub_System.Enum_InternalGetValues(RuntimeType , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.RuntimeType_IsEnumDefined(RuntimeType , Object )
   at stub_virt_System.Type_IsEnumDefined(Type , Object , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Enum_IsDefined(Type , Object )
   at stub_System.Enum_IsDefined(Type , Object , RuntimeMethodHandle , RuntimeTypeHandle )
   ~~redact~~
--- End of inner exception stack trace ---
    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at Pose.PoseContext.Isolate(Action entryPoint, Shim[] shims)
~~redact~~


Can not escape isolation for foreach loop getenum,movenext

Trying to keep the isolation context through a foreach loop and having issue where I have to forward the getenumerator function but then the MoveNext function says collection was modified

The underlying type for the original collection is List() with a single object in it.

Bug? Nuget install fails due to incompatibility with .Net 4.5.2

On trying to install the nuget package for v1.2.1, I get this error output:

Attempting to gather dependency information for package 'Pose.1.2.1' with respect to project 'VitaeUnitTests', targeting '.NETFramework,Version=v4.5.2'
Gathering dependency information took 21.36 ms
Attempting to resolve dependencies for package 'Pose.1.2.1' with DependencyBehavior 'Lowest'
Resolving dependency information took 0 ms
Resolving actions to install package 'Pose.1.2.1'
Resolved actions to install package 'Pose.1.2.1'
Retrieving package 'Pose 1.2.1' from 'nuget.org'.
Install failed. Rolling back...
Package 'Pose.1.2.1' does not exist in project 'VitaeUnitTests'
Package 'Pose.1.2.1' does not exist in folder 'C:\Users\dphse\source\repos\Vitae\packages'
Executing nuget actions took 730.28 ms
Could not install package 'Pose 1.2.1'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5.2', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
Time Elapsed: 00:00:00.9346504
========== Finished ==========

Is there a version support issue, or am I mucking something up?

Extension Method Replacement

How do you use pose to replace extension methods?

I've tried replacing with Extension.MyExtension(this myClass, T value) and also myClass.MyExtension(T value) and both fail to use the replacement code and use the original.

Is this possible? I realise I am probably doing something wrong or is it because it's a generic?

GetIndexOfMatchingShim's methodBase can be called with null

It looks like there is no null check on methodBase on the GetIndexMatchingShim method in the StubHelper.cs file. This is causing an exception.

We were replacing a static method in a static class. Unforcantly I cannot post a code sample for this.

Should there be a null check here before checking if the method is static?

System.InvalidProgramException : JIT Compiler encountered an internal limitation.

The code under test is:

using System;
using System.IO;

using FluentValidation;

using NullGuard;

namespace App.Validators
{
    public sealed class OptionsValidator : AbstractValidator<Options>
    {
        private readonly Options options;

        private readonly Lazy<bool> isValid;

        public bool IsValid => this.isValid.Value;

        public OptionsValidator(Options options, [AllowNull] Action<string> onError = null)
        {
            this.options = options;

            this.isValid = new Lazy<bool>(() =>
                {
                    var result = this.Validate(this.options);

                    if (onError != null && !result.IsValid)
                    {
                        foreach (var failure in result.Errors)
                        {
                            onError(failure.ErrorMessage);
                        }
                    }

                    return result.IsValid;
                });

            this.RuleFor(x => x.In)
                .Cascade(CascadeMode.StopOnFirstFailure)
               .NotEmpty().WithMessage("error")
                   .Must(x => Directory.Exists(x)).WithMessage("error");
        }
    }
}

The Test code is:

using System.IO;

using AutoFixture.Xunit2;
using FluentAssertions;
using Pose;
using Xunit;

namespace App.Validators
{
    public sealed class OptionsValidatorTests
    {
        [Theory,
            InlineAutoData]
        public void NegativeTest0002(Options options)
        {
            var directory =
                Shim.Replace(() => Directory.Exists(Is.A<string>()))
                       .With((string x) => false);

            PoseContext.Isolate(() =>
                {
                    var error = string.Empty;

                    var validator = new OptionsValidator(options, x => { error = x; });

                    validator.IsValid.Should().BeFalse();
                    error.Should().NotBeNullOrEmpty();
                    error.Should().BeEquivalentTo("error");
                }, 
                
                directory);
        }
    }
}

Using this code, I get the following exception:

[xUnit.net 00:00:01.25]       System.InvalidProgramException : JIT Compiler encountered an internal limitation.
[xUnit.net 00:00:01.25]       Stack Trace:
[xUnit.net 00:00:01.25]            at dynamic_System.Linq.Expressions.TypedParameterExpression_.ctor(TypedParameterExpression , Type , String )
[xUnit.net 00:00:01.25]            at stub_ctor_System.Linq.Expressions.TypedParameterExpression_.ctor(Type , String , RuntimeMethodHandle , RuntimeTypeHandle )
[xUnit.net 00:00:01.25]            at stub_System.Linq.Expressions.ParameterExpression_Make(Type , String , Boolean , RuntimeMethodHandle , RuntimeTypeHandle )
[xUnit.net 00:00:01.25]            at dynamic_System.Linq.Expressions.Expression_Parameter(Type , String )
[xUnit.net 00:00:01.25]            at stub_System.Linq.Expressions.Expression_Parameter(Type , String , RuntimeMethodHandle , RuntimeTypeHandle )
[xUnit.net 00:00:01.25]            at dynamic_App.Validators.OptionsValidator_.ctor(OptionsValidator , Options , Action`1 )
[xUnit.net 00:00:01.25]            at stub_ctor_App.Validators.OptionsValidator_.ctor(Options , Action`1 , RuntimeMethodHandle , RuntimeTypeHandle )
[xUnit.net 00:00:01.25]            at dynamic_App.Validators.OptionsValidatorTests+<>c__DisplayClass1_0_<NegativeTest0002>b__2(<>c__DisplayClass1_0 )

Incompatible with Universal Windows Platform (UWP)

Any way to resolve this? Is there a way to also support .NET Core?

Package Pose 1.2.0 is not compatible with uap10.0.10240 (UAP,Version=v10.0.10240) / win10-x86-aot. Package Pose 1.2.0 supports: netstandard2.0 (.NETStandard,Version=v2.0)

Invalid Program When Testing Code that Gets System Temporary Path

This is a .net 4.6.1 assembly using MSTest as the test runner.

I have the following code under test:

public class TempDirectory
{
    public void CreateATempDirectory()
    {
        string tempPath = System.IO.Path.GetTempPath();
        Console.WriteLine(tempPath);
    }
}

With the following test code:

[TestMethod]
public void TestMethod3()
{
    Shim s = Shim.Replace(() => Console.WriteLine(Is.A<string>())).With((string input) => Console.WriteLine("Yo!"));
    PoseContext.Isolate(() =>
    {
        var t = new TempDirectory();
        t.CreateATempDirectory();
    }, s);
}

This results in an exception:

Test Name:	TestMethod3
Test FullName:	UnitTestProject1.UnitTest1.TestMethod3
Test Source:	C:\Users\koernej\source\repos\PosePlayground\UnitTestProject1\UnitTest1.cs : line 37
Test Outcome:	Failed
Test Duration:	0:00:00.1940169

Result StackTrace:	
at dynamic_System.IO.Path_LegacyNormalizePath(String , Boolean , Int32 , Boolean )
   at stub_System.IO.Path_LegacyNormalizePath(String , Boolean , Int32 , Boolean , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.IO.Path_NormalizePath(String , Boolean , Int32 , Boolean )
   at stub_System.IO.Path_NormalizePath(String , Boolean , Int32 , Boolean , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.IO.Path_NormalizePath(String , Boolean , Int32 )
   at stub_System.IO.Path_NormalizePath(String , Boolean , Int32 , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.IO.Path_NormalizePath(String , Boolean )
   at stub_System.IO.Path_NormalizePath(String , Boolean , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.IO.Path_GetFullPathInternal(String )
   at stub_System.IO.Path_GetFullPathInternal(String , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.IO.Path_GetTempPath()
   at stub_System.IO.Path_GetTempPath(RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_PosePlayground.TempDirectory_CreateATempDirectory(TempDirectory )
   at stub_virt_PosePlayground.TempDirectory_CreateATempDirectory(TempDirectory , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_UnitTestProject1.UnitTest1+<>c_<TestMethod3>b__2_2(<>c )
--- End of inner exception stack trace ---
    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at Pose.PoseContext.Isolate(Action entryPoint, Shim[] shims)
   at UnitTestProject1.UnitTest1.TestMethod3() in C:\Users\koernej\source\repos\PosePlayground\UnitTestProject1\UnitTest1.cs:line 40
Result Message:	
Test method UnitTestProject1.UnitTest1.TestMethod3 threw exception: 
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidProgramException: Common Language Runtime detected an invalid program.

Dose not work net core 2.1

Shim classShim = Shim.Replace(() => Console.WriteLine(Is.A<string>())).With(
                    delegate (string s) {
                        Console.WriteLine("here");
                    });

Console.WriteLine("test");

Pose.Exceptions.InvalidShimSignatureException: 'Parameters count do not match“

` public class ShimTest
{
public void runTest()
{
TestModel testObj = new TestModel();
Shim boShim = Shim.Replace(() => testObj.testMethod(Is.A"<"string">"())).With((TestModel obj) => "test"); // line here throw exceptions as titled, anything wrong?
PoseContext.Isolate(() => { testObj.testMethod(""); }, boShim);
}
}

public class TestModel
{
    public string testMethod(string pa)
    {
        return "hello,world";
    }
}`

Shimming constructor

I'm having an issue shimming an empty constructor class that has the dependency in its base class. Trying to add a test to legacy code.

public class BaseClass
{
protected Dependency myDependency
  public BaseClass()
  {
     myDependency = new Dependency();
  }
}

I have another class that inherits my base class and calls the base class constructor inside its constructor

public class MyClass : BaseClass
{
   public MyClass() :base()
   {
   }

  public int addInts(int a, int b)
  {
    return a+b;
  }
}

Im using xunit for my testing framework, I'm trying to write a simple test for addInts
How I currently understand it is that to remove the dependency in the base class I need to shim the constructor in MyClass since its calling the base class constructor. I want to shim this constructor as an empty constructor and not call the base class constructor.

public class UnitTest1
{
  [Fact]
  public void Add1and3ToEqual4()
  {
     Shim ctorShim = Shim.Replace(() => new MyClass()).With(() => new MyClass() { });
     int myNumber = 0;

            PoseContext.Isolate(() =>
            {
                var myService = new MyClass();
                myNumber = myService.AddNumbers(1, 3);

            }, ctorShim );

            Assert.Equal(4, myNumber)
  }
}

I've also tried variations on this by shimming the base class constructor and passing that into the isolate as well.
Shim ctorConnection = Shim.Replace(() => new BaseClass()).With(() => new BaseClass() { });

When I run my test I get an error in the base class where the dependency is being set.
error being returned

Result Message: System.IO.FileNotFoundException : Could not load file or assembly 'System.Data.SqlClient, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.

The Dependency I'm trying to get rid of is a SqlClient Dependency.

Thank you in advance for any help. This is an awesome project.

Does not work if you pass byte array

const string someFile = "R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==";
byte[] bytes = Convert.FromBase64String(someFile);
PoseContext.Isolate(() =>
{
var x = instance.Class(bytes );
}, shim);

Can you shim a method with optional parameters?

I have a method in another assembly that looks like this (VB.NET):

    Public Class Item Parent
        Public Function GetItems(
            ByVal Optional a As Integer = 0,
            ByVal Optional b As Integer = 0,
            ByVal Optional c As Integer = 0,
            ByVal Optional d As Integer = 0) As List(Of Item)
    ...

I'm trying to figure out how to shim this. This give me the error An expression tree may not contain a call or invocation that uses optional arguments.

    var mockItems = new List<Item>();
    Shim.Replace(() => Is.A<ItemParent>().GetItems())
        .With(delegate (ItemParent@this) { return mockItems; });

This give me Pose.Exceptions.InvalidShimSignatureException: Mismatched instance types

    var mockItems = new List<Item>();
    Shim.Replace(() => Is.A<ItemParent>().GetItems(Is.A<int>(), Is.A<int>(), Is.A<int>(), Is.A<int>()))
        .With(delegate () { return mockItems; });

And these variations give me Pose.Exceptions.InvalidShimSignatureException: Parameters count do not match

    var mockItems = new List<Item>();
    Shim.Replace(() => Is.A<ItemParent>().GetItems(Is.A<int>(), Is.A<int>(), Is.A<int>(), Is.A<int>()))
        .With(delegate (ItemParent@this) { return mockItems; });

    var mockItems = new List<Item>();
    Shim.Replace(() => Is.A<ItemParent>().GetItems(Is.A<int>(), Is.A<int>(), Is.A<int>(), Is.A<int>()))
        .With(delegate (ItemParent@this, int a, int b, int c, int d) { return mockItems; });

What is the proper syntax?

Question - property setters?

With MS Fakes we can shim property setters, which allows us to then assert when certain properties are set to certain values.

Is it possible to do this with Pose?

Can't use Console.WriteLine in PoseContext

I'm not sure if this is related to #14 and #15, or if it's maybe just user error.

I was taking Pose for a quick test drive and created a shim for DateTime.Now and then tried to output it, but the app threw an exception. Then I took out any use of the shim from within the isolation, and I'm still getting an error. IOW, it seems that just calling Console.WriteLine() from within an isolation context throws an exception.

Sample code:

static void Main(string[] args)
{
    var shim = Shim.Replace(() => DateTime.Now).With(() => DateTime.Parse("2000-01-01"));

    PoseContext.Isolate(() =>
    {
        // originally had Console.WriteLine(DateTime.Now)
        Console.WriteLine("foo");
    }, shim);

    Console.ReadLine();
}

Exception:

Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidProgramException: JIT Compiler encountered an internal limitation.
   at dynamic_System.Runtime.ConstrainedExecution.CriticalFinalizerObject_.ctor(CriticalFinalizerObject )
   at stub_ctor_System.Runtime.ConstrainedExecution.CriticalFinalizerObject_.ctor(CriticalFinalizerObject , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Runtime.InteropServices.SafeHandle_.ctor(SafeHandle , IntPtr , Boolean )
   at stub_ctor_System.Runtime.InteropServices.SafeHandle_.ctor(SafeHandle , IntPtr , Boolean , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid_.ctor(SafeHandleZeroOrMinusOneIsInvalid , Boolean )
   at stub_ctor_Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid_.ctor(SafeHandleZeroOrMinusOneIsInvalid , Boolean , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_Microsoft.Win32.SafeHandles.SafeFileHandle_.ctor(SafeFileHandle , IntPtr , Boolean )
   at stub_ctor_Microsoft.Win32.SafeHandles.SafeFileHandle_.ctor(IntPtr , Boolean , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Console_GetStandardFile(Int32 , FileAccess , Int32 )
   at stub_System.Console_GetStandardFile(Int32 , FileAccess , Int32 , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Console_OpenStandardOutput(Int32 )
   at stub_System.Console_OpenStandardOutput(Int32 , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Console_InitializeStdOutError(Boolean )
   at stub_System.Console_InitializeStdOutError(Boolean , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Console_get_Out()
   at stub_System.Console_get_Out(RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_System.Console_WriteLine(String )
   at stub_System.Console_WriteLine(String , RuntimeMethodHandle , RuntimeTypeHandle )
   at dynamic_PoseTest.Program+<>c_<Main>b__0_2(<>c )
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at Pose.PoseContext.Isolate(Action entryPoint, Shim[] shims)
   at PoseTest.Program.Main(String[] args) in C:\Users\Aaron\Documents\Projects\Visual Studio\Pose\Pose\Program.cs:line 16

DateTime.Now returning incorrect value

        var consoleShim = Shim.Replace(() => Console.WriteLine(Pose.Is.A<string>())).With(
            delegate (string s) { Console.WriteLine("Hijacked: {0}", s); });
        var shimDate = new DateTime(2014, 4, 4);
        Console.WriteLine(shimDate);
        var dateTimeShim = Shim.Replace(() => DateTime.Now).With(() => shimDate);
        PoseContext.Isolate(() =>
        {
            Console.WriteLine("Hello World!");
            var dt = DateTime.Now;
            Console.WriteLine(dt);
            Console.WriteLine(DateTime.Now);
        }, consoleShim, dateTimeShim);

Test is returning: 4/18/D1935668524 3:40:45 AM

A strongly-named assembly is required

Trying to use Pose from other strongly named assemblies and getting the following exception:

System.IO.FileLoadException : Could not load file or assembly 'Pose, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. A strongly-named assembly is required. (Exception from HRESULT: 0x80131044)

Any chance of getting this assembly strongly-named?

Is this project dead?

Any further updates planned to this project, in particular to get it working properly on .NET Core? Or are there any forks out there with the necessary fixes?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.