Public/Test-Package.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Author: Miodrag Milic <miodrag.milic@gmail.com>
# Last Change: 16-Sep-2016.

<#
.SYNOPSIS
    Test Chocolatey package
 
.DESCRIPTION
    The function tries to force install and then remove the Chocolatey package.
 
.LINK
    https://github.com/chocolatey/choco/wiki/CreatePackages#testing-your-package
#>

function Test-Package {
    param(
        # If file, path to the .nupkg or .nuspec file for the package.
        # If directory, latest .nupkg or .nuspec file wil be looked in it.
        # If ommited current directory will be used.
        $Nu,

        # Test chocolateyInstall.ps1 only.
        [switch] $Install,

        # Test chocolateyUninstall.ps1 only.
        [switch] $Uninstall
    )
    if (!$Install -and !$Uninstall) { $Install = $Uninstall = $true }

    if (!$Nu) { $dir = gi $pwd }
    else {
        if (!(Test-Path $Nu)) { throw "Path not found: $Nu" }
        $Nu = gi $Nu
        $dir = if ($Nu.PSIsContainer) { $Nu; $Nu = $null } else { $Nu.Directory }
    }

    if (!$Nu) {
        $Nu = gi $dir/*.nupkg | sort -Property CreationTime -Descending | select -First 1
        if (!$Nu) { $Nu = gi $dir/*.nuspec }
        if (!$Nu) { throw "Can't find nupkg or nuspec file in the directory" }
    }

    if ($Nu.Extension -eq '.nuspec') {
        Write-Host "Nuspec file given, running choco pack"
        choco pack -r $Nu.FullName --OutputDirectory $Nu.DirectoryName | Write-Host
        if ($LASTEXITCODE -ne 0) { throw "choco pack failed with $LastExitCode"}
        $Nu = gi "$($Nu.DirectoryName)\*.nupkg" | sort -Property CreationTime -Descending | select -First 1
    } elseif ($Nu.Extension -ne '.nupkg') { throw "File is not nupkg or nuspec file" }

    $package_name    = $Nu.Name -replace '(\.\d+)+\.nupkg$'
    $package_version = ($Nu.BaseName -replace $package_name).Substring(1)

    Write-Host "`nPackage info"
    Write-Host " Path:".PadRight(15)     $Nu
    Write-Host " Name:".PadRight(15)     $package_name
    Write-Host " Version:".PadRight(15)  $package_version

    if ($Install) {
        Write-Host "`nTesting package install"
        choco install -r $package_name --version $package_version --source "'$($Nu.DirectoryName);https://chocolatey.org/api/v2/'" --force | Write-Host
        if ($LASTEXITCODE -ne 0) { throw "choco install failed with $LastExitCode"}
    }

    if ($Uninsstall) {
        Write-Host "`nTesting package uninstall"
        choco uninstall -r $package_name | Write-Host
        if ($LASTEXITCODE -ne 0) { throw "choco uninstall failed with $LastExitCode"}
    }
}