2021-01-25 19:16:53 +00:00
|
|
|
package exec
|
|
|
|
|
|
|
|
import (
|
2021-09-06 07:58:26 +00:00
|
|
|
"context"
|
2021-01-25 19:16:53 +00:00
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
portainer "github.com/portainer/portainer/api"
|
|
|
|
)
|
|
|
|
|
|
|
|
const composeFile = `version: "3.9"
|
|
|
|
services:
|
|
|
|
busybox:
|
|
|
|
image: "alpine:latest"
|
|
|
|
container_name: "compose_wrapper_test"`
|
|
|
|
const composedContainerName = "compose_wrapper_test"
|
|
|
|
|
|
|
|
func setup(t *testing.T) (*portainer.Stack, *portainer.Endpoint) {
|
|
|
|
dir := t.TempDir()
|
|
|
|
composeFileName := "compose_wrapper_test.yml"
|
|
|
|
f, _ := os.Create(filepath.Join(dir, composeFileName))
|
|
|
|
f.WriteString(composeFile)
|
|
|
|
|
|
|
|
stack := &portainer.Stack{
|
|
|
|
ProjectPath: dir,
|
|
|
|
EntryPoint: composeFileName,
|
|
|
|
Name: "project-name",
|
|
|
|
}
|
|
|
|
|
2021-07-21 01:56:28 +00:00
|
|
|
endpoint := &portainer.Endpoint{
|
|
|
|
URL: "unix://",
|
|
|
|
}
|
2021-01-25 19:16:53 +00:00
|
|
|
|
|
|
|
return stack, endpoint
|
|
|
|
}
|
|
|
|
|
|
|
|
func Test_UpAndDown(t *testing.T) {
|
|
|
|
|
|
|
|
stack, endpoint := setup(t)
|
|
|
|
|
2021-07-21 01:56:28 +00:00
|
|
|
w, err := NewComposeStackManager("", "", nil)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("Failed creating manager: %s", err)
|
|
|
|
}
|
2021-01-25 19:16:53 +00:00
|
|
|
|
2021-09-06 07:58:26 +00:00
|
|
|
ctx := context.TODO()
|
|
|
|
|
2022-01-16 21:20:45 +00:00
|
|
|
err = w.Up(ctx, stack, endpoint, false)
|
2021-01-25 19:16:53 +00:00
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("Error calling docker-compose up: %s", err)
|
|
|
|
}
|
|
|
|
|
2021-07-21 01:56:28 +00:00
|
|
|
if !containerExists(composedContainerName) {
|
2021-01-25 19:16:53 +00:00
|
|
|
t.Fatal("container should exist")
|
|
|
|
}
|
|
|
|
|
2021-09-06 07:58:26 +00:00
|
|
|
err = w.Down(ctx, stack, endpoint)
|
2021-01-25 19:16:53 +00:00
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("Error calling docker-compose down: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if containerExists(composedContainerName) {
|
|
|
|
t.Fatal("container should be removed")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-21 01:56:28 +00:00
|
|
|
func containerExists(containerName string) bool {
|
|
|
|
cmd := exec.Command("docker", "ps", "-a", "-f", fmt.Sprintf("name=%s", containerName))
|
2021-01-25 19:16:53 +00:00
|
|
|
|
|
|
|
out, err := cmd.Output()
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("failed to list containers: %s", err)
|
|
|
|
}
|
|
|
|
|
2021-07-21 01:56:28 +00:00
|
|
|
return strings.Contains(string(out), containerName)
|
2021-01-25 19:16:53 +00:00
|
|
|
}
|