@marcel91200 / caddy Mirror · read-only
Fork 0

Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS

Mirrored from https://github.com/Slazee/caddy.git

Synced Nov 10, 23:45 UTC

master
go 70 lines 1.97 KB
Raw
1 package caddycmd
2
3 import (
4 "bytes"
5 "io"
6 "net/http"
7 "net/url"
8 "testing"
9 )
10
11 type trackingReadCloser struct {
12 *bytes.Reader
13 closed bool
14 }
15
16 func (r *trackingReadCloser) Close() error {
17 r.closed = true
18 return nil
19 }
20
21 func TestDownloadBuildClosesErrorResponseBody(t *testing.T) {
22 originalTransport := http.DefaultTransport
23 t.Cleanup(func() { http.DefaultTransport = originalTransport })
24
25 body := &trackingReadCloser{Reader: bytes.NewReader([]byte(`{"error":{"message":"bad request","id":"test"}}`))}
26 http.DefaultTransport = roundTripperFunc(func(req *http.Request) (*http.Response, error) {
27 return &http.Response{
28 StatusCode: http.StatusBadRequest,
29 Body: body,
30 Request: req,
31 }, nil
32 })
33
34 if _, err := downloadBuild(url.Values{}); err == nil {
35 t.Fatal("downloadBuild succeeded, want error")
36 }
37 if !body.closed {
38 t.Fatal("downloadBuild did not close the error response body")
39 }
40 }
41
42 func TestModuleContainsPackage(t *testing.T) {
43 tests := []struct {
44 name string
45 modulePath string
46 packagePath string
47 want bool
48 }{
49 {name: "module root", modulePath: "example.com/mod", packagePath: "example.com/mod", want: true},
50 {name: "module package", modulePath: "example.com/mod", packagePath: "example.com/mod/pkg", want: true},
51 {name: "shared prefix", modulePath: "example.com/mod", packagePath: "example.com/module", want: false},
52 {name: "caddy module shared prefix", modulePath: "github.com/caddyserver/caddy/v2", packagePath: "github.com/caddyserver/caddy/v20", want: false},
53 }
54
55 for _, tt := range tests {
56 t.Run(tt.name, func(t *testing.T) {
57 if got := moduleContainsPackage(tt.modulePath, tt.packagePath); got != tt.want {
58 t.Fatalf("moduleContainsPackage(%q, %q) = %v, want %v", tt.modulePath, tt.packagePath, got, tt.want)
59 }
60 })
61 }
62 }
63
64 type roundTripperFunc func(*http.Request) (*http.Response, error)
65
66 func (f roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
67 return f(req)
68 }
69
70 var _ io.ReadCloser = (*trackingReadCloser)(nil)