aboutsummaryrefslogtreecommitdiffhomepage
path: root/container/init_test.go
blob: 9e6832d1f7bb6f0386c1e89efd09599acb71740e (plain)
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
70
71
72
73
package container_test

import (
	"context"
	"log"
	"os"
	"testing"
	"time"

	"hakurei.app/command"
	"hakurei.app/container"
	"hakurei.app/internal"
	"hakurei.app/internal/hlog"
	"hakurei.app/ldd"
)

const (
	envDoCheck = "HAKUREI_TEST_DO_CHECK"

	helperDefaultTimeout = 5 * time.Second
	helperInnerPath      = "/usr/bin/helper"
)

var (
	absHelperInnerPath = container.MustAbs(helperInnerPath)
)

var helperCommands []func(c command.Command)

func TestMain(m *testing.M) {
	container.TryArgv0(hlog.Output{}, hlog.Prepare, internal.InstallOutput)

	if os.Getenv(envDoCheck) == "1" {
		c := command.New(os.Stderr, log.Printf, "helper", func(args []string) error {
			log.SetFlags(0)
			log.SetPrefix("helper: ")
			return nil
		})
		for _, f := range helperCommands {
			f(c)
		}
		c.MustParse(os.Args[1:], func(err error) {
			if err != nil {
				log.Fatal(err.Error())
			}
		})
		return
	}

	os.Exit(m.Run())
}

func helperNewContainerLibPaths(ctx context.Context, libPaths *[]*container.Absolute, args ...string) (c *container.Container) {
	c = container.NewCommand(ctx, absHelperInnerPath, "helper", args...)
	c.Env = append(c.Env, envDoCheck+"=1")
	c.Bind(container.MustAbs(os.Args[0]), absHelperInnerPath, 0)

	// in case test has cgo enabled
	if entries, err := ldd.Exec(ctx, os.Args[0]); err != nil {
		log.Fatalf("ldd: %v", err)
	} else {
		*libPaths = ldd.Path(entries)
	}
	for _, name := range *libPaths {
		c.Bind(name, name, 0)
	}

	return
}

func helperNewContainer(ctx context.Context, args ...string) (c *container.Container) {
	return helperNewContainerLibPaths(ctx, new([]*container.Absolute), args...)
}