Test pipelined content

26 views
Skip to first unread message

cra...@gmail.com

unread,
Jan 7, 2015, 4:47:39 PM1/7/15
to pes...@googlegroups.com
How do I test content that I piped into a function?  It seems that the test is evaluated on each process block, rather than the end.

For example:

function Merge-Tokens() {

    [CmdletBinding()]
   
    param (
        [Parameter(Mandatory=$True, ValueFromPipeline=$true, Position=0)]
        [AllowEmptyString()]
        [String] $template,
        [Parameter(Mandatory=$true, Position=1)]
        [HashTable] $tokens
    )

    process {

            #
            # evaluate each line; look for tokens (e.g. __TOKEN__) in line
            # matching tokens (in groups) values are passed to the block(anonymous method)
            #
            #
            return [regex]::Replace( $template, '__(?<tokenName>\w+)__',
            {
                # __TOKEN__
                param($match)
                # Write-Host "match: $match"

                $tokenName = $match.Groups['tokenName'].Value
               
                # return $tokens[$tokenName]
                if ($tokens[$tokenName]) {return $tokens[$tokenName]}
                else {return $match}
            })

    }

}


Describe "Merge-Tokens" {

    $tokens = @{"author"="John Doe"; "title"="lorem ipsum"}

    $template = New-Item "TestDrive:\template.txt" -Type File
    Set-Content $template -value "Author: __AUTHOR__`r`nTitle: __TITLE__"

    It "processes file content in pipeline " {
        Get-Content $template | Merge-Tokens -tokens $tokens | Should BeExactly "Author: John Doe`r`nTitle: lorem ipsum"
    }

}


Fails:

 [-] processes file content in pipeline  178ms
   Expected string length 36 but was 16. Strings differ at index 16.
   Expected: {Author: John Doe\r\nTitle: lorem ipsum}
   But was:  {Author: John Doe}
   ---------------------------^


Perhaps I need to compare the pipeline output?

Dave Wyatt

unread,
Jan 19, 2015, 8:07:01 AM1/19/15
to pes...@googlegroups.com
Your current code is still outputting an array of strings (technically piping them out); there's nothing in the code that is joining that array into a single string separated by newlines.  Depending on your needs, you could do that either in the End block of your function (so instead of outputting anything to the pipeline in your process block, you just accumulate the values in an array or StringBuilder or whatever), or you can do it out in the test code before piping to Should BeExactly.  Here's an example of the latter:

(Get-Content $template | Merge-Tokens -tokens $tokens) -join "`r`n" | Should BeExactly "Author: John Doe`r`nTitle: lorem ipsum"

Reply all
Reply to author
Forward
0 new messages