Repository navigation
Description
I have been experimenting with a (hopefully) more robust mechanism for mocking commands than Pester currently uses. Here is a proof of concept. In general, the mechanism relies on invoking scriptblocks with the SessionState where the mock needs to exist. This is trivial for a SessionState associated with a module: Invoking & $module $scriptblock achieves the desired result. I haven't, however, found a straightforward way of invoking a scriptblock defined inside a module with the "global" SessionState.
Consider this working code
Get-Module LibraryModule,m | Remove-Module
New-Module LibraryModule {
$sb = {
Write-Host 'control flow: 1'
Write-Host $v
'output'
Write-Host 'control flow: 3'
}
function DownStream {
param([Parameter(ValueFromPipeline)]$i)
process {
Write-Host 'control flow: 2'
}
}
function InvokeWithModuleSessionState {
param([psmoduleinfo]$mi)
& $mi $sb | DownStream
}
function InvokeWithGlobalSessionState {
[CmdletBinding()]
param($ss)
<#
This doesn't execute in the "global" SessionState.
(ie. it has no access to 'g.v')
#>
# & $ss.InvokeCommand.NewScriptBlock($sb) | DownStream
<#
Each of these neither
1. has the correct control flow (ie. they don't yield to DownStream), nor
2. executes in the global SessionState (ie. they have no access to 'g.v').
#>
# $ss.InvokeCommand.InvokeScript($sb) | DownStream
# $ss.InvokeCommand.InvokeScript($ss,$sb,$null) | DownStream
# $ss.InvokeCommand.InvokeScript($true,$sb,$null,$null) | DownStream
# $ss.InvokeCommand.InvokeScript($false,$sb,$null,$null) | DownStream
# $ss.InvokeCommand.InvokeScript($sb,$true,'Output',$null,$null) | DownStream
# $ss.InvokeCommand.InvokeScript($sb,$false,'Output',$null,$null) | DownStream
<#
This works, but it's in bucket 4.
#>
$copyOfSb = [scriptblock]::Create($sb)
$flags = [System.Reflection.BindingFlags]'Instance,NonPublic'
$internalSessionState = [System.Management.Automation.SessionState].GetProperty('Internal', $flags).GetValue($ss, $null)
$property = [ScriptBlock].GetProperty('SessionStateInternal', $flags)
$property.SetValue($copyOfSb, $internalSessionState, $null) | Out-Null
& $copyOfSb | DownStream
}
} | Import-Module
New-Module m {
$v = 'm.v'
} | Import-Module
& {
$v = 'g.v'
Write-Host '=== Module ==='
InvokeWithModuleSessionState -sb $sb -mi (Get-Module m)
Write-Host '=== Global ==='
InvokeWithGlobalSessionState -ss $ExecutionContext.SessionState
}which outputs
=== Module ===
control flow: 1
m.v
control flow: 2
control flow: 3
=== Global ===
control flow: 1
g.v
control flow: 2
control flow: 3
This implementation of InvokeWithGlobalSessionState relies on private reflection to bind a scriptblock to the SessionState. This is clearly vulnerable to bucket 4 changes which, per the breaking changes contract, "don't require up-front approval." I'd like to avoid such sudden breakage, if there is a better way.
- Is there a supported way of binding an unbound scriptblock to the "global" session state?
- Is there a supported way of invoking an unbound scriptblock in the "global" session state? In other words, is there a supported analog to
& $module $scriptblockthat works for the "global" session state as opposed to a module session state? - Is there some other way of creating a scriptblock from a module, but invoking it in the "global" session state?
Activity
lzybkr commentedon Feb 12, 2018
I believe you'll have to rely on a conversion to string, but something like the following might work:
The idea is to recreate the script block in global scope.
Basically, you want to get this line of code executed with the correct session state.
There are other places where
SessionStateis assigned, but this is typically the first, and once set, the session state can't change.[-]Is there a supported way to binding an unbound scriptblock to the "global" SessionState?[/-][+]Is there a supported way of binding an unbound scriptblock to the "global" SessionState?[/+]SeeminglyScience commentedon Feb 12, 2018
If you already have the session state, you can create a dummy module to store it. The
SessionStateproperty is writable (mistake, maybe?)That said, I assume the actual implementation of this will be running within Pester's
SessionState. If that's the case, actually obtaining the globalSessionStateis the harder part. I haven't been able to find a way to get that without reflection.alx9r commentedon Feb 13, 2018
I see. It's not obvious to me how to do that from a module.
outputs
False.In other words, despite the
global:prefix,GetGlobalSessionState's scriptblock is bound to the module.Is there some other way to reliably get a reference to a scriptblock associated with the global session state?
This seems promising, and
$PSCmdlet.SessionStateseems to contain the caller's session state. The following code seems to prove the concept:That outputs
It seems like this technique would not be vulnerable to any of the acceptable breaking changes in the breaking changes contract. Jason Shirk (@lzybkr) Can you comment on whether this behavior is likely to be broken in the future?
SeeminglyScience commentedon Feb 13, 2018
alx9r
$PSCmdletwon't reliably get you the global session state because you can't tell what scope it's coming from. You can't really even be sure that it'll actually be there, if the module is called from a command prompt or a script withoutCmdletBindingthat won't work.You could get a little closer by iterating the call stack, something like
But that still depends on some part of the call stack outside of a module declaring
CmdletBindinglzybkr commentedon Feb 13, 2018
alx9r - I can see why that example doesn't work using
new-module, but it should work if you defined the function in module when you use theScriptsToProcessentry in the module manifest.I agree with Patrick Meinecke (@SeeminglyScience) that a writable
SessionStateproperty inModuleInfoseems unintentional. Changes to apis are generally conservative, so maybe you'd be safe using it, but I'd continue looking for alternatives so you have options to consider, or even fall back on if the api was removed.alx9r commentedon Feb 13, 2018
I agree. I've been experimenting with different approaches since my OP and I think the question I should have been asking is this: Is there a supported way of invoking a scriptblock with the caller's SessionState? It seems like
$PSCmdlet.SessionStatereliably gets the caller's SessionState.alx9r commentedon Feb 13, 2018
I thought so too. And it does work, but that approach is brittle to nested modules. If any module loads the module with
ScriptToProcessfirst, thenBindToGlobalSessionStateactually binds to that module's SessionState.I think I'm out of ideas for now. Do you have any other ideas I should explore? FWIW, I think the question I probably should have been asking is this: Is there a supported way of invoking a scriptblock with the caller's SessionState?
SeeminglyScience commentedon Feb 13, 2018
alx9r not reliably, because you can't guarantee
CmdletBindingwas declared in the caller. You could make that a requirement to mock, but if it wasn't declared and insteadPSCmdletcame from a differentSessionStatethan the caller it would be very difficult to debug unless you are intimately familiar with the engine.Your best bet at reliability (not taking support into account) is to get
InvocationInfofrom the call stack and get theSessionStateInternalof the caller.But even then there are some instances where the
ScriptBlockproperty isnull(like class methods and script blocks invoked directly withInvoke*api's)alx9r commentedon Feb 13, 2018
FWIW I have settled on implementing a function called
BindToCallerSessionState, for now. The function does the following:[psmoduleinfo]SessionStateInternalproperty using private reflectionBindToImporterSessionStatewhich is implemented usingScriptToProcessThe problem with strategies (i) and (ii) is that they might be broken by changes to PowerShell. The problem with (iii) is that it doesn't do the right thing -- binding to the importer session state is not the same as binding to the caller session state. This seems to be a matter of choosing the least evil.
I have also implemented a number of automated tests around each of the strategies. If there is a breaking change, it should be detected early either by the warnings seen by users or by the automated tests for the mock library failing.
It does seem a bit odd that PowerShell has a first class way of invoking a scriptblock in a given module (ie.
& $module $scriptblock) but no supported way of invoking a scriptblock in either the "global" session state or the caller's session state.alx9r commentedon Feb 13, 2018
This code
seems to demonstrate that declaring CmdletBinding in the caller is not necessary. Do you have an example demonstrating your concern?
SeeminglyScience commentedon Feb 13, 2018
Nope! I'm wrong. I could have sworn
$PSCmdlet.SessionStategave the current session state, but that isn't the case. Learn something new every day :)alx9r commentedon Jun 18, 2019
I think there is another alternative. As far as I can tell, when a PSCmdlet implemented in C# is invoked its SessionState property is the caller's SessionState. In other words,
Jason Shirk (@lzybkr) Can you confirm whether this is true? I'm also wondering whether this behavior is by design or by chance. In other words, can I rely on the correspondence between call site and .SessionState as described in the above bullets?
Below is (what I think is) a working example. It looks like utilizing this technique requires that any command to whose call site you need to bind a scriptblock be implemented as a binary command. I haven't succeeded at replicating this technique for implementing commands as scriptblocks.
vexx32 commentedon Jun 18, 2019
Heh, can't believe I never found this issue.
I've wrestled with this extensively myself in PSKoans, so that I could invoke the koan files in a global session rather than accidentally invoking them inside the module itself.
My own solution was basically to spin up a new runspace and work with that.
If there is a simpler way to bind a scriptblock to the global session state I'd very much appreciate it.
lzybkr commentedon Jun 18, 2019
I'm not going to answer your question directly because it's been a long time since I've looked at this area and your observations are going to be more correct than my possibly faulty memory.
IIRC,
SessionStatecan be set upon first access (or explicitly) and I didn't like that as it wasn't explicit enough for my liking.Because of this, I think it's possible it gets set by chance somewhere now, but I think Bruce Payette (@BrucePay) was careful enough when originally implementing modules that everything is (or at least once was) by design.
alx9r commentedon Jun 18, 2019
Jason Shirk (@lzybkr) Ah. I see. Got it. Thanks for the background. I think I've got enough tests around the behavior I need that I'll probably detect an inadvertent change early enough.
alx9r commentedon Jun 18, 2019
Rain Sallow (/u/ta11ow) (@vexx32) The best I've been able to come up with is the methods for binding to the caller's session state (which may or may not be the global session state) discussed above. Binding to the global session state is a bridge further than I have explored.
microsoft-github-policy-service commentedon Nov 16, 2023
This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.
microsoft-github-policy-service commentedon Nov 16, 2023
This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.
microsoft-github-policy-service commentedon Nov 16, 2023
This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.
microsoft-github-policy-service commentedon Nov 23, 2023
This issue has been marked as "No Activity" as there has been no activity for 6 months. It has been closed for housekeeping purposes.