Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Restore original function on Exit-MockScope #286

Closed
MatthieuMEZIL opened this issue Feb 21, 2015 · 3 comments
Closed

Restore original function on Exit-MockScope #286

MatthieuMEZIL opened this issue Feb 21, 2015 · 3 comments

Comments

@MatthieuMEZIL
Copy link

Hi

I have this function in a ps1 file:
function Test()
{
mkdir "C:\Temp\Foo"
}

Then I use this test:
Describe "Foo" {
It "bar" {
Mock mkdir
Assert-MockCalled mkdir 0 -ParameterFilter { }
Test
}
}

I can run it once but if I want to run it again on the same PowerShell session, I have this error: "Could not find Command mkdir"
Is there any workaround to avoid it?

Thanks

Matthieu

@dlwyatt
Copy link
Member

dlwyatt commented Feb 21, 2015

Hmm, interesting. This line is the culprit:

$ExecutionContext.InvokeProvider.Item.Rename("Function:\PesterIsMocking_$CommandName", "script:$CommandName", $true)

That is supposed to be restoring the original function when the mock is removed, but it's got that hard-coded "script:" scope. That's appropriate most of the time, but in this case, mkdir is a function that originally exists in the Global scope, not Script. As soon as the test script finishes executing, it's gone.

As a temporary workaround, you could just mock New-Item instead (since mkdir is just a simple wrapper around New-Item with the -Type parameter set to "Directory".) I'll see if there's a simple way for us to fix this in the more general case, though there's probably not a huge need to mock global functions.

@MatthieuMEZIL
Copy link
Author

Ok. Thanks. I will try with this way.

@MatthieuMEZIL
Copy link
Author

Just tested. Thanks. It works fine with this workaround

dlwyatt added a commit to dlwyatt/Pester that referenced this issue Feb 24, 2015
This works, but there might be some weirdness that can still happen if you mock a global function in conjunction with -ModuleName or InModuleScope.  (The global function gets renamed for the duration of the mock, but the mock is only available from that single module.  You can't mock the same global function from two different modules at once.)

Not sure if it's worth worrying about that edge case, since this "mocking global functions" scenario  is already pretty rare to begin with.
dlwyatt added a commit that referenced this issue Apr 28, 2015
@dlwyatt dlwyatt closed this as completed Apr 28, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants