Build/Add-TestAppsToAppJson.ps1

function Add-TestAppsToAppJson{
    Param(
        #Path to determine the environment or app .json file location
        [Parameter(Mandatory=$false)]
        [String]
        $SourcePath = (Get-Location)
    )

    #Get test apps property from environment.json
    $EnvironmentJson = ConvertFrom-Json (Get-Content (Join-Path $SourcePath 'environment.json') -Raw)
    $TestappsJsonContent =  $EnvironmentJson.PSObject.Properties.Item('testapps').Value

    if ($TestappsJsonContent.Length -gt 0){
        #app has no current dependencies, add the test test dependencies directly
        $AppJsonContent = Get-Content (Join-Path $SourcePath 'app.json') -Raw
        $AppJson = ConvertFrom-Json $AppJsonContent
        $Dependencies = Get-AppKeyValue -SourcePath $SourcePath -KeyName 'dependencies'
        if ($null -eq $Dependencies){
            $AppJson | Add-Member -Name 'dependencies' -value $TestappsJsonContent -MemberType NoteProperty
        }
        else{
            #Check the test app dependency isnt already in the app.json
            $AppJson.PSObject.Properties.Remove('dependencies')
            
            if ('' -eq $Dependencies ){
                $AppJson | Add-Member -Name 'dependencies' -value $TestappsJsonContent -MemberType NoteProperty
            } 
            else{
                [System.Array]$Dependencies = $Dependencies
                foreach ($TestDependency in $TestappsJsonContent){
                    $SkipDependency = $false
                    foreach ($Dependency in $Dependencies){
                        if (!$SkipDependency){
                            if ($null -ne $Dependency.appId) {
                                if ($Dependency.appId -eq $TestDependency.appId){
                                    $SkipDependency = $true
                                }
                            }
                            if ($null -ne $Dependency.id) {
                                if ($Dependency.id -eq $TestDependency.id){
                                    $SkipDependency = $true
                                }
                            }
                        }
                    }   
                    if (!$SkipDependency){
                        $Dependencies += $TestDependency
                    }
                }
                $AppJson | Add-Member -Name 'dependencies' -value $Dependencies -MemberType NoteProperty
            }
        }
        Set-Content -Path (Join-Path $SourcePath 'app.json') -Value (ConvertTo-Json $AppJson)
    }
}

Export-ModuleMember -Function Add-TestAppsToAppJson