Search code examples
powershellpipeline

How would I test that a PowerShell function properly streams input from the pipeline?


I know how to write a function that streams input from the pipeline. I can reasonably tell by reading the source for a function if it will perform properly. However, is there any method for actually testing for the correct behavior?

I accept any definition of "testing"... be that some manual test that I can run or something more automated.

If you need an example, let's say I have a function that splits text into words.

PS> Get-Content ./warandpeace.txt | Split-Text

How would I check that it streams input from the pipeline and begins splitting immediately?


Solution

  • Ah, I've got a very simple solution. The concept is to insert your own step into the pipeline with obvious side-effects before the function that you're testing. For example...

    PS> 1..10 | %{ Write-Host $_; $_ } | function-under-test
    

    If your function-under-test is "bad", you will see all of the output from 1..10 twice, like this

    1
    2
    3
    1
    2
    3
    

    If the function-under-test is processing items lazily from the pipeline, you'll see the output interleaved.

    1
    1
    2
    2
    3
    3