File: testutilserve.go

package info (click to toggle)
docker-buildx 0.13.1%2Bds1-3
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 2,356 kB
  • sloc: sh: 299; makefile: 87
file content (62 lines) | stat: -rw-r--r-- 1,128 bytes parent folder | download
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
package gitutil

import (
	"context"
	"fmt"
	"net"
	"net/http"
	"testing"

	"github.com/stretchr/testify/require"
)

func GitServeHTTP(c *Git, t testing.TB) (url string) {
	t.Helper()
	gitUpdateServerInfo(c, t)
	ctx, cancel := context.WithCancel(context.TODO())

	ready := make(chan struct{})
	done := make(chan struct{})

	name := "test.git"
	dir, err := c.GitDir()
	if err != nil {
		cancel()
	}

	var addr string
	go func() {
		mux := http.NewServeMux()
		prefix := fmt.Sprintf("/%s/", name)
		mux.Handle(prefix, http.StripPrefix(prefix, http.FileServer(http.Dir(dir))))
		l, err := net.Listen("tcp", "localhost:0")
		if err != nil {
			panic(err)
		}

		addr = l.Addr().String()

		close(ready)

		s := http.Server{Handler: mux} //nolint:gosec // potential attacks are not relevant for tests
		go s.Serve(l)
		<-ctx.Done()
		s.Shutdown(context.TODO())
		l.Close()

		close(done)
	}()
	<-ready

	t.Cleanup(func() {
		cancel()
		<-done
	})
	return fmt.Sprintf("http://%s/%s", addr, name)
}

func gitUpdateServerInfo(c *Git, tb testing.TB) {
	tb.Helper()
	_, err := fakeGit(c, "update-server-info")
	require.NoError(tb, err)
}