summaryrefslogtreecommitdiffstats
path: root/src/cmd/go/internal/web/file_test.go
blob: 3734df5c4e9bc0382f28ed87e2257527e17fc64f (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
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package web

import (
	"errors"
	"io/fs"
	"os"
	"path/filepath"
	"testing"
)

func TestGetFileURL(t *testing.T) {
	const content = "Hello, file!\n"

	f, err := os.CreateTemp("", "web-TestGetFileURL")
	if err != nil {
		t.Fatal(err)
	}
	defer os.Remove(f.Name())

	if _, err := f.WriteString(content); err != nil {
		t.Error(err)
	}
	if err := f.Close(); err != nil {
		t.Fatal(err)
	}

	u, err := urlFromFilePath(f.Name())
	if err != nil {
		t.Fatal(err)
	}

	b, err := GetBytes(u)
	if err != nil {
		t.Fatalf("GetBytes(%v) = _, %v", u, err)
	}
	if string(b) != content {
		t.Fatalf("after writing %q to %s, GetBytes(%v) read %q", content, f.Name(), u, b)
	}
}

func TestGetNonexistentFile(t *testing.T) {
	path, err := filepath.Abs("nonexistent")
	if err != nil {
		t.Fatal(err)
	}

	u, err := urlFromFilePath(path)
	if err != nil {
		t.Fatal(err)
	}

	b, err := GetBytes(u)
	if !errors.Is(err, fs.ErrNotExist) {
		t.Fatalf("GetBytes(%v) = %q, %v; want _, fs.ErrNotExist", u, b, err)
	}
}