AL/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 settings.json
    $EnvironmentJson = ConvertFrom-Json (Get-Content (Join-Path $SourcePath 'settings.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 ($Dependencies -eq '') {
            $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 ($null -eq $Dependencies ) {
                $AppJson | Add-Member -Name 'dependencies' -value $TestappsJsonContent -MemberType NoteProperty
            } 
            else {
                $compiler = Get-AppKeyValue -SourcePath $TestPath -KeyName 'runtime'
                [System.Array]$Dependencies = $Dependencies
                foreach ($TestDependency in $TestappsJsonContent) {
                    $SkipDependency = $false
                    foreach ($Dependency in $Dependencies) {
                        if (!$SkipDependency) {
                            if ($compiler -ge '4.3') {
                                if ($Dependency.id -eq $TestDependency.appId) {
                                    $SkipDependency = $true
                                }
                            }
                            else {
                                if ($Dependency.appId -eq $TestDependency.appId) {
                                    $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