pester / Pester

Pester is the ubiquitous test and mock framework for PowerShell.
https://pester.dev/
Other
3.08k stars 470 forks source link

Refer to a script in a parent directory #2416

Closed erossini closed 8 months ago

erossini commented 8 months ago

Checklist

Summary of the feature request

To organize better the scripts and the relative tests, I created in my pipeline a simple structure: the scripts folder has all the scripts; then the tests folder contains the folder for each script and the necessary files.

image

I have an issue in find the script from the test in the setup. For example, the code is

Describe "Setup" {
    BeforeAll {
        . $PSCommandPath.Replace('.Tests.ps1', '.ps1') -flowJsonPath $flowJsonPath
    }
}

Also, I tried to write the setup like this

Describe "Setup" {
    BeforeAll {
        $scriptName = [System.IO.Path]::GetFileName($PSCommandPath.Replace('.Tests.ps1', '.ps1'))
        $scriptPath = Split-Path -Parent $PSCommandPath.Replace('.Tests.ps1', '.ps1')
        $scriptPath = $scriptPath -replace "Tests\\JsonFiltering", ""
        $script = [System.IO.Path]::Combine($scriptPath, $scriptName)
        . $script -flowJsonPath $flowJsonPath -flowTycheJsonPath $flowTycheJsonPath -outputFilePath $outputFilePath
    }
}

but I still get an error

CommandNotFoundException: The term 'C:\Users\A084\Documents\Projects\MyProject\pipelines\Scripts\Tests\JsonFiltering\JsonFilte ring.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Is there a way to use a script in the parent directory?

How should it work?

No response

johlju commented 8 months ago

The variable $PSScriptRoot. So . $PSScriptRoot/../JsonFiltering.ps1.

erossini commented 8 months ago

Thank you for answer. If it can be useful, here the code

$scriptRoot = "$PSScriptRoot/../../"
$filename = (Split-Path $PSCommandPath -Leaf).Replace('.Tests.ps1', '.ps1')
$scriptToTest = [System.IO.Path]::Combine($scriptRoot, $filename)