gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/gmhttp/filetransport_test.go (about)

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package gmhttp
     6  
     7  import (
     8  	"io"
     9  	"os"
    10  	"path/filepath"
    11  	"testing"
    12  )
    13  
    14  func checker(t *testing.T) func(string, error) {
    15  	return func(call string, err error) {
    16  		if err == nil {
    17  			return
    18  		}
    19  		t.Fatalf("%s: %v", call, err)
    20  	}
    21  }
    22  
    23  func TestFileTransport(t *testing.T) {
    24  	check := checker(t)
    25  
    26  	dname := t.TempDir()
    27  	fname := filepath.Join(dname, "foo.txt")
    28  	err := os.WriteFile(fname, []byte("Bar"), 0644)
    29  	check("WriteFile", err)
    30  	defer func(name string) {
    31  		_ = os.Remove(name)
    32  	}(fname)
    33  
    34  	tr := &Transport{}
    35  	tr.RegisterProtocol("file", NewFileTransport(Dir(dname)))
    36  	c := &Client{Transport: tr}
    37  
    38  	fooURLs := []string{"file:///foo.txt", "file://../foo.txt"}
    39  	for _, urlstr := range fooURLs {
    40  		res, err := c.Get(urlstr)
    41  		check("Get "+urlstr, err)
    42  		if res.StatusCode != 200 {
    43  			t.Errorf("for %s, StatusCode = %d, want 200", urlstr, res.StatusCode)
    44  		}
    45  		if res.ContentLength != -1 {
    46  			t.Errorf("for %s, ContentLength = %d, want -1", urlstr, res.ContentLength)
    47  		}
    48  		if res.Body == nil {
    49  			t.Fatalf("for %s, nil Body", urlstr)
    50  		}
    51  		slurp, err := io.ReadAll(res.Body)
    52  		_ = res.Body.Close()
    53  		check("ReadAll "+urlstr, err)
    54  		if string(slurp) != "Bar" {
    55  			t.Errorf("for %s, got content %q, want %q", urlstr, string(slurp), "Bar")
    56  		}
    57  	}
    58  
    59  	const badURL = "file://../no-exist.txt"
    60  	res, err := c.Get(badURL)
    61  	check("Get "+badURL, err)
    62  	if res.StatusCode != 404 {
    63  		t.Errorf("for %s, StatusCode = %d, want 404", badURL, res.StatusCode)
    64  	}
    65  	_ = res.Body.Close()
    66  }