Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use local octopus #31

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .netconfig
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
[octopus]
serverUrl = https://etienne.octopus.app/
serverUrl = http://localhost:8080/
projectName = test
prefix = "PREFIX"
30 changes: 30 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
version: '3'
services:
octopus:
privileged: true
ports:
- "8080:8080"
- "10943:10943"
environment:
ADMIN_USERNAME: admin
ADMIN_EMAIL: [email protected]
ADMIN_PASSWORD: Password01!
ACCEPT_EULA: Y
DB_CONNECTION_STRING: Server=mssql,1433;Database=Octopus;User Id=SA;Password=Password01!;ConnectRetryCount=6
CONNSTRING: Server=mssql,1433;Database=Octopus;User Id=SA;Password=Password01!;ConnectRetryCount=6
MASTER_KEY: 6EdU6IWsCtMEwk0kPKflQQ==
image: octopusdeploy/octopusdeploy:latest
labels:
autoheal: true
depends_on:
- mssql
mssql:
environment:
ACCEPT_EULA: Y
SA_PASSWORD: Password01!
MSSQL_PID: Express
image: mcr.microsoft.com/mssql/server:2017-latest-ubuntu
autoheal:
image: willfarrell/autoheal:latest
volumes:
- /var/run/docker.sock:/var/run/docker.sock
7 changes: 7 additions & 0 deletions src/OctopusConnector.fs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
module OctopusConnector
open System
open Octopus.Client
open Octopus.Client.Model
open OctocusVariableManager
Expand Down Expand Up @@ -59,3 +60,9 @@ type OctopusWrapper(octopusConfig :OctopusConfig) =
projectResource.LifecycleId <- "Default Lifecycle"
projectResource.IsDisabled <- false
repo.Projects.Create projectResource |> ignore

member this.CreateKey username password =
repo.Users.SignIn(username, password)
let user = repo.Users.GetCurrent()
let apiKey = repo.Users.CreateApiKey(user)
apiKey.ApiKey
26 changes: 26 additions & 0 deletions test/Create-Key.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
. $PSScriptRoot\Octopus.ps1

Wait-ForOctopus

#Creating a connection
$repository = Connect-ToOctopus "http://localhost:8080"

#Creating login object
$LoginObj = New-Object Octopus.Client.Model.LoginCommand
$LoginObj.Username = "admin"
$LoginObj.Password = "Password01!"

#Loging in to Octopus
$repository.Users.SignIn($LoginObj)

#Getting current user logged in
$UserObj = $repository.Users.GetCurrent()

#Creating API Key for user. This automatically gets saved to the database.
$ApiObj = $repository.Users.CreateApiKey($UserObj, "Terraform tests")

#Save the API key so we can use it later
Set-Content -Path tests\octopus_api.txt -Value $ApiObj.ApiKey

echo "TF_ACC=true" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
echo "OCTOPUS_APIKEY=$($ApiObj.ApiKey)" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
5 changes: 4 additions & 1 deletion test/Octopus.Config.Exporter.Cli.Test.fsproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,14 @@
<Compile Include="UITest.fs" />
<Compile Include="../src/Helper.fs" />
<Compile Include="Helper.fs" />
<Compile Include="OctocusVariableManagerTest.fs" />
<Compile Include="OctopusVariableManagerTest.fs" />
<Compile Include="OctopusConnectorTest.fs" />
<Compile Include="VarJsonParser.fs" />
<Compile Include="Program.fs" />
<Content Include="config_sample.json" CopyToOutputDirectory="Always" />
<Content Include="Create-Key.ps1" />
<Content Include="Octopus.ps1" />
<Content Include="start-octopus.sh" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FsUnit.xUnit" Version="4.2.0" />
Expand Down
185 changes: 185 additions & 0 deletions test/Octopus.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
Install-Module -Name PowershellOctopusClient -Force
Import-Module -Name PowershellOctopusClient

function Wait-ForOctopus() {
$start = Get-Date
do {
Write-Host "Waiting for Octopus"

# show the status of the containers
#$containers = & docker container ls
#Write-Host $containers

# Get the logs of the octopus container
#$logs = & docker logs tests_octopus_1
#Write-Host $logs

sleep 5
$now = Get-Date
$wait = New-Timespan -Start $start -End $now
if ($wait.TotalMinutes -ge 5) {
Write-Host "Gave up waiting"
break;
}

} until (Test-Connection -IPv4 -ComputerName localhost -TCPPort 8080 -Quiet)
}

function Get-CompleteExceptionMessage() {
param (
[System.Management.Automation.ErrorRecord]$Exception,
[int]$limit = -1
)

$msg = ""

if ($null -ne $Exception) {
try {
$e = $Exception.Exception
$msg = $e.Message
while ($e.InnerException) {
$e = $e.InnerException
$msg += "`n" + $e.Message
}

} catch {
# Ignore
}
}

if ($limit -gt 0) {
$msg = $msg.SubString(0, [math]::min($limit,$msg.Length))
}

return $msg
}


function Connect-ToOctopus() {
param (
[string]$url,
[string]$username = "admin",
[string]$password = "Password01!"
)
try
{
$endpoint = New-Object Octopus.Client.OctopusServerEndpoint $url
$repository = New-Object Octopus.Client.OctopusRepository $endpoint
$LoginObj = New-Object Octopus.Client.Model.LoginCommand
$LoginObj.Username = $username
$LoginObj.Password = $password
Invoke-ScriptBlockWithRetries { $repository.Users.SignIn($LoginObj) } -FailureMessage "Failed to log into Octopus at $url" | Out-Null
return $repository
} catch {
Write-Error (Get-CompleteExceptionMessage $_)
throw $_
}
}

function Invoke-CommandWithRetries
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $True)]
[string]$Command,
[Array]$Arguments,
[bool]$TrustExitCode = $True,
[int]$RetrySleepSeconds = 10,
[int]$MaxAttempts = 10,
[bool]$PrintCommand = $True,
[bool]$PrintOutput = $False,
[int[]]$AllowedReturnValues = @(),
[string]$ErrorMessage
)

Process
{
$attempt = 0
while ($true)
{
Write-Host $(if ($PrintCommand) { "Executing: $Command $Arguments" }
else { "Executing command..." })

try
{
$output = & $Command $Arguments 2>&1
if ($PrintOutput) { Write-Host $output }

$stderr = $output | where { $_ -is [System.Management.Automation.ErrorRecord] }
if (($LASTEXITCODE -eq 0 -or $AllowedReturnValues -contains $LASTEXITCODE) -and ($TrustExitCode -or !($stderr)))
{
Write-Host "Command executed successfully"
return $output
}

Write-Host "Command failed with exit code ($LASTEXITCODE) and stderr: $stderr" -ForegroundColor Yellow
}
catch
{
Write-Host "Command failed with exit code ($LASTEXITCODE), exception ($_) and stderr: $stderr" -ForegroundColor Yellow
}

if ($attempt -eq $MaxAttempts)
{
$ex = new-object System.Management.Automation.CmdletInvocationException "All retry attempts exhausted $ErrorMessage"
$category = [System.Management.Automation.ErrorCategory]::LimitsExceeded
$errRecord = new-object System.Management.Automation.ErrorRecord $ex, "CommandFailed", $category, $Command
$psCmdlet.WriteError($errRecord)
return $output
}

$attempt++;
Write-Host "Retrying test execution [#$attempt/$MaxAttempts] in $RetrySleepSeconds seconds..."
Start-Sleep -s $RetrySleepSeconds
}
}
}

function Invoke-ScriptBlockWithRetries {
[CmdletBinding()]
param (
[parameter(Mandatory, ValueFromPipeline)]
[ValidateNotNullOrEmpty()]
[scriptblock] $ScriptBlock,
[int] $RetryCount = 3,
[int] $TimeoutInSecs = 30,
[string] $SuccessMessage = "",
[string] $FailureMessage = ""
)

process {
$Attempt = 1

do {
try {
$PreviousPreference = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
Invoke-Command -ScriptBlock $ScriptBlock -OutVariable Result | Out-Null
$ErrorActionPreference = $PreviousPreference

# flow control will execute the next line only if the command in the scriptblock executed without any errors
# if an error is thrown, flow control will go to the 'catch' block
if (-not [string]::IsNullOrEmpty($SuccessMessage)) {
Write-Host "$SuccessMessage `n"
}
return $result
}
catch {
if ($Attempt -gt $RetryCount) {
if (-not [string]::IsNullOrEmpty($FailureMessage)) {
Write-Host "$FailureMessage! Error was $(Get-CompleteExceptionMessage $_). Total retry attempts: $RetryCount"
}
throw $_.exception
}
else {
if (-not [string]::IsNullOrEmpty($FailureMessage)) {
Write-Host "[$Attempt/$RetryCount] $FailureMessage. Error was $(Get-CompleteExceptionMessage $_). Retrying in $TimeoutInSecs seconds..."
}
Start-Sleep -Seconds $TimeoutInSecs
$Attempt = $Attempt + 1
}
}
}
While ($true)
}
}
12 changes: 10 additions & 2 deletions test/OctopusConnectorTest.fs
Original file line number Diff line number Diff line change
Expand Up @@ -9,30 +9,38 @@ open OctocusVariableManager
open TestHelper
open System



type TestCliArguments =
| [<Mandatory>] [<CustomAppSettings(OctopusServerAppSettings)>] OctopusServer of server:string
| [<Mandatory>] [<CustomAppSettings(OctopusApiKeyAppSettings)>] OctopusApiKey of apiKey:string
| [<Mandatory>] [<CustomAppSettings(OctopusProjectNameAppSettings)>] OctopusProject of projectName:string

interface IArgParserTemplate with
member s.Usage = ""

let

[<Trait("Category","Integration")>]
type ``Connector``(output:ITestOutputHelper) =

let mutable octopusConfig
let getOctopusConfig (parsedResult :ParseResults<TestCliArguments>) =
{
Url = parsedResult.GetResult OctopusServer;
ApiKey = parsedResult.GetResult OctopusApiKey;
ProjectName = parsedResult.GetResult OctopusProject
}


let originalConfig = ParseResult<TestCliArguments>(true) |> getOctopusConfig
let testConfig = {originalConfig with ProjectName = Guid.NewGuid().ToString().Substring(0, 8)}

let octopusWrapper = new OctopusWrapper(testConfig)
do
octopusWrapper.CreateProject testConfig
do
let apiKey = octopusWrapper.CreateKey "admin" "Password01!"
let testConfig = {originalConfig with ApiKey = apiKey}
octopusWrapper.CreateProject testConfig

[<Fact>]
let ``GetVariables should retrieve variables from octopus`` () =
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module OctocusVariableManagerTest
module OctopusVariableManagerTest
open FsUnit
open OctocusVariableManager
open Xunit
Expand Down
3 changes: 3 additions & 0 deletions test/start-octopus.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@

docker-compose up --detach