Showing preview only (251K chars total). Download the full file or copy to clipboard to get everything.
Repository: lox/httpcache
Branch: master
Commit: 2de7d84cb251
Files: 65
Total size: 232.5 KB
Directory structure:
gitextract_qzbt7970/
├── .gitignore
├── LICENSE
├── README.md
├── bench_test.go
├── cache.go
├── cache_test.go
├── cachecontrol.go
├── cachecontrol_test.go
├── cli/
│ └── httpcache.go
├── handler.go
├── header.go
├── httplog/
│ └── log.go
├── key.go
├── key_test.go
├── logger.go
├── resource.go
├── spec_test.go
├── util_test.go
├── validator.go
├── vendor/
│ ├── github.com/
│ │ ├── rainycape/
│ │ │ └── vfs/
│ │ │ ├── LICENSE
│ │ │ ├── README.md
│ │ │ ├── bench_test.go
│ │ │ ├── chroot.go
│ │ │ ├── doc.go
│ │ │ ├── file.go
│ │ │ ├── file_util.go
│ │ │ ├── fs.go
│ │ │ ├── map.go
│ │ │ ├── mem.go
│ │ │ ├── mounter.go
│ │ │ ├── open.go
│ │ │ ├── open_test.go
│ │ │ ├── rewriter.go
│ │ │ ├── ro.go
│ │ │ ├── testdata/
│ │ │ │ ├── download-data.sh
│ │ │ │ ├── fs/
│ │ │ │ │ ├── a/
│ │ │ │ │ │ └── b/
│ │ │ │ │ │ └── c/
│ │ │ │ │ │ └── d
│ │ │ │ │ └── empty
│ │ │ │ ├── fs.tar.bz2
│ │ │ │ └── update-fs.sh
│ │ │ ├── util.go
│ │ │ ├── vfs.go
│ │ │ ├── vfs_test.go
│ │ │ ├── write.go
│ │ │ └── write_test.go
│ │ └── stretchr/
│ │ └── testify/
│ │ ├── assert/
│ │ │ ├── assertions.go
│ │ │ ├── assertions_test.go
│ │ │ ├── doc.go
│ │ │ ├── errors.go
│ │ │ ├── forward_assertions.go
│ │ │ ├── forward_assertions_test.go
│ │ │ ├── http_assertions.go
│ │ │ └── http_assertions_test.go
│ │ └── require/
│ │ ├── doc.go
│ │ ├── requirements.go
│ │ └── requirements_test.go
│ ├── gopkg.in/
│ │ └── djherbis/
│ │ └── stream.v1/
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── fs.go
│ │ ├── memfs.go
│ │ ├── reader.go
│ │ ├── stream.go
│ │ ├── stream_test.go
│ │ └── sync.go
│ └── vendor.json
└── wercker.yml
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
cachedata/
httpcache
Godeps/_workspace
================================================
FILE: LICENSE
================================================
The MIT License
Copyright (c) 2010-2014 Lachlan Donald http://lachlan.me
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
================================================
FILE: README.md
================================================
# httpcache
`httpcache` provides an [rfc7234][] compliant golang [http.Handler](http://golang.org/pkg/net/http/#Handler).
[](https://app.wercker.com/project/bykey/a76986990d27e72ea656bb37bb93f59f)
[](https://godoc.org/github.com/lox/httpcache)
## Example
This example is from the included CLI, it runs a caching proxy on http://localhost:8080.
```go
proxy := &httputil.ReverseProxy{
Director: func(r *http.Request) {
},
}
handler := httpcache.NewHandler(httpcache.NewMemoryCache(), proxy)
handler.Shared = true
log.Printf("proxy listening on http://%s", listen)
log.Fatal(http.ListenAndServe(listen, handler))
```
## Implemented
- All of [rfc7234][], except those listed below
- Disk and Memory storage
- Apache-like logging via `httplog` package
## Todo
- Offline operation
- Size constraints on memory/disk cache and cache eviction
- Correctly handle mixture of HTTP1.0 clients and 1.1 upstreams
- More detail in `Via` header
- Support for weak entities with `If-Match` and `If-None-Match`
- Invalidation based on `Content-Location` and request method
- Better handling of duplicate headers and CacheControl values
## Caveats
- Conditional requests are never cached, this includes `Range` requests
## Testing
Tests are currently conducted via the test suite and verified via the [CoAdvisor tool](http://coad.measurement-factory.com/).
## Reading List
- http://httpwg.github.io/specs/rfc7234.html
- https://www.mnot.net/blog/2011/07/11/what_proxies_must_do
- https://www.mnot.net/blog/2014/06/07/rfc2616_is_dead
[rfc7234]: http://httpwg.github.io/specs/rfc7234.html
================================================
FILE: bench_test.go
================================================
package httpcache_test
import (
"fmt"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"testing"
"github.com/lox/httpcache"
)
func BenchmarkCachingFiles(b *testing.B) {
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Cache-Control", "max-age=100000")
fmt.Fprintf(w, "cache server payload")
}))
defer backend.Close()
u, err := url.Parse(backend.URL)
if err != nil {
b.Fatal(err)
}
handler := httpcache.NewHandler(httpcache.NewMemoryCache(), httputil.NewSingleHostReverseProxy(u))
handler.Shared = true
cacheServer := httptest.NewServer(handler)
defer cacheServer.Close()
for n := 0; n < b.N; n++ {
client := http.Client{}
resp, err := client.Get(fmt.Sprintf("%s/llamas/%d", cacheServer.URL, n))
if err != nil {
b.Fatal(err)
}
resp.Body.Close()
}
}
================================================
FILE: cache.go
================================================
package httpcache
import (
"bufio"
"bytes"
"crypto/sha256"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/textproto"
"os"
pathutil "path"
"strconv"
"strings"
"time"
"github.com/rainycape/vfs"
)
const (
headerPrefix = "header/"
bodyPrefix = "body/"
formatPrefix = "v1/"
)
// Returned when a resource doesn't exist
var ErrNotFoundInCache = errors.New("Not found in cache")
type Cache interface {
Header(key string) (Header, error)
Store(res *Resource, keys ...string) error
Retrieve(key string) (*Resource, error)
Invalidate(keys ...string)
Freshen(res *Resource, keys ...string) error
}
// cache provides a storage mechanism for cached Resources
type cache struct {
fs vfs.VFS
stale map[string]time.Time
}
var _ Cache = (*cache)(nil)
type Header struct {
http.Header
StatusCode int
}
// NewCache returns a cache backend off the provided VFS
func NewVFSCache(fs vfs.VFS) Cache {
return &cache{fs: fs, stale: map[string]time.Time{}}
}
// NewMemoryCache returns an ephemeral cache in memory
func NewMemoryCache() Cache {
return NewVFSCache(vfs.Memory())
}
// NewDiskCache returns a disk-backed cache
func NewDiskCache(dir string) (Cache, error) {
if err := os.MkdirAll(dir, 0777); err != nil {
return nil, err
}
fs, err := vfs.FS(dir)
if err != nil {
return nil, err
}
chfs, err := vfs.Chroot("/", fs)
if err != nil {
return nil, err
}
return NewVFSCache(chfs), nil
}
func (c *cache) vfsWrite(path string, r io.Reader) error {
if err := vfs.MkdirAll(c.fs, pathutil.Dir(path), 0700); err != nil {
return err
}
f, err := c.fs.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer f.Close()
if _, err := io.Copy(f, r); err != nil {
return err
}
return nil
}
// Retrieve the Status and Headers for a given key path
func (c *cache) Header(key string) (Header, error) {
path := headerPrefix + formatPrefix + hashKey(key)
f, err := c.fs.Open(path)
if err != nil {
if vfs.IsNotExist(err) {
return Header{}, ErrNotFoundInCache
}
return Header{}, err
}
return readHeaders(bufio.NewReader(f))
}
// Store a resource against a number of keys
func (c *cache) Store(res *Resource, keys ...string) error {
var buf = &bytes.Buffer{}
if length, err := strconv.ParseInt(res.Header().Get("Content-Length"), 10, 64); err == nil {
if _, err = io.CopyN(buf, res, length); err != nil {
return err
}
} else if _, err = io.Copy(buf, res); err != nil {
return err
}
for _, key := range keys {
delete(c.stale, key)
if err := c.storeBody(buf, key); err != nil {
return err
}
if err := c.storeHeader(res.Status(), res.Header(), key); err != nil {
return err
}
}
return nil
}
func (c *cache) storeBody(r io.Reader, key string) error {
if err := c.vfsWrite(bodyPrefix+formatPrefix+hashKey(key), r); err != nil {
return err
}
return nil
}
func (c *cache) storeHeader(code int, h http.Header, key string) error {
hb := &bytes.Buffer{}
hb.Write([]byte(fmt.Sprintf("HTTP/1.1 %d %s\r\n", code, http.StatusText(code))))
headersToWriter(h, hb)
if err := c.vfsWrite(headerPrefix+formatPrefix+hashKey(key), bytes.NewReader(hb.Bytes())); err != nil {
return err
}
return nil
}
// Retrieve returns a cached Resource for the given key
func (c *cache) Retrieve(key string) (*Resource, error) {
f, err := c.fs.Open(bodyPrefix + formatPrefix + hashKey(key))
if err != nil {
if vfs.IsNotExist(err) {
return nil, ErrNotFoundInCache
}
return nil, err
}
h, err := c.Header(key)
if err != nil {
if vfs.IsNotExist(err) {
return nil, ErrNotFoundInCache
}
return nil, err
}
res := NewResource(h.StatusCode, f, h.Header)
if staleTime, exists := c.stale[key]; exists {
if !res.DateAfter(staleTime) {
log.Printf("stale marker of %s found", staleTime)
res.MarkStale()
}
}
return res, nil
}
func (c *cache) Invalidate(keys ...string) {
log.Printf("invalidating %q", keys)
for _, key := range keys {
c.stale[key] = Clock()
}
}
func (c *cache) Freshen(res *Resource, keys ...string) error {
for _, key := range keys {
if h, err := c.Header(key); err == nil {
if h.StatusCode == res.Status() && headersEqual(h.Header, res.Header()) {
debugf("freshening key %s", key)
if err := c.storeHeader(h.StatusCode, res.Header(), key); err != nil {
return err
}
} else {
debugf("freshen failed, invalidating %s", key)
c.Invalidate(key)
}
}
}
return nil
}
func hashKey(key string) string {
h := sha256.New()
io.WriteString(h, key)
return fmt.Sprintf("%x", h.Sum(nil))
}
func readHeaders(r *bufio.Reader) (Header, error) {
tp := textproto.NewReader(r)
line, err := tp.ReadLine()
if err != nil {
return Header{}, err
}
f := strings.SplitN(line, " ", 3)
if len(f) < 2 {
return Header{}, fmt.Errorf("malformed HTTP response: %s", line)
}
statusCode, err := strconv.Atoi(f[1])
if err != nil {
return Header{}, fmt.Errorf("malformed HTTP status code: %s", f[1])
}
mimeHeader, err := tp.ReadMIMEHeader()
if err != nil {
return Header{}, err
}
return Header{StatusCode: statusCode, Header: http.Header(mimeHeader)}, nil
}
func headersToWriter(h http.Header, w io.Writer) error {
if err := h.Write(w); err != nil {
return err
}
// ReadMIMEHeader expects a trailing newline
_, err := w.Write([]byte("\r\n"))
return err
}
================================================
FILE: cache_test.go
================================================
package httpcache_test
import (
"net/http"
"strings"
"testing"
"github.com/lox/httpcache"
"github.com/stretchr/testify/require"
)
func TestSaveResource(t *testing.T) {
var body = strings.Repeat("llamas", 5000)
var cache = httpcache.NewMemoryCache()
res := httpcache.NewResourceBytes(http.StatusOK, []byte(body), http.Header{
"Llamas": []string{"true"},
})
if err := cache.Store(res, "testkey"); err != nil {
t.Fatal(err)
}
resOut, err := cache.Retrieve("testkey")
if err != nil {
t.Fatal(err)
}
require.NotNil(t, resOut)
require.Equal(t, res.Header(), resOut.Header())
require.Equal(t, body, readAllString(resOut))
}
func TestSaveResourceWithIncorrectContentLength(t *testing.T) {
var body = "llamas"
var cache = httpcache.NewMemoryCache()
res := httpcache.NewResourceBytes(http.StatusOK, []byte(body), http.Header{
"Llamas": []string{"true"},
"Content-Length": []string{"10"},
})
if err := cache.Store(res, "testkey"); err == nil {
t.Fatal("Entry should have generated an error")
}
_, err := cache.Retrieve("testkey")
if err != httpcache.ErrNotFoundInCache {
t.Fatal("Entry shouldn't have been cached")
}
}
================================================
FILE: cachecontrol.go
================================================
package httpcache
import (
"bytes"
"fmt"
"net/http"
"sort"
"strings"
"time"
)
const (
CacheControlHeader = "Cache-Control"
)
type CacheControl map[string][]string
func ParseCacheControlHeaders(h http.Header) (CacheControl, error) {
return ParseCacheControl(strings.Join(h["Cache-Control"], ", "))
}
func ParseCacheControl(input string) (CacheControl, error) {
cc := make(CacheControl)
length := len(input)
isValue := false
lastKey := ""
for pos := 0; pos < length; pos++ {
var token string
switch input[pos] {
case '"':
if offset := strings.IndexAny(input[pos+1:], `"`); offset != -1 {
token = input[pos+1 : pos+1+offset]
} else {
token = input[pos+1:]
}
pos += len(token) + 1
case ',', '\n', '\r', ' ', '\t':
continue
case '=':
isValue = true
continue
default:
if offset := strings.IndexAny(input[pos:], "\"\n\t\r ,="); offset != -1 {
token = input[pos : pos+offset]
} else {
token = input[pos:]
}
pos += len(token) - 1
}
if isValue {
cc.Add(lastKey, token)
isValue = false
} else {
cc.Add(token, "")
lastKey = token
}
}
return cc, nil
}
func (cc CacheControl) Get(key string) (string, bool) {
v, exists := cc[key]
if exists && len(v) > 0 {
return v[0], true
}
return "", exists
}
func (cc CacheControl) Add(key, val string) {
if !cc.Has(key) {
cc[key] = []string{}
}
if val != "" {
cc[key] = append(cc[key], val)
}
}
func (cc CacheControl) Has(key string) bool {
_, exists := cc[key]
return exists
}
func (cc CacheControl) Duration(key string) (time.Duration, error) {
d, _ := cc.Get(key)
return time.ParseDuration(d + "s")
}
func (cc CacheControl) String() string {
keys := make([]string, len(cc))
for k, _ := range cc {
keys = append(keys, k)
}
sort.Strings(keys)
buf := bytes.Buffer{}
for _, k := range keys {
vals := cc[k]
if len(vals) == 0 {
buf.WriteString(k + ", ")
}
for _, val := range vals {
buf.WriteString(fmt.Sprintf("%s=%q, ", k, val))
}
}
return strings.TrimSuffix(buf.String(), ", ")
}
================================================
FILE: cachecontrol_test.go
================================================
package httpcache_test
import (
"testing"
. "github.com/lox/httpcache"
"github.com/stretchr/testify/require"
)
func TestParsingCacheControl(t *testing.T) {
table := []struct {
ccString string
ccStruct CacheControl
}{
{`public, private="set-cookie", max-age=100`, CacheControl{
"public": []string{},
"private": []string{"set-cookie"},
"max-age": []string{"100"},
}},
{` foo="max-age=8, space", public`, CacheControl{
"public": []string{},
"foo": []string{"max-age=8, space"},
}},
{`s-maxage=86400`, CacheControl{
"s-maxage": []string{"86400"},
}},
{`max-stale`, CacheControl{
"max-stale": []string{},
}},
{`max-stale=60`, CacheControl{
"max-stale": []string{"60"},
}},
{`" max-age=8,max-age=8 "=blah`, CacheControl{
" max-age=8,max-age=8 ": []string{"blah"},
}},
}
for _, expect := range table {
cc, err := ParseCacheControl(expect.ccString)
if err != nil {
t.Fatal(err)
}
require.Equal(t, cc, expect.ccStruct)
require.NotEmpty(t, cc.String())
}
}
func BenchmarkCacheControlParsing(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := ParseCacheControl(`public, private="set-cookie", max-age=100`)
if err != nil {
b.Fatal(err)
}
}
}
================================================
FILE: cli/httpcache.go
================================================
package main
import (
"flag"
"log"
"net/http"
"net/http/httputil"
"os"
"github.com/lox/httpcache"
"github.com/lox/httpcache/httplog"
)
const (
defaultListen = "0.0.0.0:8080"
defaultDir = "./cachedata"
)
var (
listen string
useDisk bool
private bool
dir string
dumpHttp bool
verbose bool
)
func init() {
flag.StringVar(&listen, "listen", defaultListen, "the host and port to bind to")
flag.StringVar(&dir, "dir", defaultDir, "the dir to store cache data in, implies -disk")
flag.BoolVar(&useDisk, "disk", false, "whether to store cache data to disk")
flag.BoolVar(&verbose, "v", false, "show verbose output and debugging")
flag.BoolVar(&private, "private", false, "make the cache private")
flag.BoolVar(&dumpHttp, "dumphttp", false, "dumps http requests and responses to stdout")
flag.Parse()
if verbose {
httpcache.DebugLogging = true
}
}
func main() {
proxy := &httputil.ReverseProxy{
Director: func(r *http.Request) {
r.URL.Scheme = "http"
r.URL.Host = "127.0.0.1:80"
},
}
var cache httpcache.Cache
if useDisk && dir != "" {
log.Printf("storing cached resources in %s", dir)
if err := os.MkdirAll(dir, 0700); err != nil {
log.Fatal(err)
}
var err error
cache, err = httpcache.NewDiskCache(dir)
if err != nil {
log.Fatal(err)
}
} else {
cache = httpcache.NewMemoryCache()
}
handler := httpcache.NewHandler(cache, proxy)
handler.Shared = !private
respLogger := httplog.NewResponseLogger(handler)
respLogger.DumpRequests = dumpHttp
respLogger.DumpResponses = dumpHttp
respLogger.DumpErrors = dumpHttp
log.Printf("listening on http://%s", listen)
log.Fatal(http.ListenAndServe(listen, respLogger))
}
================================================
FILE: handler.go
================================================
package httpcache
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"net/http"
"strconv"
"sync"
"time"
"gopkg.in/djherbis/stream.v1"
)
const (
CacheHeader = "X-Cache"
ProxyDateHeader = "Proxy-Date"
)
var Writes sync.WaitGroup
var storeable = map[int]bool{
http.StatusOK: true,
http.StatusFound: true,
http.StatusNonAuthoritativeInfo: true,
http.StatusMultipleChoices: true,
http.StatusMovedPermanently: true,
http.StatusGone: true,
http.StatusNotFound: true,
}
var cacheableByDefault = map[int]bool{
http.StatusOK: true,
http.StatusFound: true,
http.StatusNotModified: true,
http.StatusNonAuthoritativeInfo: true,
http.StatusMultipleChoices: true,
http.StatusMovedPermanently: true,
http.StatusGone: true,
http.StatusPartialContent: true,
}
type Handler struct {
Shared bool
upstream http.Handler
validator *Validator
cache Cache
}
func NewHandler(cache Cache, upstream http.Handler) *Handler {
return &Handler{
upstream: upstream,
cache: cache,
validator: &Validator{upstream},
Shared: false,
}
}
func (h *Handler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
cReq, err := newCacheRequest(r)
if err != nil {
http.Error(rw, "invalid request: "+err.Error(),
http.StatusBadRequest)
return
}
if !cReq.isCacheable() {
debugf("request not cacheable")
rw.Header().Set(CacheHeader, "SKIP")
h.pipeUpstream(rw, cReq)
return
}
res, err := h.lookup(cReq)
if err != nil && err != ErrNotFoundInCache {
http.Error(rw, "lookup error: "+err.Error(),
http.StatusInternalServerError)
return
}
cacheType := "private"
if h.Shared {
cacheType = "shared"
}
if err == ErrNotFoundInCache {
if cReq.CacheControl.Has("only-if-cached") {
http.Error(rw, "key not in cache",
http.StatusGatewayTimeout)
return
}
debugf("%s %s not in %s cache", r.Method, r.URL.String(), cacheType)
h.passUpstream(rw, cReq)
return
} else {
debugf("%s %s found in %s cache", r.Method, r.URL.String(), cacheType)
}
if h.needsValidation(res, cReq) {
if cReq.CacheControl.Has("only-if-cached") {
http.Error(rw, "key was in cache, but required validation",
http.StatusGatewayTimeout)
return
}
debugf("validating cached response")
if h.validator.Validate(r, res) {
debugf("response is valid")
h.cache.Freshen(res, cReq.Key.String())
} else {
debugf("response is changed")
h.passUpstream(rw, cReq)
return
}
}
debugf("serving from cache")
res.Header().Set(CacheHeader, "HIT")
h.serveResource(res, rw, cReq)
if err := res.Close(); err != nil {
errorf("Error closing resource: %s", err.Error())
}
}
// freshness returns the duration that a requested resource will be fresh for
func (h *Handler) freshness(res *Resource, r *cacheRequest) (time.Duration, error) {
maxAge, err := res.MaxAge(h.Shared)
if err != nil {
return time.Duration(0), err
}
if r.CacheControl.Has("max-age") {
reqMaxAge, err := r.CacheControl.Duration("max-age")
if err != nil {
return time.Duration(0), err
}
if reqMaxAge < maxAge {
debugf("using request max-age of %s", reqMaxAge.String())
maxAge = reqMaxAge
}
}
age, err := res.Age()
if err != nil {
return time.Duration(0), err
}
if res.IsStale() {
return time.Duration(0), nil
}
if hFresh := res.HeuristicFreshness(); hFresh > maxAge {
debugf("using heuristic freshness of %q", hFresh)
maxAge = hFresh
}
return maxAge - age, nil
}
func (h *Handler) needsValidation(res *Resource, r *cacheRequest) bool {
if res.MustValidate(h.Shared) {
return true
}
freshness, err := h.freshness(res, r)
if err != nil {
debugf("error calculating freshness: %s", err.Error())
return true
}
if r.CacheControl.Has("min-fresh") {
reqMinFresh, err := r.CacheControl.Duration("min-fresh")
if err != nil {
debugf("error parsing request min-fresh: %s", err.Error())
return true
}
if freshness < reqMinFresh {
debugf("resource is fresh, but won't satisfy min-fresh of %s", reqMinFresh)
return true
}
}
debugf("resource has a freshness of %s", freshness)
if freshness <= 0 && r.CacheControl.Has("max-stale") {
if len(r.CacheControl["max-stale"]) == 0 {
debugf("resource is stale, but client sent max-stale")
return false
} else if maxStale, _ := r.CacheControl.Duration("max-stale"); maxStale >= (freshness * -1) {
log.Printf("resource is stale, but within allowed max-stale period of %s", maxStale)
return false
}
}
return freshness <= 0
}
// pipeUpstream makes the request via the upstream handler, the response is not stored or modified
func (h *Handler) pipeUpstream(w http.ResponseWriter, r *cacheRequest) {
rw := newResponseStreamer(w)
rdr, err := rw.Stream.NextReader()
if err != nil {
debugf("error creating next stream reader: %v", err)
w.Header().Set(CacheHeader, "SKIP")
h.upstream.ServeHTTP(w, r.Request)
return
}
defer rdr.Close()
debugf("piping request upstream")
go func() {
h.upstream.ServeHTTP(rw, r.Request)
rw.Stream.Close()
}()
rw.WaitHeaders()
if r.Method != "HEAD" && !r.isStateChanging() {
return
}
res := rw.Resource()
defer res.Close()
if r.Method == "HEAD" {
h.cache.Freshen(res, r.Key.ForMethod("GET").String())
} else if res.IsNonErrorStatus() {
h.invalidateResource(res, r)
}
}
// passUpstream makes the request via the upstream handler and stores the result
func (h *Handler) passUpstream(w http.ResponseWriter, r *cacheRequest) {
rw := newResponseStreamer(w)
rdr, err := rw.Stream.NextReader()
if err != nil {
debugf("error creating next stream reader: %v", err)
w.Header().Set(CacheHeader, "SKIP")
h.upstream.ServeHTTP(w, r.Request)
return
}
t := Clock()
debugf("passing request upstream")
rw.Header().Set(CacheHeader, "MISS")
go func() {
h.upstream.ServeHTTP(rw, r.Request)
rw.Stream.Close()
}()
rw.WaitHeaders()
debugf("upstream responded headers in %s", Clock().Sub(t).String())
// just the headers!
res := NewResourceBytes(rw.StatusCode, nil, rw.Header())
if !h.isCacheable(res, r) {
rdr.Close()
debugf("resource is uncacheable")
rw.Header().Set(CacheHeader, "SKIP")
return
}
b, err := ioutil.ReadAll(rdr)
rdr.Close()
if err != nil {
debugf("error reading stream: %v", err)
rw.Header().Set(CacheHeader, "SKIP")
return
}
debugf("full upstream response took %s", Clock().Sub(t).String())
res.ReadSeekCloser = &byteReadSeekCloser{bytes.NewReader(b)}
if age, err := correctedAge(res.Header(), t, Clock()); err == nil {
res.Header().Set("Age", strconv.Itoa(int(math.Ceil(age.Seconds()))))
} else {
debugf("error calculating corrected age: %s", err.Error())
}
rw.Header().Set(ProxyDateHeader, Clock().Format(http.TimeFormat))
h.storeResource(res, r)
}
// correctedAge adjusts the age of a resource for clock skew and travel time
// https://httpwg.github.io/specs/rfc7234.html#rfc.section.4.2.3
func correctedAge(h http.Header, reqTime, respTime time.Time) (time.Duration, error) {
date, err := timeHeader("Date", h)
if err != nil {
return time.Duration(0), err
}
apparentAge := respTime.Sub(date)
if apparentAge < 0 {
apparentAge = 0
}
respDelay := respTime.Sub(reqTime)
ageSeconds, err := intHeader("Age", h)
age := time.Second * time.Duration(ageSeconds)
correctedAge := age + respDelay
if apparentAge > correctedAge {
correctedAge = apparentAge
}
residentTime := Clock().Sub(respTime)
currentAge := correctedAge + residentTime
return currentAge, nil
}
func (h *Handler) isCacheable(res *Resource, r *cacheRequest) bool {
cc, err := res.cacheControl()
if err != nil {
errorf("Error parsing cache-control: %s", err.Error())
return false
}
if cc.Has("no-cache") || cc.Has("no-store") {
return false
}
if cc.Has("private") && len(cc["private"]) == 0 && h.Shared {
return false
}
if _, ok := storeable[res.Status()]; !ok {
return false
}
if r.Header.Get("Authorization") != "" && h.Shared {
return false
}
if res.Header().Get("Authorization") != "" && h.Shared &&
!cc.Has("must-revalidate") && !cc.Has("s-maxage") {
return false
}
if res.HasExplicitExpiration() {
return true
}
if _, ok := cacheableByDefault[res.Status()]; !ok && !cc.Has("public") {
return false
}
if res.HasValidators() {
return true
} else if res.HeuristicFreshness() > 0 {
return true
}
return false
}
func (h *Handler) serveResource(res *Resource, w http.ResponseWriter, req *cacheRequest) {
for key, headers := range res.Header() {
for _, header := range headers {
w.Header().Add(key, header)
}
}
age, err := res.Age()
if err != nil {
http.Error(w, "Error calculating age: "+err.Error(),
http.StatusInternalServerError)
return
}
// http://httpwg.github.io/specs/rfc7234.html#warn.113
if age > (time.Hour*24) && res.HeuristicFreshness() > (time.Hour*24) {
w.Header().Add("Warning", `113 - "Heuristic Expiration"`)
}
// http://httpwg.github.io/specs/rfc7234.html#warn.110
freshness, err := h.freshness(res, req)
if err != nil || freshness <= 0 {
w.Header().Add("Warning", `110 - "Response is Stale"`)
}
debugf("resource is %s old, updating age from %s",
age.String(), w.Header().Get("Age"))
w.Header().Set("Age", fmt.Sprintf("%.f", math.Floor(age.Seconds())))
w.Header().Set("Via", res.Via())
// hacky handler for non-ok statuses
if res.Status() != http.StatusOK {
w.WriteHeader(res.Status())
io.Copy(w, res)
} else {
http.ServeContent(w, req.Request, "", res.LastModified(), res)
}
}
func (h *Handler) invalidateResource(res *Resource, r *cacheRequest) {
Writes.Add(1)
go func() {
defer Writes.Done()
debugf("invalidating resource %+v", res)
}()
}
func (h *Handler) storeResource(res *Resource, r *cacheRequest) {
Writes.Add(1)
go func() {
defer Writes.Done()
t := Clock()
keys := []string{r.Key.String()}
headers := res.Header()
if h.Shared {
res.RemovePrivateHeaders()
}
// store a secondary vary version
if vary := headers.Get("Vary"); vary != "" {
keys = append(keys, r.Key.Vary(vary, r.Request).String())
}
if err := h.cache.Store(res, keys...); err != nil {
errorf("storing resources %#v failed with error: %s", keys, err.Error())
}
debugf("stored resources %+v in %s", keys, Clock().Sub(t))
}()
}
// lookupResource finds the best matching Resource for the
// request, or nil and ErrNotFoundInCache if none is found
func (h *Handler) lookup(req *cacheRequest) (*Resource, error) {
res, err := h.cache.Retrieve(req.Key.String())
// HEAD requests can possibly be served from GET
if err == ErrNotFoundInCache && req.Method == "HEAD" {
res, err = h.cache.Retrieve(req.Key.ForMethod("GET").String())
if err != nil {
return nil, err
}
if res.HasExplicitExpiration() && req.isCacheable() {
debugf("using cached GET request for serving HEAD")
return res, nil
} else {
return nil, ErrNotFoundInCache
}
} else if err != nil {
return res, err
}
// Secondary lookup for Vary
if vary := res.Header().Get("Vary"); vary != "" {
res, err = h.cache.Retrieve(req.Key.Vary(vary, req.Request).String())
if err != nil {
return res, err
}
}
return res, nil
}
type cacheRequest struct {
*http.Request
Key Key
Time time.Time
CacheControl CacheControl
}
func newCacheRequest(r *http.Request) (*cacheRequest, error) {
cc, err := ParseCacheControl(r.Header.Get("Cache-Control"))
if err != nil {
return nil, err
}
if r.Proto == "HTTP/1.1" && r.Host == "" {
return nil, errors.New("Host header can't be empty")
}
return &cacheRequest{
Request: r,
Key: NewRequestKey(r),
Time: Clock(),
CacheControl: cc,
}, nil
}
func (r *cacheRequest) isStateChanging() bool {
if !(r.Method == "POST" || r.Method == "PUT" || r.Method == "DELETE") {
return true
}
return false
}
func (r *cacheRequest) isCacheable() bool {
if !(r.Method == "GET" || r.Method == "HEAD") {
return false
}
if r.Header.Get("If-Match") != "" ||
r.Header.Get("If-Unmodified-Since") != "" ||
r.Header.Get("If-Range") != "" {
return false
}
if maxAge, ok := r.CacheControl.Get("max-age"); ok && maxAge == "0" {
return false
}
if r.CacheControl.Has("no-store") || r.CacheControl.Has("no-cache") {
return false
}
return true
}
func newResponseStreamer(w http.ResponseWriter) *responseStreamer {
strm, err := stream.NewStream("responseBuffer", stream.NewMemFS())
if err != nil {
panic(err)
}
return &responseStreamer{
ResponseWriter: w,
Stream: strm,
C: make(chan struct{}),
}
}
type responseStreamer struct {
StatusCode int
http.ResponseWriter
*stream.Stream
// C will be closed by WriteHeader to signal the headers' writing.
C chan struct{}
}
// WaitHeaders returns iff and when WriteHeader has been called.
func (rw *responseStreamer) WaitHeaders() {
for range rw.C {
}
}
func (rw *responseStreamer) WriteHeader(status int) {
defer close(rw.C)
rw.StatusCode = status
rw.ResponseWriter.WriteHeader(status)
}
func (rw *responseStreamer) Write(b []byte) (int, error) {
rw.Stream.Write(b)
return rw.ResponseWriter.Write(b)
}
func (rw *responseStreamer) Close() error {
return rw.Stream.Close()
}
// Resource returns a copy of the responseStreamer as a Resource object
func (rw *responseStreamer) Resource() *Resource {
r, err := rw.Stream.NextReader()
if err == nil {
b, err := ioutil.ReadAll(r)
r.Close()
if err == nil {
return NewResourceBytes(rw.StatusCode, b, rw.Header())
}
}
return &Resource{
header: rw.Header(),
statusCode: rw.StatusCode,
ReadSeekCloser: errReadSeekCloser{err},
}
}
type errReadSeekCloser struct {
err error
}
func (e errReadSeekCloser) Error() string {
return e.err.Error()
}
func (e errReadSeekCloser) Close() error { return e.err }
func (e errReadSeekCloser) Read(_ []byte) (int, error) { return 0, e.err }
func (e errReadSeekCloser) Seek(_ int64, _ int) (int64, error) { return 0, e.err }
================================================
FILE: header.go
================================================
package httpcache
import (
"errors"
"net/http"
"strconv"
"time"
)
var errNoHeader = errors.New("Header doesn't exist")
func timeHeader(key string, h http.Header) (time.Time, error) {
if header := h.Get(key); header != "" {
return http.ParseTime(header)
} else {
return time.Time{}, errNoHeader
}
}
func intHeader(key string, h http.Header) (int, error) {
if header := h.Get(key); header != "" {
return strconv.Atoi(header)
} else {
return 0, errNoHeader
}
}
================================================
FILE: httplog/log.go
================================================
package httplog
import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"net/http/httputil"
"os"
"strings"
"time"
)
const (
CacheHeader = "X-Cache"
)
type responseWriter struct {
http.ResponseWriter
status int
size int
t time.Time
errorOutput bytes.Buffer
}
func (l *responseWriter) Header() http.Header {
return l.ResponseWriter.Header()
}
func (l *responseWriter) Write(b []byte) (int, error) {
if l.status == 0 {
l.status = http.StatusOK
}
if isError(l.status) {
l.errorOutput.Write(b)
}
size, err := l.ResponseWriter.Write(b)
l.size += size
return size, err
}
func (l *responseWriter) WriteHeader(s int) {
l.ResponseWriter.WriteHeader(s)
l.status = s
}
func (l *responseWriter) Status() int {
return l.status
}
func (l *responseWriter) Size() int {
return l.size
}
func NewResponseLogger(delegate http.Handler) *ResponseLogger {
return &ResponseLogger{Handler: delegate}
}
type ResponseLogger struct {
http.Handler
DumpRequests, DumpErrors, DumpResponses bool
}
func (l *ResponseLogger) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if l.DumpRequests {
b, _ := httputil.DumpRequest(req, false)
writePrefixString(strings.TrimSpace(string(b)), ">> ", os.Stderr)
}
respWr := &responseWriter{ResponseWriter: w, t: time.Now()}
l.Handler.ServeHTTP(respWr, req)
if l.DumpResponses {
buf := &bytes.Buffer{}
buf.WriteString(fmt.Sprintf("HTTP/1.1 %d %s\r\n",
respWr.status, http.StatusText(respWr.status),
))
respWr.Header().Write(buf)
writePrefixString(strings.TrimSpace(buf.String()), "<< ", os.Stderr)
}
if l.DumpErrors && isError(respWr.status) {
writePrefixString(respWr.errorOutput.String(), "<< ", os.Stderr)
}
l.writeLog(req, respWr)
}
func (l *ResponseLogger) writeLog(req *http.Request, respWr *responseWriter) {
cacheStatus := respWr.Header().Get(CacheHeader)
if strings.HasPrefix(cacheStatus, "HIT") {
cacheStatus = "\x1b[32;1mHIT\x1b[0m"
} else if strings.HasPrefix(cacheStatus, "MISS") {
cacheStatus = "\x1b[31;1mMISS\x1b[0m"
} else {
cacheStatus = "\x1b[33;1mSKIP\x1b[0m"
}
clientIP := req.RemoteAddr
if colon := strings.LastIndex(clientIP, ":"); colon != -1 {
clientIP = clientIP[:colon]
}
log.Printf(
"%s \"%s %s %s\" (%s) %d %s %s",
clientIP,
req.Method,
req.URL.String(),
req.Proto,
http.StatusText(respWr.status),
respWr.size,
cacheStatus,
time.Now().Sub(respWr.t).String(),
)
}
func isError(code int) bool {
return code >= 500
}
func writePrefixString(s, prefix string, w io.Writer) {
os.Stderr.Write([]byte("\n"))
for _, line := range strings.Split(s, "\r\n") {
w.Write([]byte(prefix))
w.Write([]byte(line))
w.Write([]byte("\n"))
}
os.Stderr.Write([]byte("\n"))
}
================================================
FILE: key.go
================================================
package httpcache
import (
"bytes"
"fmt"
"net/http"
"net/url"
"strings"
)
// Key represents a unique identifier for a resource in the cache
type Key struct {
method string
header http.Header
u url.URL
vary []string
}
// NewKey returns a new Key instance
func NewKey(method string, u *url.URL, h http.Header) Key {
return Key{method: method, header: h, u: *u, vary: []string{}}
}
// NewRequestKey generates a Key for a request
func NewRequestKey(r *http.Request) Key {
URL := r.URL
if location := r.Header.Get("Content-Location"); location != "" {
u, err := url.Parse(location)
if err == nil {
if !u.IsAbs() {
u = r.URL.ResolveReference(u)
}
if u.Host != r.Host {
debugf("illegal host %q in Content-Location", u.Host)
} else {
debugf("using Content-Location: %q", u.String())
URL = u
}
} else {
debugf("failed to parse Content-Location %q", location)
}
}
return NewKey(r.Method, URL, r.Header)
}
// ForMethod returns a new Key with a given method
func (k Key) ForMethod(method string) Key {
k2 := k
k2.method = method
return k2
}
// Vary returns a Key that is varied on particular headers in a http.Request
func (k Key) Vary(varyHeader string, r *http.Request) Key {
k2 := k
for _, header := range strings.Split(varyHeader, ", ") {
k2.vary = append(k2.vary, header+"="+r.Header.Get(header))
}
return k2
}
func (k Key) String() string {
URL := strings.ToLower(canonicalURL(&k.u).String())
b := &bytes.Buffer{}
b.WriteString(fmt.Sprintf("%s:%s", k.method, URL))
if len(k.vary) > 0 {
b.WriteString("::")
for _, v := range k.vary {
b.WriteString(v + ":")
}
}
return b.String()
}
func canonicalURL(u *url.URL) *url.URL {
return u
}
================================================
FILE: key_test.go
================================================
package httpcache_test
import (
"net/url"
"testing"
"github.com/lox/httpcache"
"github.com/stretchr/testify/assert"
)
func mustParseUrl(u string) *url.URL {
ru, err := url.Parse(u)
if err != nil {
panic(err)
}
return ru
}
func TestKeysDiffer(t *testing.T) {
k1 := httpcache.NewKey("GET", mustParseUrl("http://x.org/test"), nil)
k2 := httpcache.NewKey("GET", mustParseUrl("http://y.org/test"), nil)
assert.NotEqual(t, k1.String(), k2.String())
}
func TestRequestKey(t *testing.T) {
r := newRequest("GET", "http://x.org/test")
k1 := httpcache.NewKey("GET", mustParseUrl("http://x.org/test"), nil)
k2 := httpcache.NewRequestKey(r)
assert.Equal(t, k1.String(), k2.String())
}
func TestVaryKey(t *testing.T) {
r := newRequest("GET", "http://x.org/test", "Llamas-1: true", "Llamas-2: false")
k1 := httpcache.NewRequestKey(r)
k2 := httpcache.NewRequestKey(r).Vary("Llamas-1, Llamas-2", r)
assert.NotEqual(t, k1.String(), k2.String())
}
func TestRequestKeyWithContentLocation(t *testing.T) {
r := newRequest("GET", "http://x.org/test1", "Content-Location: http://x.org/test2")
k1 := httpcache.NewKey("GET", mustParseUrl("http://x.org/test2"), nil)
k2 := httpcache.NewRequestKey(r)
assert.Equal(t, k1.String(), k2.String())
}
func TestRequestKeyWithIllegalContentLocation(t *testing.T) {
r := newRequest("GET", "http://x.org/test1", "Content-Location: http://y.org/test2")
k1 := httpcache.NewKey("GET", mustParseUrl("http://x.org/test1"), nil)
k2 := httpcache.NewRequestKey(r)
assert.Equal(t, k1.String(), k2.String())
}
================================================
FILE: logger.go
================================================
package httpcache
import "log"
const (
ansiRed = "\x1b[31;1m"
ansiReset = "\x1b[0m"
)
var DebugLogging = false
func debugf(format string, args ...interface{}) {
if DebugLogging {
log.Printf(format, args...)
}
}
func errorf(format string, args ...interface{}) {
log.Printf(ansiRed+"✗ "+format+ansiReset, args)
}
================================================
FILE: resource.go
================================================
package httpcache
import (
"bytes"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
)
const (
lastModDivisor = 10
viaPseudonym = "httpcache"
)
var Clock = func() time.Time {
return time.Now().UTC()
}
type ReadSeekCloser interface {
io.Reader
io.Seeker
io.Closer
}
type byteReadSeekCloser struct {
*bytes.Reader
}
func (brsc *byteReadSeekCloser) Close() error { return nil }
type Resource struct {
ReadSeekCloser
RequestTime, ResponseTime time.Time
header http.Header
statusCode int
cc CacheControl
stale bool
}
func NewResource(statusCode int, body ReadSeekCloser, hdrs http.Header) *Resource {
return &Resource{
header: hdrs,
ReadSeekCloser: body,
statusCode: statusCode,
}
}
func NewResourceBytes(statusCode int, b []byte, hdrs http.Header) *Resource {
return &Resource{
header: hdrs,
statusCode: statusCode,
ReadSeekCloser: &byteReadSeekCloser{bytes.NewReader(b)},
}
}
func (r *Resource) IsNonErrorStatus() bool {
return r.statusCode >= 200 && r.statusCode < 400
}
func (r *Resource) Status() int {
return r.statusCode
}
func (r *Resource) Header() http.Header {
return r.header
}
func (r *Resource) IsStale() bool {
return r.stale
}
func (r *Resource) MarkStale() {
r.stale = true
}
func (r *Resource) cacheControl() (CacheControl, error) {
if r.cc != nil {
return r.cc, nil
}
cc, err := ParseCacheControlHeaders(r.header)
if err != nil {
return cc, err
}
r.cc = cc
return cc, nil
}
func (r *Resource) LastModified() time.Time {
var modTime time.Time
if lastModHeader := r.header.Get("Last-Modified"); lastModHeader != "" {
if t, err := http.ParseTime(lastModHeader); err == nil {
modTime = t
}
}
return modTime
}
func (r *Resource) Expires() (time.Time, error) {
if expires := r.header.Get("Expires"); expires != "" {
return http.ParseTime(expires)
}
return time.Time{}, nil
}
func (r *Resource) MustValidate(shared bool) bool {
cc, err := r.cacheControl()
if err != nil {
debugf("Error parsing Cache-Control: ", err.Error())
return true
}
// The s-maxage directive also implies the semantics of proxy-revalidate
if cc.Has("s-maxage") && shared {
return true
}
if cc.Has("must-revalidate") || (cc.Has("proxy-revalidate") && shared) {
return true
}
return false
}
func (r *Resource) DateAfter(d time.Time) bool {
if dateHeader := r.header.Get("Date"); dateHeader != "" {
if t, err := http.ParseTime(dateHeader); err != nil {
return false
} else {
return t.After(d)
}
}
return false
}
// Calculate the age of the resource
func (r *Resource) Age() (time.Duration, error) {
var age time.Duration
if ageInt, err := intHeader("Age", r.header); err == nil {
age = time.Second * time.Duration(ageInt)
}
if proxyDate, err := timeHeader(ProxyDateHeader, r.header); err == nil {
return Clock().Sub(proxyDate) + age, nil
}
if date, err := timeHeader("Date", r.header); err == nil {
return Clock().Sub(date) + age, nil
}
return time.Duration(0), errors.New("Unable to calculate age")
}
func (r *Resource) MaxAge(shared bool) (time.Duration, error) {
cc, err := r.cacheControl()
if err != nil {
return time.Duration(0), err
}
if cc.Has("s-maxage") && shared {
if maxAge, err := cc.Duration("s-maxage"); err != nil {
return time.Duration(0), err
} else if maxAge > 0 {
return maxAge, nil
}
}
if cc.Has("max-age") {
if maxAge, err := cc.Duration("max-age"); err != nil {
return time.Duration(0), err
} else if maxAge > 0 {
return maxAge, nil
}
}
if expiresVal := r.header.Get("Expires"); expiresVal != "" {
expires, err := http.ParseTime(expiresVal)
if err != nil {
return time.Duration(0), err
}
return expires.Sub(Clock()), nil
}
return time.Duration(0), nil
}
func (r *Resource) RemovePrivateHeaders() {
cc, err := r.cacheControl()
if err != nil {
debugf("Error parsing Cache-Control: %s", err.Error())
}
for _, p := range cc["private"] {
debugf("removing private header %q", p)
r.header.Del(p)
}
}
func (r *Resource) HasValidators() bool {
if r.header.Get("Last-Modified") != "" || r.header.Get("Etag") != "" {
return true
}
return false
}
func (r *Resource) HasExplicitExpiration() bool {
cc, err := r.cacheControl()
if err != nil {
debugf("Error parsing Cache-Control: %s", err.Error())
return false
}
if d, _ := cc.Duration("max-age"); d > time.Duration(0) {
return true
}
if d, _ := cc.Duration("s-maxage"); d > time.Duration(0) {
return true
}
if exp, _ := r.Expires(); !exp.IsZero() {
return true
}
return false
}
func (r *Resource) HeuristicFreshness() time.Duration {
if !r.HasExplicitExpiration() && r.header.Get("Last-Modified") != "" {
return Clock().Sub(r.LastModified()) / time.Duration(lastModDivisor)
}
return time.Duration(0)
}
func (r *Resource) Via() string {
via := []string{}
via = append(via, fmt.Sprintf("1.1 %s", viaPseudonym))
return strings.Join(via, ",")
}
================================================
FILE: spec_test.go
================================================
package httpcache_test
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"testing"
"time"
"github.com/lox/httpcache"
"github.com/lox/httpcache/httplog"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func testSetup() (*client, *upstreamServer) {
upstream := &upstreamServer{
Body: []byte("llamas"),
asserts: []func(r *http.Request){},
Now: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),
Header: http.Header{},
}
httpcache.Clock = func() time.Time {
return upstream.Now
}
cacheHandler := httpcache.NewHandler(
httpcache.NewMemoryCache(),
upstream,
)
var handler http.Handler = cacheHandler
if testing.Verbose() {
rlogger := httplog.NewResponseLogger(cacheHandler)
rlogger.DumpRequests = true
rlogger.DumpResponses = true
handler = rlogger
httpcache.DebugLogging = true
} else {
log.SetOutput(ioutil.Discard)
}
return &client{handler, cacheHandler}, upstream
}
func TestSpecResponseCacheControl(t *testing.T) {
var cases = []struct {
cacheControl string
cacheStatus string
requests int
secondsElapsed time.Duration
shared bool
}{
{cacheControl: "", requests: 2},
{cacheControl: "no-cache", requests: 2, cacheStatus: "SKIP"},
{cacheControl: "no-store", requests: 2, cacheStatus: "SKIP"},
{cacheControl: "max-age=0, no-cache", requests: 2, cacheStatus: "SKIP"},
{cacheControl: "max-age=0", requests: 2, cacheStatus: "SKIP"},
{cacheControl: "s-maxage=0", requests: 2, cacheStatus: "SKIP", shared: true},
{cacheControl: "s-maxage=60", requests: 2, cacheStatus: "HIT", shared: true},
{cacheControl: "s-maxage=60", requests: 2, secondsElapsed: 65, shared: true},
{cacheControl: "max-age=60", requests: 1, cacheStatus: "HIT"},
{cacheControl: "max-age=60", requests: 1, secondsElapsed: 35, cacheStatus: "HIT"},
{cacheControl: "max-age=60", requests: 2, secondsElapsed: 65},
{cacheControl: "max-age=60, must-revalidate", requests: 2, cacheStatus: "HIT"},
{cacheControl: "max-age=60, proxy-revalidate", requests: 1, cacheStatus: "HIT"},
{cacheControl: "max-age=60, proxy-revalidate", requests: 2, cacheStatus: "HIT", shared: true},
{cacheControl: "private, max-age=60", requests: 1, cacheStatus: "HIT"},
{cacheControl: "private, max-age=60", requests: 2, cacheStatus: "SKIP", shared: true},
}
for idx, c := range cases {
client, upstream := testSetup()
upstream.CacheControl = c.cacheControl
client.cacheHandler.Shared = c.shared
assert.Equal(t, http.StatusOK, client.get("/").Code)
upstream.timeTravel(time.Second * time.Duration(c.secondsElapsed))
r := client.get("/")
assert.Equal(t, http.StatusOK, r.statusCode)
require.Equal(t, c.requests, upstream.requests,
fmt.Sprintf("case #%d failed, %+v", idx+1, c))
if c.cacheStatus != "" {
require.Equal(t, c.cacheStatus, r.cacheStatus,
fmt.Sprintf("case #%d failed, %+v", idx+1, c))
}
}
}
func TestSpecResponseCacheControlWithPrivateHeaders(t *testing.T) {
client, upstream := testSetup()
client.cacheHandler.Shared = false
upstream.CacheControl = `max-age=10, private=X-Llamas, private=Set-Cookie"`
upstream.Header.Add("X-Llamas", "fully")
upstream.Header.Add("Set-Cookie", "llamas=true")
assert.Equal(t, http.StatusOK, client.get("/r1").Code)
r1 := client.get("/r1")
assert.Equal(t, http.StatusOK, r1.statusCode)
assert.Equal(t, "HIT", r1.cacheStatus)
assert.Equal(t, "fully", r1.HeaderMap.Get("X-Llamas"))
assert.Equal(t, "llamas=true", r1.HeaderMap.Get("Set-Cookie"))
assert.Equal(t, 1, upstream.requests)
client.cacheHandler.Shared = true
assert.Equal(t, http.StatusOK, client.get("/r2").Code)
r2 := client.get("/r2")
assert.Equal(t, http.StatusOK, r1.statusCode)
assert.Equal(t, "HIT", r2.cacheStatus)
assert.Equal(t, "", r2.HeaderMap.Get("X-Llamas"))
assert.Equal(t, "", r2.HeaderMap.Get("Set-Cookie"))
assert.Equal(t, 2, upstream.requests)
}
func TestSpecResponseCacheControlWithAuthorizationHeaders(t *testing.T) {
client, upstream := testSetup()
client.cacheHandler.Shared = true
upstream.CacheControl = `max-age=10`
upstream.Header.Add("Authorization", "fully")
assert.Equal(t, http.StatusOK, client.get("/r1").Code)
r1 := client.get("/r1")
assert.Equal(t, http.StatusOK, r1.statusCode)
assert.Equal(t, "SKIP", r1.cacheStatus)
assert.Equal(t, "fully", r1.HeaderMap.Get("Authorization"))
assert.Equal(t, 2, upstream.requests)
client.cacheHandler.Shared = false
assert.Equal(t, http.StatusOK, client.get("/r2").Code)
r3 := client.get("/r2")
assert.Equal(t, http.StatusOK, r3.statusCode)
assert.Equal(t, "HIT", r3.cacheStatus)
assert.Equal(t, "fully", r3.HeaderMap.Get("Authorization"))
assert.Equal(t, 3, upstream.requests)
}
func TestSpecRequestCacheControl(t *testing.T) {
var cases = []struct {
cacheControl string
cacheStatus string
requests int
secondsElapsed time.Duration
}{
{cacheControl: "", requests: 1},
{cacheControl: "no-cache", requests: 2},
{cacheControl: "no-store", requests: 2},
{cacheControl: "max-age=0", requests: 2},
{cacheControl: "max-stale", requests: 1, secondsElapsed: 65},
{cacheControl: "max-stale=0", requests: 2, secondsElapsed: 65},
{cacheControl: "max-stale=60", requests: 1, secondsElapsed: 65},
{cacheControl: "max-stale=60", requests: 1, secondsElapsed: 65},
{cacheControl: "max-age=30", requests: 2, secondsElapsed: 40},
{cacheControl: "min-fresh=5", requests: 1},
{cacheControl: "min-fresh=120", requests: 2},
}
for idx, c := range cases {
client, upstream := testSetup()
upstream.CacheControl = "max-age=60"
assert.Equal(t, http.StatusOK, client.get("/").Code)
upstream.timeTravel(time.Second * time.Duration(c.secondsElapsed))
r := client.get("/", "Cache-Control: "+c.cacheControl)
assert.Equal(t, http.StatusOK, r.statusCode)
assert.Equal(t, c.requests, upstream.requests,
fmt.Sprintf("case #%d failed, %+v", idx+1, c))
}
}
func TestSpecRequestCacheControlWithOnlyIfCached(t *testing.T) {
client, upstream := testSetup()
upstream.CacheControl = "max-age=10"
assert.Equal(t, http.StatusOK, client.get("/").Code)
assert.Equal(t, http.StatusOK, client.get("/").Code)
upstream.timeTravel(time.Second * 20)
assert.Equal(t, http.StatusGatewayTimeout,
client.get("/", "Cache-Control: only-if-cached").Code)
assert.Equal(t, 1, upstream.requests)
}
func TestSpecCachingStatusCodes(t *testing.T) {
client, upstream := testSetup()
upstream.StatusCode = http.StatusNotFound
upstream.CacheControl = "public, max-age=60"
r1 := client.get("/r1")
assert.Equal(t, http.StatusNotFound, r1.statusCode)
assert.Equal(t, "MISS", r1.cacheStatus)
assert.Equal(t, string(upstream.Body), string(r1.body))
upstream.timeTravel(time.Second * 10)
r2 := client.get("/r1")
assert.Equal(t, http.StatusNotFound, r2.statusCode)
assert.Equal(t, "HIT", r2.cacheStatus)
assert.Equal(t, string(upstream.Body), string(r2.body))
assert.Equal(t, time.Second*10, r2.age)
upstream.StatusCode = http.StatusPaymentRequired
r3 := client.get("/r2")
assert.Equal(t, http.StatusPaymentRequired, r3.statusCode)
assert.Equal(t, "SKIP", r3.cacheStatus)
}
func TestSpecConditionalCaching(t *testing.T) {
client, upstream := testSetup()
upstream.Etag = `"llamas"`
r1 := client.get("/")
assert.Equal(t, "MISS", r1.cacheStatus)
assert.Equal(t, string(upstream.Body), string(r1.body))
r2 := client.get("/", `If-None-Match: "llamas"`)
assert.Equal(t, http.StatusNotModified, r2.Code)
assert.Equal(t, "", string(r2.body))
assert.Equal(t, "HIT", r2.cacheStatus)
}
func TestSpecRangeRequests(t *testing.T) {
client, upstream := testSetup()
r1 := client.get("/", "Range: bytes=0-3")
assert.Equal(t, http.StatusPartialContent, r1.Code)
assert.Equal(t, "SKIP", r1.cacheStatus)
assert.Equal(t, string(upstream.Body[0:4]), string(r1.body))
}
func TestSpecHeuristicCaching(t *testing.T) {
client, upstream := testSetup()
upstream.LastModified = upstream.Now.AddDate(-1, 0, 0)
assert.Equal(t, "MISS", client.get("/").cacheStatus)
upstream.timeTravel(time.Hour * 48)
r2 := client.get("/")
assert.Equal(t, "HIT", r2.cacheStatus)
assert.Equal(t, []string{"113 - \"Heuristic Expiration\""}, r2.Header()["Warning"])
assert.Equal(t, 1, upstream.requests, "The second request shouldn't validate")
}
func TestSpecCacheControlTrumpsExpires(t *testing.T) {
client, upstream := testSetup()
upstream.LastModified = upstream.Now.AddDate(-1, 0, 0)
upstream.CacheControl = "max-age=2"
assert.Equal(t, "MISS", client.get("/").cacheStatus)
assert.Equal(t, "HIT", client.get("/").cacheStatus)
assert.Equal(t, 1, upstream.requests)
upstream.timeTravel(time.Hour * 48)
assert.Equal(t, "HIT", client.get("/").cacheStatus)
assert.Equal(t, 2, upstream.requests)
}
func TestSpecNotCachedWithoutValidatorOrExpiration(t *testing.T) {
client, upstream := testSetup()
upstream.LastModified = time.Time{}
upstream.Etag = ""
assert.Equal(t, "SKIP", client.get("/").cacheStatus)
assert.Equal(t, "SKIP", client.get("/").cacheStatus)
assert.Equal(t, 2, upstream.requests)
}
func TestSpecNoCachingForInvalidExpires(t *testing.T) {
client, upstream := testSetup()
upstream.LastModified = time.Time{}
upstream.Header.Set("Expires", "-1")
assert.Equal(t, "SKIP", client.get("/").cacheStatus)
}
func TestSpecRequestsWithoutHostHeader(t *testing.T) {
client, _ := testSetup()
r := newRequest("GET", "http://example.org")
r.Header.Del("Host")
r.Host = ""
resp := client.do(r)
assert.Equal(t, http.StatusBadRequest, resp.Code,
"Requests without a Host header should result in a 400")
}
func TestSpecCacheControlMaxStale(t *testing.T) {
client, upstream := testSetup()
upstream.CacheControl = "max-age=60"
assert.Equal(t, "MISS", client.get("/").cacheStatus)
upstream.timeTravel(time.Second * 90)
upstream.Body = []byte("brand new content")
r2 := client.get("/", "Cache-Control: max-stale=3600")
assert.Equal(t, "HIT", r2.cacheStatus)
assert.Equal(t, time.Second*90, r2.age)
upstream.timeTravel(time.Second * 90)
r3 := client.get("/")
assert.Equal(t, "MISS", r3.cacheStatus)
assert.Equal(t, time.Duration(0), r3.age)
}
func TestSpecValidatingStaleResponsesUnchanged(t *testing.T) {
client, upstream := testSetup()
upstream.CacheControl = "max-age=60"
upstream.Etag = "llamas1"
assert.Equal(t, "MISS", client.get("/").cacheStatus)
upstream.timeTravel(time.Second * 90)
upstream.Header.Add("X-New-Header", "1")
r2 := client.get("/")
assert.Equal(t, http.StatusOK, r2.Code)
assert.Equal(t, string(upstream.Body), string(r2.body))
assert.Equal(t, "HIT", r2.cacheStatus)
}
func TestSpecValidatingStaleResponsesWithNewContent(t *testing.T) {
client, upstream := testSetup()
upstream.CacheControl = "max-age=60"
assert.Equal(t, "MISS", client.get("/").cacheStatus)
upstream.timeTravel(time.Second * 90)
upstream.Body = []byte("brand new content")
r2 := client.get("/")
assert.Equal(t, http.StatusOK, r2.Code)
assert.Equal(t, "MISS", r2.cacheStatus)
assert.Equal(t, "brand new content", string(r2.body))
assert.Equal(t, time.Duration(0), r2.age)
}
func TestSpecValidatingStaleResponsesWithNewEtag(t *testing.T) {
client, upstream := testSetup()
upstream.CacheControl = "max-age=60"
upstream.Etag = "llamas1"
assert.Equal(t, "MISS", client.get("/").cacheStatus)
upstream.timeTravel(time.Second * 90)
upstream.Etag = "llamas2"
r2 := client.get("/")
assert.Equal(t, http.StatusOK, r2.Code)
assert.Equal(t, "MISS", r2.cacheStatus)
}
func TestSpecVaryHeader(t *testing.T) {
client, upstream := testSetup()
upstream.CacheControl = "max-age=60"
upstream.Vary = "Accept-Language"
upstream.Etag = "llamas"
assert.Equal(t, "MISS", client.get("/", "Accept-Language: en").cacheStatus)
assert.Equal(t, "HIT", client.get("/", "Accept-Language: en").cacheStatus)
assert.Equal(t, "MISS", client.get("/", "Accept-Language: de").cacheStatus)
assert.Equal(t, "HIT", client.get("/", "Accept-Language: de").cacheStatus)
}
func TestSpecHeadersPropagated(t *testing.T) {
client, upstream := testSetup()
upstream.CacheControl = "max-age=60"
upstream.Header.Add("X-Llamas", "1")
upstream.Header.Add("X-Llamas", "3")
upstream.Header.Add("X-Llamas", "2")
assert.Equal(t, "MISS", client.get("/").cacheStatus)
r2 := client.get("/")
assert.Equal(t, "HIT", r2.cacheStatus)
assert.Equal(t, []string{"1", "3", "2"}, r2.Header()["X-Llamas"])
}
func TestSpecAgeHeaderFromUpstream(t *testing.T) {
client, upstream := testSetup()
upstream.CacheControl = "max-age=86400"
upstream.Header.Set("Age", "3600") //1hr
assert.Equal(t, time.Hour, client.get("/").age)
upstream.timeTravel(time.Hour * 2)
assert.Equal(t, time.Hour*3, client.get("/").age)
}
func TestSpecAgeHeaderWithResponseDelay(t *testing.T) {
client, upstream := testSetup()
upstream.CacheControl = "max-age=86400"
upstream.Header.Set("Age", "3600") //1hr
upstream.ResponseDuration = time.Second * 2
assert.Equal(t, time.Second*3602, client.get("/").age)
upstream.timeTravel(time.Second * 60)
assert.Equal(t, time.Second*3662, client.get("/").age)
assert.Equal(t, 1, upstream.requests)
}
func TestSpecAgeHeaderGeneratedWhereNoneExists(t *testing.T) {
client, upstream := testSetup()
upstream.CacheControl = "max-age=86400"
upstream.ResponseDuration = time.Second * 2
assert.Equal(t, time.Second*2, client.get("/").age)
upstream.timeTravel(time.Second * 60)
assert.Equal(t, time.Second*62, client.get("/").age)
assert.Equal(t, 1, upstream.requests)
}
func TestSpecWarningForOldContent(t *testing.T) {
client, upstream := testSetup()
upstream.LastModified = upstream.Now.AddDate(-1, 0, 0)
assert.Equal(t, "MISS", client.get("/").cacheStatus)
upstream.timeTravel(time.Hour * 48)
r2 := client.get("/")
assert.Equal(t, "HIT", r2.cacheStatus)
assert.Equal(t, []string{"113 - \"Heuristic Expiration\""}, r2.Header()["Warning"])
}
func TestSpecHeadCanBeServedFromCacheOnlyWithExplicitFreshness(t *testing.T) {
client, upstream := testSetup()
upstream.CacheControl = "max-age=3600"
assert.Equal(t, "MISS", client.get("/explicit").cacheStatus)
assert.Equal(t, "HIT", client.head("/explicit").cacheStatus)
assert.Equal(t, "HIT", client.head("/explicit").cacheStatus)
upstream.CacheControl = ""
assert.Equal(t, "SKIP", client.get("/implicit").cacheStatus)
assert.Equal(t, "SKIP", client.head("/implicit").cacheStatus)
assert.Equal(t, "SKIP", client.head("/implicit").cacheStatus)
}
func TestSpecInvalidatingGetWithHeadRequest(t *testing.T) {
client, upstream := testSetup()
upstream.CacheControl = "max-age=3600"
assert.Equal(t, "MISS", client.get("/explicit").cacheStatus)
upstream.Body = []byte("brand new content")
assert.Equal(t, "SKIP", client.head("/explicit", "Cache-Control: max-age=0").cacheStatus)
assert.Equal(t, "MISS", client.get("/explicit").cacheStatus)
}
func TestSpecFresheningGetWithHeadRequest(t *testing.T) {
client, upstream := testSetup()
upstream.CacheControl = "max-age=3600"
assert.Equal(t, "MISS", client.get("/explicit").cacheStatus)
upstream.timeTravel(time.Second * 10)
assert.Equal(t, 10*time.Second, client.get("/explicit").age)
upstream.Header.Add("X-Llamas", "llamas")
assert.Equal(t, "SKIP", client.head("/explicit", "Cache-Control: max-age=0").cacheStatus)
refreshed := client.get("/explicit")
assert.Equal(t, "HIT", refreshed.cacheStatus)
assert.Equal(t, time.Duration(0), refreshed.age)
assert.Equal(t, "llamas", refreshed.header.Get("X-Llamas"))
}
func TestSpecContentHeaderInRequestRespected(t *testing.T) {
client, upstream := testSetup()
upstream.CacheControl = "max-age=3600"
r1 := client.get("/llamas/rock")
assert.Equal(t, "MISS", r1.cacheStatus)
assert.Equal(t, string(upstream.Body), string(r1.body))
r2 := client.get("/another/llamas", "Content-Location: /llamas/rock")
assert.Equal(t, "HIT", r2.cacheStatus)
assert.Equal(t, string(upstream.Body), string(r2.body))
}
func TestSpecMultipleCacheControlHeaders(t *testing.T) {
client, upstream := testSetup()
upstream.Header.Add("Cache-Control", "max-age=60, max-stale=10")
upstream.Header.Add("Cache-Control", "no-cache")
r1 := client.get("/")
assert.Equal(t, "SKIP", r1.cacheStatus)
}
================================================
FILE: util_test.go
================================================
package httpcache_test
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"time"
"github.com/lox/httpcache"
)
func newRequest(method, url string, h ...string) *http.Request {
req, err := http.NewRequest(method, url, strings.NewReader(""))
if err != nil {
panic(err)
}
req.Header = parseHeaders(h)
req.RemoteAddr = "test.local"
return req
}
func newResponse(status int, body []byte, h ...string) *http.Response {
return &http.Response{
Status: fmt.Sprintf("%d %s", status, http.StatusText(status)),
StatusCode: status,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
ContentLength: int64(len(body)),
Body: ioutil.NopCloser(bytes.NewReader(body)),
Header: parseHeaders(h),
Close: true,
}
}
func parseHeaders(input []string) http.Header {
headers := http.Header{}
for _, header := range input {
if idx := strings.Index(header, ": "); idx != -1 {
headers.Add(header[0:idx], strings.TrimSpace(header[idx+1:]))
}
}
return headers
}
type client struct {
handler http.Handler
cacheHandler *httpcache.Handler
}
func (c *client) do(r *http.Request) *clientResponse {
rec := httptest.NewRecorder()
c.handler.ServeHTTP(rec, r)
rec.Flush()
var age int
var err error
if ageHeader := rec.HeaderMap.Get("Age"); ageHeader != "" {
age, err = strconv.Atoi(ageHeader)
if err != nil {
panic("Can't parse age header")
}
}
// wait for writes to finish
httpcache.Writes.Wait()
return &clientResponse{
ResponseRecorder: rec,
cacheStatus: rec.HeaderMap.Get(httpcache.CacheHeader),
statusCode: rec.Code,
age: time.Second * time.Duration(age),
body: rec.Body.Bytes(),
header: rec.HeaderMap,
}
}
func (c *client) get(path string, headers ...string) *clientResponse {
return c.do(newRequest("GET", "http://example.org"+path, headers...))
}
func (c *client) head(path string, headers ...string) *clientResponse {
return c.do(newRequest("HEAD", "http://example.org"+path, headers...))
}
func (c *client) put(path string, headers ...string) *clientResponse {
return c.do(newRequest("PUT", "http://example.org"+path, headers...))
}
func (c *client) post(path string, headers ...string) *clientResponse {
return c.do(newRequest("POST", "http://example.org"+path, headers...))
}
type clientResponse struct {
*httptest.ResponseRecorder
cacheStatus string
statusCode int
age time.Duration
body []byte
header http.Header
}
type upstreamServer struct {
Now time.Time
Body []byte
Filename string
CacheControl string
Etag, Vary string
LastModified time.Time
ResponseDuration time.Duration
StatusCode int
Header http.Header
asserts []func(r *http.Request)
requests int
}
func (u *upstreamServer) timeTravel(d time.Duration) {
u.Now = u.Now.Add(d)
}
func (u *upstreamServer) assert(f func(r *http.Request)) {
u.asserts = append(u.asserts, f)
}
func (u *upstreamServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
u.requests = u.requests + 1
for _, assertf := range u.asserts {
assertf(req)
}
if !u.Now.IsZero() {
rw.Header().Set("Date", u.Now.Format(http.TimeFormat))
}
if u.CacheControl != "" {
rw.Header().Set("Cache-Control", u.CacheControl)
}
if u.Etag != "" {
rw.Header().Set("Etag", u.Etag)
}
if u.Vary != "" {
rw.Header().Set("Vary", u.Vary)
}
if u.Header != nil {
for key, headers := range u.Header {
for _, header := range headers {
rw.Header().Add(key, header)
}
}
}
u.timeTravel(u.ResponseDuration)
if u.StatusCode != 0 && u.StatusCode != 200 {
rw.WriteHeader(u.StatusCode)
io.Copy(rw, bytes.NewReader(u.Body))
} else {
http.ServeContent(rw, req, u.Filename, u.LastModified, bytes.NewReader(u.Body))
}
}
func (u *upstreamServer) RoundTrip(req *http.Request) (*http.Response, error) {
rec := httptest.NewRecorder()
u.ServeHTTP(rec, req)
rec.Flush()
resp := newResponse(rec.Code, rec.Body.Bytes())
resp.Header = rec.HeaderMap
return resp, nil
}
func cc(cc string) string {
return fmt.Sprintf("Cache-Control: %s", cc)
}
func readAll(r io.Reader) []byte {
b, err := ioutil.ReadAll(r)
if err != nil {
panic(err)
}
return b
}
func readAllString(r io.Reader) string {
return string(readAll(r))
}
================================================
FILE: validator.go
================================================
package httpcache
import (
"fmt"
"net/http"
"net/http/httptest"
)
type Validator struct {
Handler http.Handler
}
func (v *Validator) Validate(req *http.Request, res *Resource) bool {
outreq := cloneRequest(req)
resHeaders := res.Header()
if etag := resHeaders.Get("Etag"); etag != "" {
outreq.Header.Set("If-None-Match", etag)
} else if lastMod := resHeaders.Get("Last-Modified"); lastMod != "" {
outreq.Header.Set("If-Modified-Since", lastMod)
}
t := Clock()
resp := httptest.NewRecorder()
v.Handler.ServeHTTP(resp, outreq)
resp.Flush()
if age, err := correctedAge(resp.HeaderMap, t, Clock()); err == nil {
resp.Header().Set("Age", fmt.Sprintf("%.f", age.Seconds()))
}
if headersEqual(resHeaders, resp.HeaderMap) {
res.header = resp.HeaderMap
res.header.Set(ProxyDateHeader, Clock().Format(http.TimeFormat))
return true
}
return false
}
var validationHeaders = []string{"ETag", "Content-MD5", "Last-Modified", "Content-Length"}
func headersEqual(h1, h2 http.Header) bool {
for _, header := range validationHeaders {
if value := h2.Get(header); value != "" {
if h1.Get(header) != value {
debugf("%s changed, %q != %q", header, value, h1.Get(header))
return false
}
}
}
return true
}
// cloneRequest returns a clone of the provided *http.Request.
// The clone is a shallow copy of the struct and its Header map.
func cloneRequest(r *http.Request) *http.Request {
r2 := new(http.Request)
*r2 = *r
r2.Header = make(http.Header)
for k, s := range r.Header {
r2.Header[k] = s
}
return r2
}
================================================
FILE: vendor/github.com/rainycape/vfs/LICENSE
================================================
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
================================================
FILE: vendor/github.com/rainycape/vfs/README.md
================================================
# vfs
vfs implements Virtual File Systems with read-write support in Go (golang)
[](https://godoc.org/github.com/rainycape/vfs)
================================================
FILE: vendor/github.com/rainycape/vfs/bench_test.go
================================================
package vfs
import (
"bytes"
"compress/gzip"
"io/ioutil"
"os"
"testing"
)
func BenchmarkLoadGoSrc(b *testing.B) {
f := openOptionalTestFile(b, goTestFile)
defer f.Close()
// Decompress to avoid measuring the time to gunzip
zr, err := gzip.NewReader(f)
if err != nil {
b.Fatal(err)
}
defer zr.Close()
data, err := ioutil.ReadAll(zr)
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
for ii := 0; ii < b.N; ii++ {
if _, err := Tar(bytes.NewReader(data)); err != nil {
b.Fatal(err)
}
}
}
func BenchmarkWalkGoSrc(b *testing.B) {
f := openOptionalTestFile(b, goTestFile)
defer f.Close()
fs, err := TarGzip(f)
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
for ii := 0; ii < b.N; ii++ {
Walk(fs, "/", func(_ VFS, _ string, _ os.FileInfo, _ error) error { return nil })
}
}
================================================
FILE: vendor/github.com/rainycape/vfs/chroot.go
================================================
package vfs
import (
"fmt"
"os"
"path"
)
type chrootFileSystem struct {
root string
fs VFS
}
func (fs *chrootFileSystem) path(p string) string {
// root always ends with /, if there are double
// slashes they will be fixed by the underlying
// VFS
return fs.root + p
}
func (fs *chrootFileSystem) VFS() VFS {
return fs.fs
}
func (fs *chrootFileSystem) Open(path string) (RFile, error) {
return fs.fs.Open(fs.path(path))
}
func (fs *chrootFileSystem) OpenFile(path string, flag int, perm os.FileMode) (WFile, error) {
return fs.fs.OpenFile(fs.path(path), flag, perm)
}
func (fs *chrootFileSystem) Lstat(path string) (os.FileInfo, error) {
return fs.fs.Lstat(fs.path(path))
}
func (fs *chrootFileSystem) Stat(path string) (os.FileInfo, error) {
return fs.fs.Stat(fs.path(path))
}
func (fs *chrootFileSystem) ReadDir(path string) ([]os.FileInfo, error) {
return fs.fs.ReadDir(fs.path(path))
}
func (fs *chrootFileSystem) Mkdir(path string, perm os.FileMode) error {
return fs.fs.Mkdir(fs.path(path), perm)
}
func (fs *chrootFileSystem) Remove(path string) error {
return fs.fs.Remove(fs.path(path))
}
func (fs *chrootFileSystem) String() string {
return fmt.Sprintf("Chroot %s %s", fs.root, fs.fs.String())
}
// Chroot returns a new VFS wrapping the given VFS, making the given
// directory the new root ("/"). Note that root must be an existing
// directory in the given file system, otherwise an error is returned.
func Chroot(root string, fs VFS) (VFS, error) {
root = path.Clean("/" + root)
st, err := fs.Stat(root)
if err != nil {
return nil, err
}
if !st.IsDir() {
return nil, fmt.Errorf("%s is not a directory", root)
}
return &chrootFileSystem{root: root + "/", fs: fs}, nil
}
================================================
FILE: vendor/github.com/rainycape/vfs/doc.go
================================================
// Package vfs implements Virtual File Systems with read-write support.
//
// All implementatations use slash ('/') separated paths, with / representing
// the root directory. This means that to manipulate or construct paths, the
// functions in path package should be used, like path.Join or path.Dir.
// There's also no notion of the current directory nor relative paths. The paths
// /a/b/c and a/b/c are considered to point to the same element.
//
// This package also implements some shorthand functions which might be used with
// any VFS implementation, providing the same functionality than functions in the
// io/ioutil, os and path/filepath packages:
//
// io/ioutil.ReadFile => ReadFile
// io/ioutil.WriteFile => WriteFile
// os.IsExist => IsExist
// os.IsNotExist => IsNotExist
// os.MkdirAll => MkdirAll
// os.RemoveAll => RemoveAll
// path/filepath.Walk => Walk
//
// All VFS implementations are thread safe, so multiple readers and writers might
// operate on them at any time.
package vfs
================================================
FILE: vendor/github.com/rainycape/vfs/file.go
================================================
package vfs
import (
"os"
"path"
"sync"
"time"
)
// EntryType indicates the type of the entry.
type EntryType uint8
const (
// EntryTypeFile indicates the entry is a file.
EntryTypeFile EntryType = iota + 1
// EntryTypeDir indicates the entry is a directory.
EntryTypeDir
)
const (
ModeCompress os.FileMode = 1 << 16
)
// Entry is the interface implemented by the in-memory representations
// of files and directories.
type Entry interface {
// Type returns the entry type, either EntryTypeFile or
// EntryTypeDir.
Type() EntryType
// Size returns the file size. For directories, it's always zero.
Size() int64
// FileMode returns the file mode as an os.FileMode.
FileMode() os.FileMode
// ModificationTime returns the last time the file or the directory
// was modified.
ModificationTime() time.Time
}
// Type File represents an in-memory file. Most in-memory VFS implementations
// should use this structure to represent their files, in order to save work.
type File struct {
sync.RWMutex
// Data contains the file data.
Data []byte
// Mode is the file or directory mode. Note that some filesystems
// might ignore the permission bits.
Mode os.FileMode
// ModTime represents the last modification time to the file.
ModTime time.Time
}
func (f *File) Type() EntryType {
return EntryTypeFile
}
func (f *File) Size() int64 {
f.RLock()
defer f.RUnlock()
return int64(len(f.Data))
}
func (f *File) FileMode() os.FileMode {
return f.Mode
}
func (f *File) ModificationTime() time.Time {
f.RLock()
defer f.RUnlock()
return f.ModTime
}
// Type Dir represents an in-memory directory. Most in-memory VFS
// implementations should use this structure to represent their
// directories, in order to save work.
type Dir struct {
sync.RWMutex
// Mode is the file or directory mode. Note that some filesystems
// might ignore the permission bits.
Mode os.FileMode
// ModTime represents the last modification time to directory.
ModTime time.Time
// Entry names in this directory, in order.
EntryNames []string
// Entries in the same order as EntryNames.
Entries []Entry
}
func (d *Dir) Type() EntryType {
return EntryTypeDir
}
func (d *Dir) Size() int64 {
return 0
}
func (d *Dir) FileMode() os.FileMode {
return d.Mode
}
func (d *Dir) ModificationTime() time.Time {
d.RLock()
defer d.RUnlock()
return d.ModTime
}
// Add ads a new entry to the directory. If there's already an
// entry ith the same name, an error is returned.
func (d *Dir) Add(name string, entry Entry) error {
// TODO: Binary search
for ii, v := range d.EntryNames {
if v > name {
names := make([]string, len(d.EntryNames)+1)
copy(names, d.EntryNames[:ii])
names[ii] = name
copy(names[ii+1:], d.EntryNames[ii:])
d.EntryNames = names
entries := make([]Entry, len(d.Entries)+1)
copy(entries, d.Entries[:ii])
entries[ii] = entry
copy(entries[ii+1:], d.Entries[ii:])
d.Entries = entries
return nil
}
if v == name {
return os.ErrExist
}
}
// Not added yet, put at the end
d.EntryNames = append(d.EntryNames, name)
d.Entries = append(d.Entries, entry)
return nil
}
// Find returns the entry with the given name and its index,
// or an error if an entry with that name does not exist in
// the directory.
func (d *Dir) Find(name string) (Entry, int, error) {
for ii, v := range d.EntryNames {
if v == name {
return d.Entries[ii], ii, nil
}
}
return nil, -1, os.ErrNotExist
}
// EntryInfo implements the os.FileInfo interface wrapping
// a given File and its Path in its VFS.
type EntryInfo struct {
// Path is the full path to the entry in its VFS.
Path string
// Entry is the instance used by the VFS to represent
// the in-memory entry.
Entry Entry
}
func (info *EntryInfo) Name() string {
return path.Base(info.Path)
}
func (info *EntryInfo) Size() int64 {
return info.Entry.Size()
}
func (info *EntryInfo) Mode() os.FileMode {
return info.Entry.FileMode()
}
func (info *EntryInfo) ModTime() time.Time {
return info.Entry.ModificationTime()
}
func (info *EntryInfo) IsDir() bool {
return info.Entry.Type() == EntryTypeDir
}
// Sys returns the underlying Entry.
func (info *EntryInfo) Sys() interface{} {
return info.Entry
}
// FileInfos represents an slice of os.FileInfo which
// implements the sort.Interface. This type is only
// exported for users who want to implement their own
// filesystems, since VFS.ReadDir requires the returned
// []os.FileInfo to be sorted by name.
type FileInfos []os.FileInfo
func (f FileInfos) Len() int {
return len(f)
}
func (f FileInfos) Less(i, j int) bool {
return f[i].Name() < f[j].Name()
}
func (f FileInfos) Swap(i, j int) {
f[i], f[j] = f[j], f[i]
}
================================================
FILE: vendor/github.com/rainycape/vfs/file_util.go
================================================
package vfs
import (
"bytes"
"compress/zlib"
"errors"
"fmt"
"io"
"os"
"runtime"
"time"
)
var (
errFileClosed = errors.New("file is closed")
)
// NewRFile returns a RFile from a *File.
func NewRFile(f *File) (RFile, error) {
data, err := fileData(f)
if err != nil {
return nil, err
}
return &file{f: f, data: data, readable: true}, nil
}
// NewWFile returns a WFile from a *File.
func NewWFile(f *File, read bool, write bool) (WFile, error) {
data, err := fileData(f)
if err != nil {
return nil, err
}
w := &file{f: f, data: data, readable: read, writable: write}
runtime.SetFinalizer(w, closeFile)
return w, nil
}
func closeFile(f *file) {
f.Close()
}
func fileData(f *File) ([]byte, error) {
if len(f.Data) == 0 || f.Mode&ModeCompress == 0 {
return f.Data, nil
}
zr, err := zlib.NewReader(bytes.NewReader(f.Data))
if err != nil {
return nil, err
}
defer zr.Close()
var out bytes.Buffer
if _, err := io.Copy(&out, zr); err != nil {
return nil, err
}
return out.Bytes(), nil
}
type file struct {
f *File
data []byte
offset int
readable bool
writable bool
closed bool
}
func (f *file) Read(p []byte) (int, error) {
if !f.readable {
return 0, ErrWriteOnly
}
f.f.RLock()
defer f.f.RUnlock()
if f.closed {
return 0, errFileClosed
}
if f.offset > len(f.data) {
return 0, io.EOF
}
n := copy(p, f.data[f.offset:])
f.offset += n
if n < len(p) {
return n, io.EOF
}
return n, nil
}
func (f *file) Seek(offset int64, whence int) (int64, error) {
f.f.Lock()
defer f.f.Unlock()
if f.closed {
return 0, errFileClosed
}
switch whence {
case os.SEEK_SET:
f.offset = int(offset)
case os.SEEK_CUR:
f.offset += int(offset)
case os.SEEK_END:
f.offset = len(f.data) + int(offset)
default:
panic(fmt.Errorf("Seek: invalid whence %d", whence))
}
if f.offset > len(f.data) {
f.offset = len(f.data)
} else if f.offset < 0 {
f.offset = 0
}
return int64(f.offset), nil
}
func (f *file) Write(p []byte) (int, error) {
if !f.writable {
return 0, ErrReadOnly
}
f.f.Lock()
defer f.f.Unlock()
if f.closed {
return 0, errFileClosed
}
count := len(p)
n := copy(f.data[f.offset:], p)
if n < count {
f.data = append(f.data, p[n:]...)
}
f.offset += count
f.f.ModTime = time.Now()
return count, nil
}
func (f *file) Close() error {
if !f.closed {
f.f.Lock()
defer f.f.Unlock()
if !f.closed {
if f.f.Mode&ModeCompress != 0 {
var buf bytes.Buffer
zw := zlib.NewWriter(&buf)
if _, err := zw.Write(f.data); err != nil {
return err
}
if err := zw.Close(); err != nil {
return err
}
if buf.Len() < len(f.data) {
f.f.Data = buf.Bytes()
} else {
f.f.Mode &= ^ModeCompress
f.f.Data = f.data
}
} else {
f.f.Data = f.data
}
f.closed = true
}
}
return nil
}
func (f *file) IsCompressed() bool {
return f.f.Mode&ModeCompress != 0
}
func (f *file) SetCompressed(c bool) {
f.f.Lock()
defer f.f.Unlock()
if c {
f.f.Mode |= ModeCompress
} else {
f.f.Mode &= ^ModeCompress
}
}
================================================
FILE: vendor/github.com/rainycape/vfs/fs.go
================================================
package vfs
import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
)
// IMPORTANT: Note about wrapping os. functions: os.Open, os.OpenFile etc... will return a non-nil
// interface pointing to a nil instance in case of error (whoever decided this disctintion in Go
// was a good idea deservers to be hung by his thumbs). This is highly undesirable, since users
// can't rely on checking f != nil to know if a correct handle was returned. That's why the
// methods in fileSystem do the error checking themselves and return a true nil in case of error.
type fileSystem struct {
root string
temporary bool
}
func (fs *fileSystem) path(name string) string {
name = path.Clean("/" + name)
return filepath.Join(fs.root, filepath.FromSlash(name))
}
// Root returns the root directory of the fileSystem, as an
// absolute path native to the current operating system.
func (fs *fileSystem) Root() string {
return fs.root
}
// IsTemporary returns wheter the fileSystem is temporary.
func (fs *fileSystem) IsTemporary() bool {
return fs.temporary
}
func (fs *fileSystem) Open(path string) (RFile, error) {
f, err := os.Open(fs.path(path))
if err != nil {
return nil, err
}
return f, nil
}
func (fs *fileSystem) OpenFile(path string, flag int, mode os.FileMode) (WFile, error) {
f, err := os.OpenFile(fs.path(path), flag, mode)
if err != nil {
return nil, err
}
return f, nil
}
func (fs *fileSystem) Lstat(path string) (os.FileInfo, error) {
info, err := os.Lstat(fs.path(path))
if err != nil {
return nil, err
}
return info, nil
}
func (fs *fileSystem) Stat(path string) (os.FileInfo, error) {
info, err := os.Stat(fs.path(path))
if err != nil {
return nil, err
}
return info, nil
}
func (fs *fileSystem) ReadDir(path string) ([]os.FileInfo, error) {
files, err := ioutil.ReadDir(fs.path(path))
if err != nil {
return nil, err
}
return files, nil
}
func (fs *fileSystem) Mkdir(path string, perm os.FileMode) error {
return os.Mkdir(fs.path(path), perm)
}
func (fs *fileSystem) Remove(path string) error {
return os.Remove(fs.path(path))
}
func (fs *fileSystem) String() string {
return fmt.Sprintf("fileSystem: %s", fs.root)
}
// Close is a no-op on non-temporary filesystems. On temporary
// ones (as returned by TmpFS), it removes all the temporary files.
func (f *fileSystem) Close() error {
if f.temporary {
return os.RemoveAll(f.root)
}
return nil
}
func newFS(root string) (*fileSystem, error) {
abs, err := filepath.Abs(root)
if err != nil {
return nil, err
}
return &fileSystem{root: abs}, nil
}
// FS returns a VFS at the given path, which must be provided
// as native path of the current operating system. The path might be
// either absolute or relative, but the fileSystem will be anchored
// at the absolute path represented by root at the time of the function
// call.
func FS(root string) (VFS, error) {
return newFS(root)
}
// TmpFS returns a temporary file system with the given prefix and its root
// directory name, which might be empty. The temporary file system is created
// in the default temporary directory for the operating system. Once you're
// done with the temporary filesystem, you might can all its files by calling
// its Close method.
func TmpFS(prefix string) (TemporaryVFS, error) {
dir, err := ioutil.TempDir("", prefix)
if err != nil {
return nil, err
}
fs, err := newFS(dir)
if err != nil {
return nil, err
}
fs.temporary = true
return fs, nil
}
================================================
FILE: vendor/github.com/rainycape/vfs/map.go
================================================
package vfs
import (
"path"
"sort"
)
// Map returns an in-memory file system using the given files argument to
// populate it (which might be nil). Note that the files map does
// not need to contain any directories, they will be created automatically.
// If the files contain conflicting paths (e.g. files named a and a/b, thus
// making "a" both a file and a directory), an error will be returned.
func Map(files map[string]*File) (VFS, error) {
fs := newMemory()
keys := make([]string, 0, len(files))
for k := range files {
keys = append(keys, k)
}
sort.Strings(keys)
var dir *Dir
var prevDir *Dir
var prevDirPath string
for _, k := range keys {
file := files[k]
if file.Mode == 0 {
file.Mode = 0644
}
fileDir, fileBase := path.Split(k)
if prevDir != nil && fileDir == prevDirPath {
dir = prevDir
} else {
if err := MkdirAll(fs, fileDir, 0755); err != nil {
return nil, err
}
var err error
dir, err = fs.dirEntry(fileDir)
if err != nil {
return nil, err
}
prevDir = dir
prevDirPath = fileDir
}
if err := dir.Add(fileBase, file); err != nil {
return nil, err
}
}
return fs, nil
}
================================================
FILE: vendor/github.com/rainycape/vfs/mem.go
================================================
package vfs
import (
"errors"
"fmt"
"os"
pathpkg "path"
"strings"
"sync"
"time"
)
var (
errNoEmptyNameFile = errors.New("can't create file with empty name")
errNoEmptyNameDir = errors.New("can't create directory with empty name")
)
type memoryFileSystem struct {
mu sync.RWMutex
root *Dir
}
// entry must always be called with the lock held
func (fs *memoryFileSystem) entry(path string) (Entry, *Dir, int, error) {
path = cleanPath(path)
if path == "" || path == "/" || path == "." {
return fs.root, nil, 0, nil
}
if path[0] == '/' {
path = path[1:]
}
dir := fs.root
for {
p := strings.IndexByte(path, '/')
name := path
if p > 0 {
name = path[:p]
path = path[p+1:]
} else {
path = ""
}
dir.RLock()
entry, pos, err := dir.Find(name)
dir.RUnlock()
if err != nil {
return nil, nil, 0, err
}
if len(path) == 0 {
return entry, dir, pos, nil
}
if entry.Type() != EntryTypeDir {
break
}
dir = entry.(*Dir)
}
return nil, nil, 0, os.ErrNotExist
}
func (fs *memoryFileSystem) dirEntry(path string) (*Dir, error) {
entry, _, _, err := fs.entry(path)
if err != nil {
return nil, err
}
if entry.Type() != EntryTypeDir {
return nil, fmt.Errorf("%s it's not a directory", path)
}
return entry.(*Dir), nil
}
func (fs *memoryFileSystem) Open(path string) (RFile, error) {
entry, _, _, err := fs.entry(path)
if err != nil {
return nil, err
}
if entry.Type() != EntryTypeFile {
return nil, fmt.Errorf("%s is not a file", path)
}
return NewRFile(entry.(*File))
}
func (fs *memoryFileSystem) OpenFile(path string, flag int, mode os.FileMode) (WFile, error) {
if mode&os.ModeType != 0 {
return nil, fmt.Errorf("%T does not support special files", fs)
}
path = cleanPath(path)
dir, base := pathpkg.Split(path)
if base == "" {
return nil, errNoEmptyNameFile
}
fs.mu.RLock()
d, err := fs.dirEntry(dir)
fs.mu.RUnlock()
if err != nil {
return nil, err
}
d.Lock()
defer d.Unlock()
f, _, _ := d.Find(base)
if f == nil && flag&os.O_CREATE == 0 {
return nil, os.ErrNotExist
}
// Read only file?
if flag&os.O_WRONLY == 0 && flag&os.O_RDWR == 0 {
if f == nil {
return nil, os.ErrNotExist
}
return NewWFile(f.(*File), true, false)
}
// Write file, either f != nil or flag&os.O_CREATE
if f != nil {
if f.Type() != EntryTypeFile {
return nil, fmt.Errorf("%s is not a file", path)
}
if flag&os.O_EXCL != 0 {
return nil, os.ErrExist
}
// Check if we should truncate
if flag&os.O_TRUNC != 0 {
file := f.(*File)
file.Lock()
file.ModTime = time.Now()
file.Data = nil
file.Unlock()
}
} else {
f = &File{ModTime: time.Now()}
d.Add(base, f)
}
return NewWFile(f.(*File), flag&os.O_RDWR != 0, true)
}
func (fs *memoryFileSystem) Lstat(path string) (os.FileInfo, error) {
return fs.Stat(path)
}
func (fs *memoryFileSystem) Stat(path string) (os.FileInfo, error) {
entry, _, _, err := fs.entry(path)
if err != nil {
return nil, err
}
return &EntryInfo{Path: path, Entry: entry}, nil
}
func (fs *memoryFileSystem) ReadDir(path string) ([]os.FileInfo, error) {
fs.mu.RLock()
defer fs.mu.RUnlock()
return fs.readDir(path)
}
func (fs *memoryFileSystem) readDir(path string) ([]os.FileInfo, error) {
entry, _, _, err := fs.entry(path)
if err != nil {
return nil, err
}
if entry.Type() != EntryTypeDir {
return nil, fmt.Errorf("%s is not a directory", path)
}
dir := entry.(*Dir)
dir.RLock()
infos := make([]os.FileInfo, len(dir.Entries))
for ii, v := range dir.EntryNames {
infos[ii] = &EntryInfo{
Path: pathpkg.Join(path, v),
Entry: dir.Entries[ii],
}
}
dir.RUnlock()
return infos, nil
}
func (fs *memoryFileSystem) Mkdir(path string, perm os.FileMode) error {
path = cleanPath(path)
dir, base := pathpkg.Split(path)
if base == "" {
if dir == "/" || dir == "" {
return os.ErrExist
}
return errNoEmptyNameDir
}
fs.mu.RLock()
d, err := fs.dirEntry(dir)
fs.mu.RUnlock()
if err != nil {
return err
}
d.Lock()
defer d.Unlock()
if _, p, _ := d.Find(base); p >= 0 {
return os.ErrExist
}
d.Add(base, &Dir{
Mode: os.ModeDir | perm,
ModTime: time.Now(),
})
return nil
}
func (fs *memoryFileSystem) Remove(path string) error {
entry, dir, pos, err := fs.entry(path)
if err != nil {
return err
}
if entry.Type() == EntryTypeDir && len(entry.(*Dir).Entries) > 0 {
return fmt.Errorf("directory %s not empty", path)
}
// Lock again, the position might have changed
dir.Lock()
_, pos, err = dir.Find(pathpkg.Base(path))
if err == nil {
dir.EntryNames = append(dir.EntryNames[:pos], dir.EntryNames[pos+1:]...)
dir.Entries = append(dir.Entries[:pos], dir.Entries[pos+1:]...)
}
dir.Unlock()
return err
}
func (fs *memoryFileSystem) String() string {
return "MemoryFileSystem"
}
func newMemory() *memoryFileSystem {
fs := &memoryFileSystem{
root: &Dir{
Mode: os.ModeDir | 0755,
ModTime: time.Now(),
},
}
return fs
}
// Memory returns an empty in memory VFS.
func Memory() VFS {
return newMemory()
}
func cleanPath(path string) string {
return strings.Trim(pathpkg.Clean("/"+path), "/")
}
================================================
FILE: vendor/github.com/rainycape/vfs/mounter.go
================================================
package vfs
import (
"fmt"
"os"
"path"
"strings"
)
const (
separator = "/"
)
func hasSubdir(root, dir string) (string, bool) {
root = path.Clean(root)
if !strings.HasSuffix(root, separator) {
root += separator
}
dir = path.Clean(dir)
if !strings.HasPrefix(dir, root) {
return "", false
}
return dir[len(root):], true
}
type mountPoint struct {
point string
fs VFS
}
func (m *mountPoint) String() string {
return fmt.Sprintf("%s at %s", m.fs, m.point)
}
// Mounter implements the VFS interface and allows mounting different virtual
// file systems at arbitraty points, working much like a UNIX filesystem.
// Note that the first mounted filesystem must be always at "/".
type Mounter struct {
points []*mountPoint
}
func (m *Mounter) fs(p string) (VFS, string, error) {
for ii := len(m.points) - 1; ii >= 0; ii-- {
if rel, ok := hasSubdir(m.points[ii].point, p); ok {
return m.points[ii].fs, rel, nil
}
}
return nil, "", os.ErrNotExist
}
// Mount mounts the given filesystem at the given mount point. Unless the
// mount point is /, it must be an already existing directory.
func (m *Mounter) Mount(fs VFS, point string) error {
point = path.Clean(point)
if point == "." || point == "" {
point = "/"
}
if point == "/" {
if len(m.points) > 0 {
return fmt.Errorf("%s is already mounted at /", m.points[0])
}
m.points = append(m.points, &mountPoint{point, fs})
return nil
}
stat, err := m.Stat(point)
if err != nil {
return err
}
if !stat.IsDir() {
return fmt.Errorf("%s is not a directory", point)
}
m.points = append(m.points, &mountPoint{point, fs})
return nil
}
// Umount umounts the filesystem from the given mount point. If there are other filesystems
// mounted below it or there's no filesystem mounted at that point, an error is returned.
func (m *Mounter) Umount(point string) error {
point = path.Clean(point)
for ii, v := range m.points {
if v.point == point {
// Check if we have mount points below this one
for _, vv := range m.points[ii:] {
if _, ok := hasSubdir(v.point, vv.point); ok {
return fmt.Errorf("can't umount %s because %s is mounted below it", point, vv)
}
}
m.points = append(m.points[:ii], m.points[ii+1:]...)
return nil
}
}
return fmt.Errorf("no filesystem mounted at %s", point)
}
func (m *Mounter) Open(path string) (RFile, error) {
fs, p, err := m.fs(path)
if err != nil {
return nil, err
}
return fs.Open(p)
}
func (m *Mounter) OpenFile(path string, flag int, perm os.FileMode) (WFile, error) {
fs, p, err := m.fs(path)
if err != nil {
return nil, err
}
return fs.OpenFile(p, flag, perm)
}
func (m *Mounter) Lstat(path string) (os.FileInfo, error) {
fs, p, err := m.fs(path)
if err != nil {
return nil, err
}
return fs.Lstat(p)
}
func (m *Mounter) Stat(path string) (os.FileInfo, error) {
fs, p, err := m.fs(path)
if err != nil {
return nil, err
}
return fs.Stat(p)
}
func (m *Mounter) ReadDir(path string) ([]os.FileInfo, error) {
fs, p, err := m.fs(path)
if err != nil {
return nil, err
}
return fs.ReadDir(p)
}
func (m *Mounter) Mkdir(path string, perm os.FileMode) error {
fs, p, err := m.fs(path)
if err != nil {
return err
}
return fs.Mkdir(p, perm)
}
func (m *Mounter) Remove(path string) error {
// TODO: Don't allow removing an empty directory
// with a mount below it.
fs, p, err := m.fs(path)
if err != nil {
return err
}
return fs.Remove(p)
}
func (m *Mounter) String() string {
s := make([]string, len(m.points))
for ii, v := range m.points {
s[ii] = v.String()
}
return fmt.Sprintf("Mounter: %s", strings.Join(s, ", "))
}
func mounterCompileTimeCheck() VFS {
return &Mounter{}
}
================================================
FILE: vendor/github.com/rainycape/vfs/open.go
================================================
package vfs
import (
"archive/tar"
"archive/zip"
"bytes"
"compress/bzip2"
"compress/gzip"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
// Zip returns an in-memory VFS initialized with the
// contents of the .zip file read from the given io.Reader.
// Since archive/zip requires an io.ReaderAt rather than an
// io.Reader, and a known size, Zip will read the whole file
// into memory and provide its own buffering if r does not
// implement io.ReaderAt or size is <= 0.
func Zip(r io.Reader, size int64) (VFS, error) {
rat, _ := r.(io.ReaderAt)
if rat == nil || size <= 0 {
data, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
rat = bytes.NewReader(data)
size = int64(len(data))
}
zr, err := zip.NewReader(rat, size)
if err != nil {
return nil, err
}
files := make(map[string]*File)
for _, file := range zr.File {
if file.Mode().IsDir() {
continue
}
f, err := file.Open()
if err != nil {
return nil, err
}
data, err := ioutil.ReadAll(f)
f.Close()
if err != nil {
return nil, err
}
files[file.Name] = &File{
Data: data,
Mode: file.Mode(),
ModTime: file.ModTime(),
}
}
return Map(files)
}
// Tar returns an in-memory VFS initialized with the
// contents of the .tar file read from the given io.Reader.
func Tar(r io.Reader) (VFS, error) {
files := make(map[string]*File)
tr := tar.NewReader(r)
for {
hdr, err := tr.Next()
if err != nil {
if err == io.EOF {
break
}
return nil, err
}
if hdr.FileInfo().IsDir() {
continue
}
data, err := ioutil.ReadAll(tr)
if err != nil {
return nil, err
}
files[hdr.Name] = &File{
Data: data,
Mode: hdr.FileInfo().Mode(),
ModTime: hdr.ModTime,
}
}
return Map(files)
}
// TarGzip returns an in-memory VFS initialized with the
// contents of the .tar.gz file read from the given io.Reader.
func TarGzip(r io.Reader) (VFS, error) {
zr, err := gzip.NewReader(r)
if err != nil {
return nil, err
}
defer zr.Close()
return Tar(zr)
}
// TarBzip2 returns an in-memory VFS initialized with the
// contents of then .tar.bz2 file read from the given io.Reader.
func TarBzip2(r io.Reader) (VFS, error) {
bzr := bzip2.NewReader(r)
return Tar(bzr)
}
// Open returns an in-memory VFS initialized with the contents
// of the given filename, which must have one of the following
// extensions:
//
// - .zip
// - .tar
// - .tar.gz
// - .tar.bz2
func Open(filename string) (VFS, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
base := filepath.Base(filename)
ext := strings.ToLower(filepath.Ext(base))
nonExt := filename[:len(filename)-len(ext)]
if strings.ToLower(filepath.Ext(nonExt)) == ".tar" {
ext = ".tar" + ext
}
switch ext {
case ".zip":
st, err := f.Stat()
if err != nil {
return nil, err
}
return Zip(f, st.Size())
case ".tar":
return Tar(f)
case ".tar.gz":
return TarGzip(f)
case ".tar.bz2":
return TarBzip2(f)
}
return nil, fmt.Errorf("can't open a VFS from a %s file", ext)
}
================================================
FILE: vendor/github.com/rainycape/vfs/open_test.go
================================================
package vfs
import (
"path/filepath"
"testing"
)
func testOpenedVFS(t *testing.T, fs VFS) {
data1, err := ReadFile(fs, "a/b/c/d")
if err != nil {
t.Fatal(err)
}
if string(data1) != "go" {
t.Errorf("expecting a/b/c/d to contain \"go\", it contains %q instead", string(data1))
}
data2, err := ReadFile(fs, "empty")
if err != nil {
t.Fatal(err)
}
if len(data2) > 0 {
t.Error("non-empty empty file")
}
}
func testOpenFilename(t *testing.T, filename string) {
p := filepath.Join("testdata", filename)
fs, err := Open(p)
if err != nil {
t.Fatal(err)
}
testOpenedVFS(t, fs)
}
func TestOpenZip(t *testing.T) {
testOpenFilename(t, "fs.zip")
}
func TestOpenTar(t *testing.T) {
testOpenFilename(t, "fs.tar")
}
func TestOpenTarGzip(t *testing.T) {
testOpenFilename(t, "fs.tar.gz")
}
func TestOpenTarBzip2(t *testing.T) {
testOpenFilename(t, "fs.tar.bz2")
}
================================================
FILE: vendor/github.com/rainycape/vfs/rewriter.go
================================================
package vfs
import (
"fmt"
"os"
)
type rewriterFileSystem struct {
fs VFS
rewriter func(string) string
}
func (fs *rewriterFileSystem) VFS() VFS {
return fs.fs
}
func (fs *rewriterFileSystem) Open(path string) (RFile, error) {
return fs.fs.Open(fs.rewriter(path))
}
func (fs *rewriterFileSystem) OpenFile(path string, flag int, perm os.FileMode) (WFile, error) {
return fs.fs.OpenFile(fs.rewriter(path), flag, perm)
}
func (fs *rewriterFileSystem) Lstat(path string) (os.FileInfo, error) {
return fs.fs.Lstat(fs.rewriter(path))
}
func (fs *rewriterFileSystem) Stat(path string) (os.FileInfo, error) {
return fs.fs.Stat(fs.rewriter(path))
}
func (fs *rewriterFileSystem) ReadDir(path string) ([]os.FileInfo, error) {
return fs.fs.ReadDir(fs.rewriter(path))
}
func (fs *rewriterFileSystem) Mkdir(path string, perm os.FileMode) error {
return fs.fs.Mkdir(fs.rewriter(path), perm)
}
func (fs *rewriterFileSystem) Remove(path string) error {
return fs.fs.Remove(fs.rewriter(path))
}
func (fs *rewriterFileSystem) String() string {
return fmt.Sprintf("Rewriter %s", fs.fs.String())
}
// Rewriter returns a file system which uses the provided function
// to rewrite paths.
func Rewriter(fs VFS, rewriter func(oldPath string) (newPath string)) VFS {
if rewriter == nil {
return fs
}
return &rewriterFileSystem{fs: fs, rewriter: rewriter}
}
================================================
FILE: vendor/github.com/rainycape/vfs/ro.go
================================================
package vfs
import (
"errors"
"fmt"
"os"
)
var (
// ErrReadOnlyFileSystem is the error returned by read only file systems
// from calls which would result in a write operation.
ErrReadOnlyFileSystem = errors.New("read-only filesystem")
)
type readOnlyFileSystem struct {
fs VFS
}
func (fs *readOnlyFileSystem) VFS() VFS {
return fs.fs
}
func (fs *readOnlyFileSystem) Open(path string) (RFile, error) {
return fs.fs.Open(path)
}
func (fs *readOnlyFileSystem) OpenFile(path string, flag int, perm os.FileMode) (WFile, error) {
if flag&(os.O_CREATE|os.O_WRONLY|os.O_RDWR) != 0 {
return nil, ErrReadOnlyFileSystem
}
return fs.fs.OpenFile(path, flag, perm)
}
func (fs *readOnlyFileSystem) Lstat(path string) (os.FileInfo, error) {
return fs.fs.Lstat(path)
}
func (fs *readOnlyFileSystem) Stat(path string) (os.FileInfo, error) {
return fs.fs.Stat(path)
}
func (fs *readOnlyFileSystem) ReadDir(path string) ([]os.FileInfo, error) {
return fs.fs.ReadDir(path)
}
func (fs *readOnlyFileSystem) Mkdir(path string, perm os.FileMode) error {
return ErrReadOnlyFileSystem
}
func (fs *readOnlyFileSystem) Remove(path string) error {
return ErrReadOnlyFileSystem
}
func (fs *readOnlyFileSystem) String() string {
return fmt.Sprintf("RO %s", fs.fs.String())
}
// ReadOnly returns a read-only filesystem wrapping the given fs.
func ReadOnly(fs VFS) VFS {
return &readOnlyFileSystem{fs: fs}
}
================================================
FILE: vendor/github.com/rainycape/vfs/testdata/download-data.sh
================================================
#!/bin/sh
SRC=https://storage.googleapis.com/golang/go1.3.src.tar.gz
if which curl > /dev/null 2>&1; then
curl -O ${SRC}
elif which wget > /dev/null 2&1; then
wget -O `basename ${SRC}` ${SRC}
else
echo "no curl nor wget found" 1>&2
exit 1
fi
================================================
FILE: vendor/github.com/rainycape/vfs/testdata/fs/a/b/c/d
================================================
go
================================================
FILE: vendor/github.com/rainycape/vfs/testdata/fs/empty
================================================
================================================
FILE: vendor/github.com/rainycape/vfs/testdata/update-fs.sh
================================================
#!/bin/sh
set -e
cd fs
zip -r ../fs.zip *
tar cvvf ../fs.tar *
tar cvvzf ../fs.tar.gz *
tar cvvjf ../fs.tar.bz2 *
cd -
================================================
FILE: vendor/github.com/rainycape/vfs/util.go
================================================
package vfs
import (
"errors"
"fmt"
"io/ioutil"
"os"
pathpkg "path"
"strings"
)
var (
// SkipDir is used by a WalkFunc to signal Walk that
// it wans to skip the given directory.
SkipDir = errors.New("skip this directory")
// ErrReadOnly is returned from Write() on a read-only file.
ErrReadOnly = errors.New("can't write to read only file")
// ErrWriteOnly is returned from Read() on a write-only file.
ErrWriteOnly = errors.New("can't read from write only file")
)
// WalkFunc is the function type used by Walk to iterate over a VFS.
type WalkFunc func(fs VFS, path string, info os.FileInfo, err error) error
func walk(fs VFS, p string, info os.FileInfo, fn WalkFunc) error {
err := fn(fs, p, info, nil)
if err != nil {
if info.IsDir() && err == SkipDir {
err = nil
}
return err
}
if !info.IsDir() {
return nil
}
infos, err := fs.ReadDir(p)
if err != nil {
return fn(fs, p, info, err)
}
for _, v := range infos {
name := pathpkg.Join(p, v.Name())
fileInfo, err := fs.Lstat(name)
if err != nil {
if err := fn(fs, name, fileInfo, err); err != nil && err != SkipDir {
return err
}
continue
}
if err := walk(fs, name, fileInfo, fn); err != nil && (!fileInfo.IsDir() || err != SkipDir) {
return err
}
}
return nil
}
// Walk iterates over all the files in the VFS which descend from the given
// root (including root itself), descending into any subdirectories. In each
// directory, files are visited in alphabetical order. The given function might
// chose to skip a directory by returning SkipDir.
func Walk(fs VFS, root string, fn WalkFunc) error {
info, err := fs.Lstat(root)
if err != nil {
return fn(fs, root, nil, err)
}
return walk(fs, root, info, fn)
}
func makeDir(fs VFS, path string, perm os.FileMode) error {
stat, err := fs.Lstat(path)
if err == nil {
if !stat.IsDir() {
return fmt.Errorf("%s exists and is not a directory", path)
}
} else {
if err := fs.Mkdir(path, perm); err != nil {
return err
}
}
return nil
}
// MkdirAll makes all directories pointed by the given path, using the same
// permissions for all of them. Note that MkdirAll skips directories which
// already exists rather than returning an error.
func MkdirAll(fs VFS, path string, perm os.FileMode) error {
cur := "/"
if err := makeDir(fs, cur, perm); err != nil {
return err
}
parts := strings.Split(path, "/")
for _, v := range parts {
cur += v
if err := makeDir(fs, cur, perm); err != nil {
return err
}
cur += "/"
}
return nil
}
// RemoveAll removes all files from the given fs and path, including
// directories (by removing its contents first).
func RemoveAll(fs VFS, path string) error {
stat, err := fs.Lstat(path)
if err != nil {
if err == os.ErrNotExist {
return nil
}
return err
}
if stat.IsDir() {
files, err := fs.ReadDir(path)
if err != nil {
return err
}
for _, v := range files {
filePath := pathpkg.Join(path, v.Name())
if err := RemoveAll(fs, filePath); err != nil {
return err
}
}
}
return fs.Remove(path)
}
// ReadFile reads the file at the given path from the given fs, returning
// either its contents or an error if the file couldn't be read.
func ReadFile(fs VFS, path string) ([]byte, error) {
f, err := fs.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return ioutil.ReadAll(f)
}
// WriteFile writes a file at the given path and fs with the given data and
// permissions. If the file already exists, WriteFile truncates it before
// writing. If the file can't be created, an error will be returned.
func WriteFile(fs VFS, path string, data []byte, perm os.FileMode) error {
f, err := fs.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, perm)
if err != nil {
return err
}
if _, err := f.Write(data); err != nil {
f.Close()
return err
}
return f.Close()
}
// Clone copies all the files from the src VFS to dst. Note that files or directories with
// all permissions set to 0 will be set to 0755 for directories and 0644 for files. If you
// need more granularity, use Walk directly to clone the file systems.
func Clone(dst VFS, src VFS) error {
err := Walk(src, "/", func(fs VFS, path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
perm := info.Mode() & os.ModePerm
if perm == 0 {
perm = 0755
}
err := dst.Mkdir(path, info.Mode()|perm)
if err != nil && !IsExist(err) {
return err
}
return nil
}
data, err := ReadFile(fs, path)
if err != nil {
return err
}
perm := info.Mode() & os.ModePerm
if perm == 0 {
perm = 0644
}
if err := WriteFile(dst, path, data, info.Mode()|perm); err != nil {
return err
}
return nil
})
return err
}
// IsExist returns wheter the error indicates that the file or directory
// already exists.
func IsExist(err error) bool {
return os.IsExist(err)
}
// IsExist returns wheter the error indicates that the file or directory
// does not exist.
func IsNotExist(err error) bool {
return os.IsNotExist(err)
}
// Compressor is the interface implemented by VFS files which can be
// transparently compressed and decompressed. Currently, this is only
// supported by the in-memory filesystems.
type Compressor interface {
IsCompressed() bool
SetCompressed(c bool)
}
// Compress is a shorthand method for compressing all the files in a VFS.
// Note that not all file systems support transparent compression/decompression.
func Compress(fs VFS) error {
return Walk(fs, "/", func(fs VFS, p string, info os.FileInfo, err error) error {
if err != nil {
return err
}
mode := info.Mode()
if mode.IsDir() || mode&ModeCompress != 0 {
return nil
}
f, err := fs.Open(p)
if err != nil {
return err
}
if c, ok := f.(Compressor); ok {
c.SetCompressed(true)
}
return f.Close()
})
}
================================================
FILE: vendor/github.com/rainycape/vfs/vfs.go
================================================
package vfs
import (
"io"
"os"
)
// Opener is the interface which specifies the methods for
// opening a file. All the VFS implementations implement
// this interface.
type Opener interface {
// Open returns a readable file at the given path. See also
// the shorthand function ReadFile.
Open(path string) (RFile, error)
// OpenFile returns a readable and writable file at the given
// path. Note that, depending on the flags, the file might be
// only readable or only writable. See also the shorthand
// function WriteFile.
OpenFile(path string, flag int, perm os.FileMode) (WFile, error)
}
// RFile is the interface implemented by the returned value from a VFS
// Open method. It allows reading and seeking, and must be closed after use.
type RFile interface {
io.Reader
io.Seeker
io.Closer
}
// WFile is the interface implemented by the returned value from a VFS
// OpenFile method. It allows reading, seeking and writing, and must
// be closed after use. Note that, depending on the flags passed to
// OpenFile, the Read or Write methods might always return an error (e.g.
// if the file was opened in read-only or write-only mode).
type WFile interface {
io.Reader
io.Writer
io.Seeker
io.Closer
}
// VFS is the interface implemented by all the Virtual File Systems.
type VFS interface {
Opener
// Lstat returns the os.FileInfo for the given path, without
// following symlinks.
Lstat(path string) (os.FileInfo, error)
// Stat returns the os.FileInfo for the given path, following
// symlinks.
Stat(path string) (os.FileInfo, error)
// ReadDir returns the contents of the directory at path as an slice
// of os.FileInfo, ordered alphabetically by name. If path is not a
// directory or the permissions don't allow it, an error will be
// returned.
ReadDir(path string) ([]os.FileInfo, error)
// Mkdir creates a directory at the given path. If the directory
// already exists or its parent directory does not exist or
// the permissions don't allow it, an error will be returned. See
// also the shorthand function MkdirAll.
Mkdir(path string, perm os.FileMode) error
// Remove removes the item at the given path. If the path does
// not exists or the permissions don't allow removing it or it's
// a non-empty directory, an error will be returned. See also
// the shorthand function RemoveAll.
Remove(path string) error
// String returns a human-readable description of the VFS.
String() string
}
// TemporaryVFS represents a temporary on-disk file system which can be removed
// by calling its Close method.
type TemporaryVFS interface {
VFS
// Root returns the root directory for the temporary VFS.
Root() string
// Close removes all the files in temporary VFS.
Close() error
}
// Container is implemented by some file systems which
// contain another one.
type Container interface {
// VFS returns the underlying VFS.
VFS() VFS
}
================================================
FILE: vendor/github.com/rainycape/vfs/vfs_test.go
================================================
package vfs
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"testing"
)
const (
goTestFile = "go1.3.src.tar.gz"
)
type errNoTestFile string
func (e errNoTestFile) Error() string {
return fmt.Sprintf("%s test file not found, use testdata/download-data.sh to fetch it", filepath.Base(string(e)))
}
func openOptionalTestFile(t testing.TB, name string) *os.File {
filename := filepath.Join("testdata", name)
f, err := os.Open(filename)
if err != nil {
t.Skip(errNoTestFile(filename))
}
return f
}
func testVFS(t *testing.T, fs VFS) {
if err := WriteFile(fs, "a", []byte("A"), 0644); err != nil {
t.Fatal(err)
}
data, err := ReadFile(fs, "a")
if err != nil {
t.Fatal(err)
}
if string(data) != "A" {
t.Errorf("expecting file a to contain \"A\" got %q instead", string(data))
}
if err := WriteFile(fs, "b", []byte("B"), 0755); err != nil {
t.Fatal(err)
}
if _, err := fs.OpenFile("b", os.O_CREATE|os.O_TRUNC|os.O_EXCL|os.O_WRONLY, 0755); err == nil || !IsExist(err) {
t.Errorf("error should be ErrExist, it's %v", err)
}
fb, err := fs.OpenFile("b", os.O_TRUNC|os.O_WRONLY, 0755)
if err != nil {
t.Fatalf("error opening b: %s", err)
}
if _, err := fb.Write([]byte("BB")); err != nil {
t.Errorf("error writing to b: %s", err)
}
if _, err := fb.Seek(0, os.SEEK_SET); err != nil {
t.Errorf("error seeking b: %s", err)
}
if _, err := fb.Read(make([]byte, 2)); err == nil {
t.Error("allowed reading WRONLY file b")
}
if err := fb.Close(); err != nil {
t.Errorf("error closing b: %s", err)
}
files, err := fs.ReadDir("/")
if err != nil {
t.Fatal(err)
}
if len(files) != 2 {
t.Errorf("expecting 2 files, got %d", len(files))
}
if n := files[0].Name(); n != "a" {
t.Errorf("expecting first file named \"a\", got %q", n)
}
if n := files[1].Name(); n != "b" {
t.Errorf("expecting first file named \"b\", got %q", n)
}
for ii, v := range files {
es := int64(ii + 1)
if s := v.Size(); es != s {
t.Errorf("expecting file %s to have size %d, has %d", v.Name(), es, s)
}
}
if err := MkdirAll(fs, "a/b/c/d", 0); err == nil {
t.Error("should not allow dir over file")
}
if err := MkdirAll(fs, "c/d", 0755); err != nil {
t.Fatal(err)
}
// Idempotent
if err := MkdirAll(fs, "c/d", 0755); err != nil {
t.Fatal(err)
}
if err := fs.Mkdir("c", 0755); err == nil || !IsExist(err) {
t.Errorf("err should be ErrExist, it's %v", err)
}
// Should fail to remove, c is not empty
if err := fs.Remove("c"); err == nil {
t.Fatalf("removed non-empty directory")
}
var walked []os.FileInfo
var walkedNames []string
err = Walk(fs, "c", func(fs VFS, path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
walked = append(walked, info)
walkedNames = append(walkedNames, path)
return nil
})
if err != nil {
t.Fatal(err)
}
if exp := []string{"c", "c/d"}; !reflect.DeepEqual(exp, walkedNames) {
t.Error("expecting walked names %v, got %v", exp, walkedNames)
}
for _, v := range walked {
if !v.IsDir() {
t.Errorf("%s should be a dir", v.Name())
}
}
if err := RemoveAll(fs, "c"); err != nil {
t.Fatal(err)
}
err = Walk(fs, "c", func(fs VFS, path string, info os.FileInfo, err error) error {
return err
})
if err == nil || !IsNotExist(err) {
t.Errorf("error should be ErrNotExist, it's %v", err)
}
}
func TestMapFS(t *testing.T) {
fs, err := Map(nil)
if err != nil {
t.Fatal(err)
}
testVFS(t, fs)
}
func TestPopulatedMap(t *testing.T) {
files := map[string]*File{
"a/1": &File{},
"a/2": &File{},
}
fs, err := Map(files)
if err != nil {
t.Fatal(err)
}
infos, err := fs.ReadDir("a")
if err != nil {
t.Fatal(err)
}
if c := len(infos); c != 2 {
t.Fatalf("expecting 2 files in a, got %d", c)
}
if infos[0].Name() != "1" || infos[1].Name() != "2" {
t.Errorf("expecting names 1, 2 got %q, %q", infos[0].Name(), infos[1].Name())
}
}
func TestBadPopulatedMap(t *testing.T) {
// 1 can't be file and directory
files := map[string]*File{
"a/1": &File{},
"a/1/2": &File{},
}
_, err := Map(files)
if err == nil {
t.Fatal("Map should not work with a path as both file and directory")
}
}
func TestTmpFS(t *testing.T) {
fs, err := TmpFS("vfs-test")
if err != nil {
t.Fatal(err)
}
defer fs.Close()
testVFS(t, fs)
}
const (
go13FileCount = 4157
// +1 because of the root, the real count is 407
go13DirCount = 407 + 1
)
func countFileSystem(fs VFS) (int, int, error) {
files, dirs := 0, 0
err := Walk(fs, "/", func(fs VFS, _ string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
dirs++
} else {
files++
}
return nil
})
return files, dirs, err
}
func testGoFileCount(t *testing.T, fs VFS) {
files, dirs, err := countFileSystem(fs)
if err != nil {
t.Fatal(err)
}
if files != go13FileCount {
t.Errorf("expecting %d files in go1.3, got %d instead", go13FileCount, files)
}
if dirs != go13DirCount {
t.Errorf("expecting %d directories in go1.3, got %d instead", go13DirCount, dirs)
}
}
func TestGo13Files(t *testing.T) {
f := openOptionalTestFile(t, goTestFile)
defer f.Close()
fs, err := TarGzip(f)
if err != nil {
t.Fatal(err)
}
testGoFileCount(t, fs)
}
func TestMounter(t *testing.T) {
m := &Mounter{}
f := openOptionalTestFile(t, goTestFile)
defer f.Close()
fs, err := TarGzip(f)
if err != nil {
t.Fatal(err)
}
m.Mount(fs, "/")
testGoFileCount(t, m)
}
func TestClone(t *testing.T) {
fs, err := Open(filepath.Join("testdata", "fs.zip"))
if err != nil {
t.Fatal(err)
}
infos1, err := fs.ReadDir("/")
if err != nil {
t.Fatal(err)
}
mem1 := Memory()
if err := Clone(mem1, fs); err != nil {
t.Fatal(err)
}
infos2, err := mem1.ReadDir("/")
if err != nil {
t.Fatal(err)
}
if len(infos2) != len(infos1) {
t.Fatalf("cloned fs has %d entries in / rather than %d", len(infos2), len(infos1))
}
mem2 := Memory()
if err := Clone(mem2, mem1); err != nil {
t.Fatal(err)
}
infos3, err := mem2.ReadDir("/")
if err != nil {
t.Fatal(err)
}
if len(infos3) != len(infos2) {
t.Fatalf("cloned fs has %d entries in / rather than %d", len(infos3), len(infos2))
}
}
func measureVFSMemorySize(t testing.TB, fs VFS) int {
mem, ok := fs.(*memoryFileSystem)
if !ok {
t.Fatalf("%T is not a memory filesystem", fs)
}
var total int
var f func(d *Dir)
f = func(d *Dir) {
for _, v := range d.Entries {
total += int(v.Size())
if sd, ok := v.(*Dir); ok {
f(sd)
}
}
}
f(mem.root)
return total
}
func hashVFS(t testing.TB, fs VFS) string {
sha := sha1.New()
err := Walk(fs, "/", func(fs VFS, p string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
return err
}
f, err := fs.Open(p)
if err != nil {
return err
}
defer f.Close()
if _, err := io.Copy(sha, f); err != nil {
return err
}
return nil
})
if err != nil {
t.Fatal(err)
}
return hex.EncodeToString(sha.Sum(nil))
}
func TestCompress(t *testing.T) {
f := openOptionalTestFile(t, goTestFile)
defer f.Close()
fs, err := TarGzip(f)
if err != nil {
t.Fatal(err)
}
size1 := measureVFSMemorySize(t, fs)
hash1 := hashVFS(t, fs)
if err := Compress(fs); err != nil {
t.Fatalf("can't compress fs: %s", err)
}
testGoFileCount(t, fs)
size2 := measureVFSMemorySize(t, fs)
hash2 := hashVFS(t, fs)
if size2 >= size1 {
t.Fatalf("compressed fs takes more memory %d than bare fs %d", size2, size1)
}
if hash1 != hash2 {
t.Fatalf("compressing fs changed hash from %s to %s", hash1, hash2)
}
}
================================================
FILE: vendor/github.com/rainycape/vfs/write.go
================================================
package vfs
import (
"archive/tar"
"archive/zip"
"compress/gzip"
"io"
"os"
)
func copyVFS(fs VFS, copier func(p string, info os.FileInfo, f io.Reader) error) error {
return Walk(fs, "/", func(vfs VFS, p string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
f, err := fs.Open(p)
if err != nil {
return err
}
defer f.Close()
return copier(p[1:], info, f)
})
}
// WriteZip writes the given VFS as a zip file to the given io.Writer.
func WriteZip(w io.Writer, fs VFS) error {
zw := zip.NewWriter(w)
err := copyVFS(fs, func(p string, info os.FileInfo, f io.Reader) error {
hdr, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
hdr.Name = p
fw, err := zw.CreateHeader(hdr)
if err != nil {
return err
}
_, err = io.Copy(fw, f)
return err
})
if err != nil {
return err
}
return zw.Close()
}
// WriteTar writes the given VFS as a tar file to the given io.Writer.
func WriteTar(w io.Writer, fs VFS) error {
tw := tar.NewWriter(w)
err := copyVFS(fs, func(p string, info os.FileInfo, f io.Reader) error {
hdr, err := tar.FileInfoHeader(info, "")
if err != nil {
return err
}
hdr.Name = p
if err := tw.WriteHeader(hdr); err != nil {
return err
}
_, err = io.Copy(tw, f)
return err
})
if err != nil {
return err
}
return tw.Close()
}
// WriteTarGzip writes the given VFS as a tar.gz file to the given io.Writer.
func WriteTarGzip(w io.Writer, fs VFS) error {
gw, err := gzip.NewWriterLevel(w, gzip.BestCompression)
if err != nil {
return err
}
if err := WriteTar(gw, fs); err != nil {
return err
}
return gw.Close()
}
================================================
FILE: vendor/github.com/rainycape/vfs/write_test.go
================================================
package vfs
import (
"bytes"
"io"
"path/filepath"
"testing"
)
type writeTester struct {
name string
writer func(io.Writer, VFS) error
reader func(io.Reader) (VFS, error)
}
func TestWrite(t *testing.T) {
var (
writeTests = []writeTester{
{"zip", WriteZip, func(r io.Reader) (VFS, error) { return Zip(r, 0) }},
{"tar", WriteTar, Tar},
{"tar.gz", WriteTarGzip, TarGzip},
}
)
p := filepath.Join("testdata", "fs.zip")
fs, err := Open(p)
if err != nil {
t.Fatal(err)
}
var buf bytes.Buffer
for _, v := range writeTests {
buf.Reset()
if err := v.writer(&buf, fs); err != nil {
t.Fatalf("error writing %s: %s", v.name, err)
}
newFs, err := v.reader(&buf)
if err != nil {
t.Fatalf("error reading %s: %s", v.name, err)
}
testOpenedVFS(t, newFs)
}
}
================================================
FILE: vendor/github.com/stretchr/testify/assert/assertions.go
================================================
package assert
import (
"bufio"
"bytes"
"fmt"
"reflect"
"regexp"
"runtime"
"strings"
"time"
)
// TestingT is an interface wrapper around *testing.T
type TestingT interface {
Errorf(format string, args ...interface{})
}
// Comparison a custom function that returns true on success and false on failure
type Comparison func() (success bool)
/*
Helper functions
*/
// ObjectsAreEqual determines if two objects are considered equal.
//
// This function does no assertion of any kind.
func ObjectsAreEqual(expected, actual interface{}) bool {
if expected == nil || actual == nil {
return expected == actual
}
if reflect.DeepEqual(expected, actual) {
return true
}
expectedValue := reflect.ValueOf(expected)
actualValue := reflect.ValueOf(actual)
if expectedValue == actualValue {
return true
}
// Attempt comparison after type conversion
if actualValue.Type().ConvertibleTo(expectedValue.Type()) && expectedValue == actualValue.Convert(expectedValue.Type()) {
return true
}
// Last ditch effort
if fmt.Sprintf("%#v", expected) == fmt.Sprintf("%#v", actual) {
return true
}
return false
}
/* CallerInfo is necessary because the assert functions use the testing object
internally, causing it to print the file:line of the assert method, rather than where
the problem actually occured in calling code.*/
// CallerInfo returns a string containing the file and line number of the assert call
// that failed.
func CallerInfo() string {
file := ""
line := 0
ok := false
for i := 0; ; i++ {
_, file, line, ok = runtime.Caller(i)
if !ok {
return ""
}
parts := strings.Split(file, "/")
dir := parts[len(parts)-2]
file = parts[len(parts)-1]
if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" {
break
}
}
return fmt.Sprintf("%s:%d", file, line)
}
// getWhitespaceString returns a string that is long enough to overwrite the default
// output from the go testing framework.
func getWhitespaceString() string {
_, file, line, ok := runtime.Caller(1)
if !ok {
return ""
}
parts := strings.Split(file, "/")
file = parts[len(parts)-1]
return strings.Repeat(" ", len(fmt.Sprintf("%s:%d: ", file, line)))
}
func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
if len(msgAndArgs) == 0 || msgAndArgs == nil {
return ""
}
if len(msgAndArgs) == 1 {
return msgAndArgs[0].(string)
}
if len(msgAndArgs) > 1 {
return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
}
return ""
}
// Indents all lines of the message by appending a number of tabs to each line, in an output format compatible with Go's
// test printing (see inner comment for specifics)
func indentMessageLines(message string, tabs int) string {
outBuf := new(bytes.Buffer)
for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ {
if i != 0 {
outBuf.WriteRune('\n')
}
for ii := 0; ii < tabs; ii++ {
outBuf.WriteRune('\t')
// Bizarrely, all lines except the first need one fewer tabs prepended, so deliberately advance the counter
// by 1 prematurely.
if ii == 0 && i > 0 {
ii++
}
}
outBuf.WriteString(scanner.Text())
}
return outBuf.String()
}
// Fail reports a failure through
func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
message := messageFromMsgAndArgs(msgAndArgs...)
if len(message) > 0 {
t.Errorf("\r%s\r\tLocation:\t%s\n"+
"\r\tError:%s\n"+
"\r\tMessages:\t%s\n\r",
getWhitespaceString(),
CallerInfo(),
indentMessageLines(failureMessage, 2),
message)
} else {
t.Errorf("\r%s\r\tLocation:\t%s\n"+
"\r\tError:%s\n\r",
getWhitespaceString(),
CallerInfo(),
indentMessageLines(failureMessage, 2))
}
return false
}
// Implements asserts that an object is implemented by the specified interface.
//
// assert.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject")
func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
interfaceType := reflect.TypeOf(interfaceObject).Elem()
if !reflect.TypeOf(object).Implements(interfaceType) {
return Fail(t, fmt.Sprintf("Object must implement %v", interfaceType), msgAndArgs...)
}
return true
}
// IsType asserts that the specified objects are of the same type.
func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) {
return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...)
}
return true
}
// Equal asserts that two objects are equal.
//
// assert.Equal(t, 123, 123, "123 and 123 should be equal")
//
// Returns whether the assertion was successful (true) or not (false).
func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
if !ObjectsAreEqual(expected, actual) {
return Fail(t, fmt.Sprintf("Not equal: %#v (expected)\n"+
" != %#v (actual)", expected, actual), msgAndArgs...)
}
return true
}
// Exactly asserts that two objects are equal is value and type.
//
// assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal")
//
// Returns whether the assertion was successful (true) or not (false).
func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
aType := reflect.TypeOf(expected)
bType := reflect.TypeOf(actual)
if aType != bType {
return Fail(t, "Types expected to match exactly", "%v != %v", aType, bType)
}
return Equal(t, expected, actual, msgAndArgs...)
}
// NotNil asserts that the specified object is not nil.
//
// assert.NotNil(t, err, "err should be something")
//
// Returns whether the assertion was successful (true) or not (false).
func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
success := true
if object == nil {
success = false
} else {
value := reflect.ValueOf(object)
kind := value.Kind()
if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() {
success = false
}
}
if !success {
Fail(t, "Expected not to be nil.", msgAndArgs...)
}
return success
}
// isNil checks if a specified object is nil or not, without Failing.
func isNil(object interface{}) bool {
if object == nil {
return true
}
value := reflect.ValueOf(object)
kind := value.Kind()
if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() {
return true
}
return false
}
// Nil asserts that the specified object is nil.
//
// assert.Nil(t, err, "err should be nothing")
//
// Returns whether the assertion was successful (true) or not (false).
func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
if isNil(object) {
return true
}
return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
}
var zeros = []interface{}{
int(0),
int8(0),
int16(0),
int32(0),
int64(0),
uint(0),
uint8(0),
uint16(0),
uint32(0),
uint64(0),
float32(0),
float64(0),
}
// isEmpty gets whether the specified object is considered empty or not.
func isEmpty(object interface{}) bool {
if object == nil {
return true
} else if object == "" {
return true
} else if object == false {
return true
}
for _, v := range zeros {
if object == v {
return true
}
}
objValue := reflect.ValueOf(object)
switch objValue.Kind() {
case reflect.Map:
fallthrough
case reflect.Slice, reflect.Chan:
{
return (objValue.Len() == 0)
}
case reflect.Ptr:
{
switch object.(type) {
case *time.Time:
return object.(*time.Time).IsZero()
default:
return false
}
}
}
return false
}
// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either
// a slice or a channel with len == 0.
//
// assert.Empty(t, obj)
//
// Returns whether the assertion was successful (true) or not (false).
func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
pass := isEmpty(object)
if !pass {
Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
}
return pass
}
// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
// a slice or a channel with len == 0.
//
// if assert.NotEmpty(t, obj) {
// assert.Equal(t, "two", obj[1])
// }
//
// Returns whether the assertion was successful (true) or not (false).
func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
pass := !isEmpty(object)
if !pass {
Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...)
}
return pass
}
// getLen try to get length of object.
// return (false, 0) if impossible.
func getLen(x interface{}) (ok bool, length int) {
v := reflect.ValueOf(x)
defer func() {
if e := recover(); e != nil {
ok = false
}
}()
return true, v.Len()
}
// Len asserts that the specified object has specific length.
// Len also fails if the object has a type that len() not accept.
//
// assert.Len(t, mySlice, 3, "The size of slice is not 3")
//
// Returns whether the assertion was successful (true) or not (false).
func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool {
ok, l := getLen(object)
if !ok {
return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...)
}
if l != length {
return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
}
return true
}
// True asserts that the specified value is true.
//
// assert.True(t, myBool, "myBool should be true")
//
// Returns whether the assertion was successful (true) or not (false).
func True(t TestingT, value bool, msgAndArgs ...interface{}) bool {
if value != true {
return Fail(t, "Should be true", msgAndArgs...)
}
return true
}
// False asserts that the specified value is true.
//
// assert.False(t, myBool, "myBool should be false")
//
// Returns whether the assertion was successful (true) or not (false).
func False(t TestingT, value bool, msgAndArgs ...interface{}) bool {
if value != false {
return Fail(t, "Should be false", msgAndArgs...)
}
return true
}
// NotEqual asserts that the specified values are NOT equal.
//
// assert.NotEqual(t, obj1, obj2, "two objects shouldn't be equal")
//
// Returns whether the assertion was successful (true) or not (false).
func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
if ObjectsAreEqual(expected, actual) {
return Fail(t, "Should not be equal", msgAndArgs...)
}
return true
}
// containsElement try loop over the list check if the list includes the element.
// return (false, false) if impossible.
// return (true, false) if element was not found.
// return (true, true) if element was found.
func includeElement(list interface{}, element interface{}) (ok, found bool) {
listValue := reflect.ValueOf(list)
elementValue := reflect.ValueOf(element)
defer func() {
if e := recover(); e != nil {
ok = false
found = false
}
}()
if reflect.TypeOf(list).Kind() == reflect.String {
return true, strings.Contains(listValue.String(), elementValue.String())
}
for i := 0; i < listValue.Len(); i++ {
if listValue.Index(i).Interface() == element {
return true, true
}
}
return true, false
}
// Contains asserts that the specified string or list(array, slice...) contains the
// specified substring or element.
//
// assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'")
// assert.Contains(t, ["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'")
//
// Returns whether the assertion was successful (true) or not (false).
func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
ok, found := includeElement(s, contains)
if !ok {
return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
}
if !found {
return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...)
}
return true
}
// NotContains asserts that the specified string or list(array, slice...) does NOT contain the
// specified substring or element.
//
// assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'")
// assert.NotContains(t, ["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'")
//
// Returns whether the assertion was successful (true) or not (false).
func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
ok, found := includeElement(s, contains)
if !ok {
return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
}
if found {
return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...)
}
return true
}
// Condition uses a Comparison to assert a complex condition.
func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
result := comp()
if !result {
Fail(t, "Condition failed!", msgAndArgs...)
}
return result
}
// PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics
// methods, and represents a simple func that takes no arguments, and returns nothing.
type PanicTestFunc func()
// didPanic returns true if the function passed to it panics. Otherwise, it returns false.
func didPanic(f PanicTestFunc) (bool, interface{}) {
didPanic := false
var message interface{}
func() {
defer func() {
if message = recover(); message != nil {
didPanic = true
}
}()
// call the target function
f()
}()
return didPanic, message
}
// Panics asserts that the code inside the specified PanicTestFunc panics.
//
// assert.Panics(t, func(){
// GoCrazy()
// }, "Calling GoCrazy() should panic")
//
// Returns whether the assertion was successful (true) or not (false).
func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
if funcDidPanic, panicValue := didPanic(f); !funcDidPanic {
return Fail(t, fmt.Sprintf("func %#v should panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...)
}
return true
}
// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
//
// assert.NotPanics(t, func(){
// RemainCalm()
// }, "Calling RemainCalm() should NOT panic")
//
// Returns whether the assertion was successful (true) or not (false).
func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
if funcDidPanic, panicValue := didPanic(f); funcDidPanic {
return Fail(t, fmt.Sprintf("func %#v should not panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...)
}
return true
}
// WithinDuration asserts that the two times are within duration delta of each other.
//
// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s")
//
// Returns whether the assertion was successful (true) or not (false).
func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
dt := expected.Sub(actual)
if dt < -delta || dt > delta {
return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
}
return true
}
func toFloat(x interface{}) (float64, bool) {
var xf float64
xok := true
switch xn := x.(type) {
case uint8:
xf = float64(xn)
case uint16:
xf = float64(xn)
case uint32:
xf = float64(xn)
case uint64:
xf = float64(xn)
case int:
xf = float64(xn)
case int8:
xf = float64(xn)
case int16:
xf = float64(xn)
case int32:
xf = float64(xn)
case int64:
xf = float64(xn)
case float32:
xf = float64(xn)
case float64:
xf = float64(xn)
default:
xok = false
}
return xf, xok
}
// InDelta asserts that the two numerals are within delta of each other.
//
// assert.InDelta(t, math.Pi, (22 / 7.0), 0.01)
//
// Returns whether the assertion was successful (true) or not (false).
func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
af, aok := toFloat(expected)
bf, bok := toFloat(actual)
if !aok || !bok {
return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...)
}
dt := af - bf
if dt < -delta || dt > delta {
return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
}
return true
}
// min(|expected|, |actual|) * epsilon
func calcEpsilonDelta(expected, actual interface{}, epsilon float64) float64 {
af, aok := toFloat(expected)
bf, bok := toFloat(actual)
if !aok || !bok {
// invalid input
return 0
}
if af < 0 {
af = -af
}
if bf < 0 {
bf = -bf
}
var delta float64
if af < bf {
delta = af * epsilon
} else {
delta = bf * epsilon
}
return delta
}
// InEpsilon asserts that expected and actual have a relative error less than epsilon
//
// Returns whether the assertion was successful (true) or not (false).
func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
delta := calcEpsilonDelta(expected, actual, epsilon)
return InDelta(t, expected, actual, delta, msgAndArgs...)
}
/*
Errors
*/
// NoError asserts that a function returned no error (i.e. `nil`).
//
// actualObj, err := SomeFunction()
// if assert.NoError(t, err) {
// assert.Equal(t, actualObj, expectedObj)
// }
//
// Returns whether the assertion was successful (true) or not (false).
func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
if isNil(err) {
return true
}
return Fail(t, fmt.Sprintf("No error is expected but got %v", err), msgAndArgs...)
}
// Error asserts that a function returned an error (i.e. not `nil`).
//
// actualObj, err := SomeFunction()
// if assert.Error(t, err, "An error was expected") {
// assert.Equal(t, err, expectedError)
// }
//
// Returns whether the assertion was successful (true) or not (false).
func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
message := messageFromMsgAndArgs(msgAndArgs...)
return NotNil(t, err, "An error is expected but got nil. %s", message)
}
// EqualError asserts that a function returned an error (i.e. not `nil`)
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
// if assert.Error(t, err, "An error was expected") {
// assert.Equal(t, err, expectedError)
// }
//
// Returns whether the assertion was successful (true) or not (false).
func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool {
message := messageFromMsgAndArgs(msgAndArgs...)
if !NotNil(t, theError, "An error is expected but got nil. %s", message) {
return false
}
s := "An error with value \"%s\" is expected but got \"%s\". %s"
return Equal(t, theError.Error(), errString,
s, errString, theError.Error(), message)
}
// matchRegexp return true if a specified regexp matches a string.
func matchRegexp(rx interface{}, str interface{}) bool {
var r *regexp.Regexp
if rr, ok := rx.(*regexp.Regexp); ok {
r = rr
} else {
r = regexp.MustCompile(fmt.Sprint(rx))
}
return (r.FindStringIndex(fmt.Sprint(str)) != nil)
}
// Regexp asserts that a specified regexp matches a string.
//
// assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
// assert.Regexp(t, "start...$", "it's not starting")
//
// Returns whether the assertion was successful (true) or not (false).
func Regexp(t TestingT, rx interface{}, str interface{}) bool {
match := matchRegexp(rx, str)
if !match {
Fail(t, "Expect \"%s\" to match \"%s\"")
}
return match
}
// NotRegexp asserts that a specified regexp does not match a string.
//
// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
// assert.NotRegexp(t, "^start", "it's not starting")
//
// Returns whether the assertion was successful (true) or not (false).
func NotRegexp(t TestingT, rx interface{}, str interface{}) bool {
match := matchRegexp(rx, str)
if match {
Fail(t, "Expect \"%s\" to NOT match \"%s\"")
}
return !match
}
================================================
FILE: vendor/github.com/stretchr/testify/assert/assertions_test.go
================================================
package assert
import (
"errors"
"regexp"
"testing"
"time"
)
// AssertionTesterInterface defines an interface to be used for testing assertion methods
type AssertionTesterInterface interface {
TestMethod()
}
// AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface
type AssertionTesterConformingObject struct {
}
func (a *AssertionTesterConformingObject) TestMethod() {
}
// AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface
type AssertionTesterNonConformingObject struct {
}
func TestObjectsAreEqual(t *testing.T) {
if !ObjectsAreEqual("Hello World", "Hello World") {
t.Error("objectsAreEqual should return true")
}
if !ObjectsAreEqual(123, 123) {
t.Error("objectsAreEqual should return true")
}
if !ObjectsAreEqual(123.5, 123.5) {
t.Error("objectsAreEqual should return true")
}
if !ObjectsAreEqual([]byte("Hello World"), []byte("Hello World")) {
t.Error("objectsAreEqual should return true")
}
if !ObjectsAreEqual(nil, nil) {
t.Error("objectsAreEqual should return true")
}
}
func TestImplements(t *testing.T) {
mockT := new(testing.T)
if !Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) {
t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface")
}
if Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) {
t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface")
}
}
func TestIsType(t *testing.T) {
mockT := new(testing.T)
if !IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) {
t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject")
}
if IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) {
t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject")
}
}
func TestEqual(t *testing.T) {
mockT := new(testing.T)
if !Equal(mockT, "Hello World", "Hello World") {
t.Error("Equal should return true")
}
if !Equal(mockT, 123, 123) {
t.Error("Equal should return true")
}
if !Equal(mockT, 123.5, 123.5) {
t.Error("Equal should return true")
}
if !Equal(mockT, []byte("Hello World"), []byte("Hello World")) {
t.Error("Equal should return true")
}
if !Equal(mockT, nil, nil) {
t.Error("Equal should return true")
}
if !Equal(mockT, int32(123), int64(123)) {
t.Error("Equal should return true")
}
if !Equal(mockT, int64(123), uint64(123)) {
t.Error("Equal should return true")
}
}
func TestNotNil(t *testing.T) {
mockT := new(testing.T)
if !NotNil(mockT, new(AssertionTesterConformingObject)) {
t.Error("NotNil should return true: object is not nil")
}
if NotNil(mockT, nil) {
t.Error("NotNil should return false: object is nil")
}
}
func TestNil(t *testing.T) {
mockT := new(testing.T)
if !Nil(mockT, nil) {
t.Error("Nil should return true: object is nil")
}
if Nil(mockT, new(AssertionTesterConformingObject)) {
t.Error("Nil should return false: object is not nil")
}
}
func TestTrue(t *testing.T) {
mockT := new(testing.T)
if !True(mockT, true) {
t.Error("True should return true")
}
if True(mockT, false) {
t.Error("True should return false")
}
}
func TestFalse(t *testing.T) {
mockT := new(testing.T)
if !False(mockT, false) {
t.Error("False should return true")
}
if False(mockT, true) {
t.Error("False should return false")
}
}
func TestExactly(t *testing.T) {
mockT := new(testing.T)
a := float32(1)
b := float64(1)
c := float32(1)
d := float32(2)
if Exactly(mockT, a, b) {
t.Error("Exactly should return false")
}
if Exactly(mockT, a, d) {
t.Error("Exactly should return false")
}
if !Exactly(mockT, a, c) {
t.Error("Exactly should return true")
}
if Exactly(mockT, nil, a) {
t.Error("Exactly should return false")
}
if Exactly(mockT, a, nil) {
t.Error("Exactly should return false")
}
}
func TestNotEqual(t *testing.T) {
mockT := new(testing.T)
if !NotEqual(mockT, "Hello World", "Hello World!") {
t.Error("NotEqual should return true")
}
if !NotEqual(mockT, 123, 1234) {
t.Error("NotEqual should return true")
}
if !NotEqual(mockT, 123.5, 123.55) {
t.Error("NotEqual should return true")
}
if !NotEqual(mockT, []byte("Hello World"), []byte("Hello World!")) {
t.Error("NotEqual should return true")
}
if !NotEqual(mockT, nil, new(AssertionTesterConformingObject)) {
t.Error("NotEqual should return true")
}
if NotEqual(mockT, "Hello World", "Hello World") {
t.Error("NotEqual should return false")
}
if NotEqual(mockT, 123, 123) {
t.Error("NotEqual should return false")
}
if NotEqual(mockT, 123.5, 123.5) {
t.Error("NotEqual should return false")
}
if NotEqual(mockT, []byte("Hello World"), []byte("Hello World")) {
t.Error("NotEqual should return false")
}
if NotEqual(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) {
t.Error("NotEqual should return false")
}
}
func TestContains(t *testing.T) {
mockT := new(testing.T)
list := []string{"Foo", "Bar"}
if !Contains(mockT, "Hello World", "Hello") {
t.Error("Contains should return true: \"Hello World\" contains \"Hello\"")
}
if Contains(mockT, "Hello World", "Salut") {
t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"")
}
if !Contains(mockT, list, "Bar") {
t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Bar\"")
}
if Contains(mockT, list, "Salut") {
t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"")
}
}
func TestNotContains(t *testing.T) {
mockT := new(testing.T)
list := []string{"Foo", "Bar"}
if !NotContains(mockT, "Hello World", "Hello!") {
t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"")
}
if NotContains(mockT, "Hello World", "Hello") {
t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"")
}
if !NotContains(mockT, list, "Foo!") {
t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"")
}
if NotContains(mockT, list, "Foo") {
t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"")
}
}
func Test_includeElement(t *testing.T) {
list1 := []string{"Foo", "Bar"}
list2 := []int{1, 2}
ok, found := includeElement("Hello World", "World")
True(t, ok)
True(t, found)
ok, found = includeElement(list1, "Foo")
True(t, ok)
True(t, found)
ok, found = includeElement(list1, "Bar")
True(t, ok)
True(t, found)
ok, found = includeElement(list2, 1)
True(t, ok)
True(t, found)
ok, found = includeElement(list2, 2)
True(t, ok)
True(t, found)
ok, found = includeElement(list1, "Foo!")
True(t, ok)
False(t, found)
ok, found = includeElement(list2, 3)
True(t, ok)
False(t, found)
ok, found = includeElement(list2, "1")
True(t, ok)
False(t, found)
ok, found = includeElement(1433, "1")
False(t, ok)
False(t, found)
}
func TestCondition(t *testing.T) {
mockT := new(testing.T)
if !Condition(mockT, func() bool { return true }, "Truth") {
t.Error("Condition should return true")
}
if Condition(mockT, func() bool { return false }, "Lie") {
t.Error("Condition should return false")
}
}
func TestDidPanic(t *testing.T) {
if funcDidPanic, _ := didPanic(func() {
panic("Panic!")
}); !funcDidPanic {
t.Error("didPanic should return true")
}
if funcDidPanic, _ := didPanic(func() {
}); funcDidPanic {
t.Error("didPanic should return false")
}
}
func TestPanics(t *testing.T) {
mockT := new(testing.T)
if !Panics(mockT, func() {
panic("Panic!")
}) {
t.Error("Panics should return true")
}
if Panics(mockT, func() {
}) {
t.Error("Panics should return false")
}
}
func TestNotPanics(t *testing.T) {
mockT := new(testing.T)
if !NotPanics(mockT, func() {
}) {
t.Error("NotPanics should return true")
}
if NotPanics(mockT, func() {
panic("Panic!")
}) {
t.Error("NotPanics should return false")
}
}
func TestEqual_Funcs(t *testing.T) {
type f func() int
f1 := func() int { return 1 }
f2 := func() int { return 2 }
f1Copy := f1
Equal(t, f1Copy, f1, "Funcs are the same and should be considered equal")
NotEqual(t, f1, f2, "f1 and f2 are different")
}
func TestNoError(t *testing.T) {
mockT := new(testing.T)
// start with a nil error
var err error
True(t, NoError(mockT, err), "NoError should return True for nil arg")
// now set an error
err = errors.New("some error")
False(t, NoError(mockT, err), "NoError with error should return False")
}
func TestError(t *testing.T) {
mockT := new(testing.T)
// start with a nil error
var err error
False(t, Error(mockT, err), "Error should return False for nil arg")
// now set an error
err = errors.New("some error")
True(t, Error(mockT, err), "Error with error should return True")
}
func TestEqualError(t *testing.T) {
mockT := new(testing.T)
// start with a nil error
var err error
False(t, EqualError(mockT, err, ""),
"EqualError should return false for nil arg")
// now set an error
err = errors.New("some error")
False(t, EqualError(mockT, err, "Not some error"),
"EqualError should return false for different error string")
True(t, EqualError(mockT, err, "some error"),
"EqualError should return true")
}
func Test_isEmpty(t *testing.T) {
chWithValue := make(chan struct{}, 1)
chWithValue <- struct{}{}
True(t, isEmpty(""))
True(t, isEmpty(nil))
True(t, isEmpty([]string{}))
True(t, isEmpty(0))
True(t, isEmpty(int32(0)))
True(t, isEmpty(int64(0)))
True(t, isEmpty(false))
True(t, isEmpty(map[string]string{}))
True(t, isEmpty(new(time.Time)))
True(t, isEmpty(make(chan struct{})))
False(t, isEmpty("something"))
False(t, isEmpty(errors.New("something")))
False(t, isEmpty([]string{"something"}))
False(t, isEmpty(1))
False(t, isEmpty(true))
False(t, isEmpty(map[string]string{"Hello": "World"}))
False(t, isEmpty(chWithValue))
}
func TestEmpty(t *testing.T) {
mockT := new(testing.T)
chWithValue := make(chan struct{}, 1)
chWithValue <- struct{}{}
True(t, Empty(mockT, ""), "Empty string is empty")
True(t, Empty(mockT, nil), "Nil is empty")
True(t, Empty(mockT, []string{}), "Empty string array is empty")
True(t, Empty(mockT, 0), "Zero int value is empty")
True(t, Empty(mockT, false), "False value is empty")
True(t, Empty(mockT, make(chan struct{})), "Channel without values is empty")
False(t, Empty(mockT, "something"), "Non Empty string is not empty")
False(t, Empty(mockT, errors.New("something")), "Non nil object is not empty")
False(t, Empty(mockT, []string{"something"}), "Non empty string array is not empty")
False(t, Empty(mockT, 1), "Non-zero int value is not empty")
False(t, Empty(mockT, true), "True value is not empty")
False(t, Empty(mockT, chWithValue), "Channel with values is not empty")
}
func TestNotEmpty(t *testing.T) {
mockT := new(testing.T)
chWithValue := make(chan struct{}, 1)
chWithValue <- struct{}{}
False(t, NotEmpty(mockT, ""), "Empty string is empty")
False(t, NotEmpty(mockT, nil), "Nil is empty")
False(t, NotEmpty(mockT, []string{}), "Empty string array is empty")
False(t, NotEmpty(mockT, 0), "Zero int value is empty")
False(t, NotEmpty(mockT, false), "False value is empty")
False(t, NotEmpty(mockT, make(chan struct{})), "Channel without values is empty")
True(t, NotEmpty(mockT, "something"), "Non Empty string is not empty")
True(t, NotEmpty(mockT, errors.New("something")), "Non nil object is not empty")
True(t, NotEmpty(mockT, []string{"something"}), "Non empty string array is not empty")
True(t, NotEmpty(mockT, 1), "Non-zero int value is not empty")
True(t, NotEmpty(mockT, true), "True value is not empty")
True(t, NotEmpty(mockT, chWithValue), "Channel with values is not empty")
}
func Test_getLen(t *testing.T) {
falseCases := []interface{}{
nil,
0,
true,
false,
'A',
struct{}{},
}
for _, v := range falseCases {
ok, l := getLen(v)
False(t, ok, "Expected getLen fail to get length of %#v", v)
Equal(t, 0, l, "getLen should return 0 for %#v", v)
}
ch := make(chan int, 5)
ch <- 1
ch <- 2
ch <- 3
trueCases := []struct {
v interface{}
l int
}{
{[]int{1, 2, 3}, 3},
{[...]int{1, 2, 3}, 3},
{"ABC", 3},
{map[int]int{1: 2, 2: 4, 3: 6}, 3},
{ch, 3},
{[]int{}, 0},
{map[int]int{}, 0},
{make(chan int), 0},
{[]int(nil), 0},
{map[int]int(nil), 0},
{(chan int)(nil), 0},
}
for _, c := range trueCases {
ok, l := getLen(c.v)
True(t, ok, "Expected getLen success to get length of %#v", c.v)
Equal(t, c.l, l)
}
}
func TestLen(t *testing.T) {
mockT := new(testing.T)
False(t, Len(mockT, nil, 0), "nil does not have length")
False(t, Len(mockT, 0, 0), "int does not have length")
False(t, Len(mockT, true, 0), "true does not have length")
False(t, Len(mockT, false, 0), "false does not have length")
False(t, Len(mockT, 'A', 0), "Rune does not have length")
False(t, Len(mockT, struct{}{}, 0), "Struct does not have length")
ch := make(chan int, 5)
ch <- 1
ch <- 2
ch <- 3
cases := []struct {
v interface{}
l int
}{
{[]int{1, 2, 3}, 3},
{[...]int{1, 2, 3}, 3},
{"ABC", 3},
{map[int]int{1: 2, 2: 4, 3: 6}, 3},
{ch, 3},
{[]int{}, 0},
{map[int]int{}, 0},
{make(chan int), 0},
{[]int(nil), 0},
{map[int]int(nil), 0},
{(chan int)(nil), 0},
}
for _, c := range cases {
True(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l)
}
cases = []struct {
v interface{}
l int
}{
{[]int{1, 2, 3}, 4},
{[...]int{1, 2, 3}, 2},
{"ABC", 2},
{map[int]int{1: 2, 2: 4, 3: 6}, 4},
{ch, 2},
{[]int{}, 1},
{map[int]int{}, 1},
{make(chan int), 1},
{[]int(nil), 1},
{map[int]int(nil), 1},
{(chan int)(nil), 1},
}
for _, c := range cases {
False(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l)
}
}
func TestWithinDuration(t *testing.T) {
mockT := new(testing.T)
a := time.Now()
b := a.Add(10 * time.Second)
True(t, WithinDuration(mockT, a, b, 10*time.Second), "A 10s difference is within a 10s time difference")
True(t, WithinDuration(mockT, b, a, 10*time.Second), "A 10s difference is within a 10s time difference")
False(t, WithinDuration(mockT, a, b, 9*time.Second), "A 10s difference is not within a 9s time difference")
False(t, WithinDuration(mockT, b, a, 9*time.Second), "A 10s difference is not within a 9s time difference")
False(t, WithinDuration(mockT, a, b, -9*time.Second), "A 10s difference is not within a 9s time difference")
False(t, WithinDuration(mockT, b, a, -9*time.Second), "A 10s difference is not within a 9s time difference")
False(t, WithinDuration(mockT, a, b, -11*time.Second), "A 10s difference is not within a 9s time difference")
False(t, WithinDuration(mockT, b, a, -11*time.Second), "A 10s difference is not within a 9s time difference")
}
func TestInDelta(t *testing.T) {
mockT := new(testing.T)
True(t, InDelta(mockT, 1.001, 1, 0.01), "|1.001 - 1| <= 0.01")
True(t, InDelta(mockT, 1, 1.001, 0.01), "|1 - 1.001| <= 0.01")
True(t, InDelta(mockT, 1, 2, 1), "|1 - 2| <= 1")
False(t, InDelta(mockT, 1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail")
False(t, InDelta(mockT, 2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail")
False(t, InDelta(mockT, "", nil, 1), "Expected non numerals to fail")
cases := []struct {
a, b interface{}
delta float64
}{
{uint8(2), uint8(1), 1},
{uint16(2), uint16(1), 1},
{uint32(2), uint32(1), 1},
{uint64(2), uint64(1), 1},
{int(2), int(1), 1},
{int8(2), int8(1), 1},
{int16(2), int16(1), 1},
{int32(2), int32(1), 1},
{int64(2), int64(1), 1},
{float32(2), float32(1), 1},
{float64(2), float64(1), 1},
}
for _, tc := range cases {
True(t, InDelta(mockT, tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta)
}
}
func TestInEpsilon(t *testing.T) {
mockT := new(testing.T)
cases := []struct {
a, b interface{}
epsilon float64
}{
{uint8(2), uint16(2), .001},
{2.1, 2.2, 0.1},
{2.2, 2.1, 0.1},
{-2.1, -2.2, 0.1},
{-2.2, -2.1, 0.1},
{uint64(100), uint8(101), 0.01},
{0.1, -0.1, 2},
}
for _, tc := range cases {
True(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon))
}
cases = []struct {
a, b interface{}
epsilon float64
}{
{uint8(2), int16(-2), .001},
{uint64(100), uint8(102), 0.01},
{2.1, 2.2, 0.001},
{2.2, 2.1, 0.001},
{2.1, -2.2, 1},
{2.1, "bla-bla", 0},
{0.1, -0.1, 1.99},
}
for _, tc := range cases {
False(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon))
}
}
func TestRegexp(t *testing.T) {
mockT := new(testing.T)
cases := []struct {
rx, str string
}{
{"^start", "start of the line"},
{"end$", "in the end"},
{"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"},
}
for _, tc := range cases {
True(t, Regexp(mockT, tc.rx, tc.str))
True(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
False(t, NotRegexp(mockT, tc.rx, tc.str))
False(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
}
cases = []struct {
rx, str string
}{
{"^asdfastart", "Not the start of the line"},
{"end$", "in the end."},
{"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"},
}
for _, tc := range cases {
False(t, Regexp(mockT, tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str)
False(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
True(t, NotRegexp(mockT, tc.rx, tc.str))
True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
}
}
================================================
FILE: vendor/github.com/stretchr/testify/assert/doc.go
================================================
// A set of comprehensive testing tools for use with the normal Go testing system.
//
// Example Usage
//
// The following is a complete example using assert in a standard test function:
// import (
// "testing"
// "github.com/stretchr/testify/assert"
// )
//
// func TestSomething(t *testing.T) {
//
// var a string = "Hello"
// var b string = "Hello"
//
// assert.Equal(t, a, b, "The two words should be the same.")
//
// }
//
// if you assert many times, use the below:
//
// import (
// "testing"
// "github.com/stretchr/testify/assert"
// )
//
// func TestSomething(t *testing.T) {
// assert := assert.New(t)
//
// var a string = "Hello"
// var b string = "Hello"
//
// assert.Equal(a, b, "The two words should be the same.")
// }
//
// Assertions
//
// Assertions allow you to easily write test code, and are global funcs in the `assert` package.
// All assertion functions take, as the first argument, the `*testing.T` object provided by the
// testing framework. This allows the assertion funcs to write the failings and other details to
// the correct place.
//
// Every assertion function also takes an optional string message as the final argument,
// allowing custom error messages to be appended to the message the assertion method outputs.
//
// Here is an overview of the assert functions:
//
// assert.Equal(t, expected, actual [, message [, format-args])
//
// assert.NotEqual(t, notExpected, actual [, message [, format-args]])
//
// assert.True(t, actualBool [, message [, format-args]])
//
// assert.False(t, actualBool [, message [, format-args]])
//
// assert.Nil(t, actualObject [, message [, format-args]])
//
// assert.NotNil(t, actualObject [, message [, format-args]])
//
// assert.Empty(t, actualObject [, message [, format-args]])
//
// assert.NotEmpty(t, actualObject [, message [, format-args]])
//
// assert.Len(t, actualObject, expectedLength, [, message [, format-args]])
//
// assert.Error(t, errorObject [, message [, format-args]])
//
// assert.NoError(t, errorObject [, message [, format-args]])
//
// assert.EqualError(t, theError, errString [, message [, format-args]])
//
// assert.Implements(t, (*MyInterface)(nil), new(MyObject) [,message [, format-args]])
//
// assert.IsType(t, expectedObject, actualObject [, message [, format-args]])
//
// assert.Contains(t, stringOrSlice, substringOrElement [, message [, format-args]])
//
// assert.NotContains(t, stringOrSlice, substringOrElement [, message [, format-args]])
//
// assert.Panics(t, func(){
//
// // call code that should panic
//
// } [, message [, format-args]])
//
// assert.NotPanics(t, func(){
//
// // call code that should not panic
//
// } [, message [, format-args]])
//
// assert.WithinDuration(t, timeA, timeB, deltaTime, [, message [, format-args]])
//
// assert.InDelta(t, numA, numB, delta, [, message [, format-args]])
//
// assert.InEpsilon(t, numA, numB, epsilon, [, message [, format-args]])
//
// assert package contains Assertions object. it has assertion methods.
//
// Here is an overview of the assert functions:
// assert.Equal(expected, actual [, message [, format-args])
//
// assert.NotEqual(notExpected, actual [, message [, format-args]])
//
// assert.True(actualBool [, message [, format-args]])
//
// assert.False(actualBool [, message [, format-args]])
//
// assert.Nil(actualObject [, message [, format-args]])
//
// assert.NotNil(actualObject [, message [, format-args]])
//
// assert.Empty(actualObject [, message [, format-args]])
//
// assert.NotEmpty(actualObject [, message [, format-args]])
//
// assert.Len(actualObject, expectedLength, [, message [, format-args]])
//
// assert.Error(errorObject [, message [, format-args]])
//
// assert.NoError(errorObject [, message [, format-args]])
//
// assert.EqualError(theError, errString [, message [, format-args]])
//
// assert.Implements((*MyInterface)(nil), new(MyObject) [,message [, format-args]])
//
// assert.IsType(expectedObject, actualObject [, message [, format-args]])
//
// assert.Contains(stringOrSlice, substringOrElement [, message [, format-args]])
//
// assert.NotContains(stringOrSlice, substringOrElement [, message [, format-args]])
//
// assert.Panics(func(){
//
// // call code that should panic
//
// } [, message [, format-args]])
//
// assert.NotPanics(func(){
//
// // call code that should not panic
//
// } [, message [, format-args]])
//
// assert.WithinDuration(timeA, timeB, deltaTime, [, message [, format-args]])
//
// assert.InDelta(numA, numB, delta, [, message [, format-args]])
//
// assert.InEpsilon(numA, numB, epsilon, [, message [, format-args]])
package assert
================================================
FILE: vendor/github.com/stretchr/testify/assert/errors.go
================================================
package assert
import (
"errors"
)
// AnError is an error instance useful for testing. If the code does not care
// about error specifics, and only needs to return the error for example, this
// error should be used to make the test code more readable.
var AnError = errors.New("assert.AnError general error for testing")
================================================
FILE: vendor/github.com/stretchr/testify/assert/forward_assertions.go
================================================
package assert
import "time"
type Assertions struct {
t TestingT
}
func New(t TestingT) *Assertions {
return &Assertions{
t: t,
}
}
// Fail reports a failure through
func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool {
return Fail(a.t, failureMessage, msgAndArgs...)
}
// Implements asserts that an object is implemented by the specified interface.
//
// assert.Implements((*MyInterface)(nil), new(MyObject), "MyObject")
func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
return Implements(a.t, interfaceObject, object, msgAndArgs...)
}
// IsType asserts that the specified objects are of the same type.
func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
return IsType(a.t, expectedType, object, msgAndArgs...)
}
// Equal asserts that two objects are equal.
//
// assert.Equal(123, 123, "123 and 123 should be equal")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) Equal(expected, actual interface{}, msgAndArgs ...interface{}) bool {
return Equal(a.t, expected, actual, msgAndArgs...)
}
// Exactly asserts that two objects are equal is value and type.
//
// assert.Exactly(int32(123), int64(123), "123 and 123 should NOT be equal")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) Exactly(expected, actual interface{}, msgAndArgs ...interface{}) bool {
return Exactly(a.t, expected, actual, msgAndArgs...)
}
// NotNil asserts that the specified object is not nil.
//
// assert.NotNil(err, "err should be something")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool {
return NotNil(a.t, object, msgAndArgs...)
}
// Nil asserts that the specified object is nil.
//
// assert.Nil(err, "err should be nothing")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool {
return Nil(a.t, object, msgAndArgs...)
}
// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or a
// slice with len == 0.
//
// assert.Empty(obj)
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool {
return Empty(a.t, object, msgAndArgs...)
}
// Empty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or a
// slice with len == 0.
//
// if assert.NotEmpty(obj) {
// assert.Equal("two", obj[1])
// }
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool {
return NotEmpty(a.t, object, msgAndArgs...)
}
// Len asserts that the specified object has specific length.
// Len also fails if the object has a type that len() not accept.
//
// assert.Len(mySlice, 3, "The size of slice is not 3")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool {
return Len(a.t, object, length, msgAndArgs...)
}
// True asserts that the specified value is true.
//
// assert.True(myBool, "myBool should be true")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool {
return True(a.t, value, msgAndArgs...)
}
// False asserts that the specified value is true.
//
// assert.False(myBool, "myBool should be false")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool {
return False(a.t, value, msgAndArgs...)
}
// NotEqual asserts that the specified values are NOT equal.
//
// assert.NotEqual(obj1, obj2, "two objects shouldn't be equal")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) NotEqual(expected, actual interface{}, msgAndArgs ...interface{}) bool {
return NotEqual(a.t, expected, actual, msgAndArgs...)
}
// Contains asserts that the specified string contains the specified substring.
//
// assert.Contains("Hello World", "World", "But 'Hello World' does contain 'World'")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) Contains(s, contains interface{}, msgAndArgs ...interface{}) bool {
return Contains(a.t, s, contains, msgAndArgs...)
}
// NotContains asserts that the specified string does NOT contain the specified substring.
//
// assert.NotContains("Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) NotContains(s, contains interface{}, msgAndArgs ...interface{}) bool {
return NotContains(a.t, s, contains, msgAndArgs...)
}
// Uses a Comparison to assert a complex condition.
func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool {
return Condition(a.t, comp, msgAndArgs...)
}
// Panics asserts that the code inside the specified PanicTestFunc panics.
//
// assert.Panics(func(){
// GoCrazy()
// }, "Calling GoCrazy() should panic")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool {
return Panics(a.t, f, msgAndArgs...)
}
// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
//
// assert.NotPanics(func(){
// RemainCalm()
// }, "Calling RemainCalm() should NOT panic")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool {
return NotPanics(a.t, f, msgAndArgs...)
}
// WithinDuration asserts that the two times are within duration delta of each other.
//
// assert.WithinDuration(time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) WithinDuration(expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
return WithinDuration(a.t, expected, actual, delta, msgAndArgs...)
}
// InDelta asserts that the two numerals are within delta of each other.
//
// assert.InDelta(t, math.Pi, (22 / 7.0), 0.01)
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) InDelta(expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
return InDelta(a.t, expected, actual, delta, msgAndArgs...)
}
// InEpsilon asserts that expected and actual have a relative error less than epsilon
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) InEpsilon(expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
return InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...)
}
// NoError asserts that a function returned no error (i.e. `nil`).
//
// actualObj, err := SomeFunction()
// if assert.NoError(err) {
// assert.Equal(actualObj, expectedObj)
// }
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) NoError(theError error, msgAndArgs ...interface{}) bool {
return NoError(a.t, theError, msgAndArgs...)
}
// Error asserts that a function returned an error (i.e. not `nil`).
//
// actualObj, err := SomeFunction()
// if assert.Error(err, "An error was expected") {
// assert.Equal(err, expectedError)
// }
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) Error(theError error, msgAndArgs ...interface{}) bool {
return Error(a.t, theError, msgAndArgs...)
}
// EqualError asserts that a function returned an error (i.e. not `nil`)
// and that it is equal to the provided error.
//
// actualObj, err := SomeFunction()
// if assert.Error(err, "An error was expected") {
// assert.Equal(err, expectedError)
// }
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool {
return EqualError(a.t, theError, errString, msgAndArgs...)
}
// Regexp asserts that a specified regexp matches a string.
//
// assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
// assert.Regexp(t, "start...$", "it's not starting")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) Regexp(rx interface{}, str interface{}) bool {
return Regexp(a.t, rx, str)
}
// NotRegexp asserts that a specified regexp does not match a string.
//
// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
// assert.NotRegexp(t, "^start", "it's not starting")
//
// Returns whether the assertion was successful (true) or not (false).
func (a *Assertions) NotRegexp(rx interface{}, str interface{}) bool {
return NotRegexp(a.t, rx, str)
}
================================================
FILE: vendor/github.com/stretchr/testify/assert/forward_assertions_test.go
================================================
package assert
import (
"errors"
"regexp"
"testing"
"time"
)
func TestImplementsWrapper(t *testing.T) {
assert := New(new(testing.T))
if !assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) {
t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface")
}
if assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) {
t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface")
}
}
func TestIsTypeWrapper(t *testing.T) {
assert := New(new(testing.T))
if !assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) {
t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject")
}
if assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) {
t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject")
}
}
func TestEqualWrapper(t *testing.T) {
assert := New(new(testing.T))
if !assert.Equal("Hello World", "Hello World") {
t.Error("Equal should return true")
}
if !assert.Equal(123, 123) {
t.Error("Equal should return true")
}
if !assert.Equal(123.5, 123.5) {
t.Error("Equal should return true")
}
if !assert.Equal([]byte("Hello World"), []byte("Hello World")) {
t.Error("Equal should return true")
}
if !assert.Equal(nil, nil) {
t.Error("Equal should return true")
}
}
func TestNotNilWrapper(t *testing.T) {
assert := New(new(testing.T))
if !assert.NotNil(new(AssertionTesterConformingObject)) {
t.Error("NotNil should return true: object is not nil")
}
if assert.NotNil(nil) {
t.Error("NotNil should return false: object is nil")
}
}
func TestNilWrapper(t *testing.T) {
assert := New(new(testing.T))
if !assert.Nil(nil) {
t.Error("Nil should return true: object is nil")
}
if assert.Nil(new(AssertionTesterConformingObject)) {
t.Error("Nil should return false: object is not nil")
}
}
func TestTrueWrapper(t *testing.T) {
assert := New(new(testing.T))
if !assert.True(true) {
t.Error("True should return true")
}
if assert.True(false) {
t.Error("True should return false")
}
}
func TestFalseWrapper(t *testing.T) {
assert := New(new(testing.T))
if !assert.False(false) {
t.Error("False should return true")
}
if assert.False(true) {
t.Error("False should return false")
}
}
func TestExactlyWrapper(t *testing.T) {
assert := New(new(testing.T))
a := float32(1)
b := float64(1)
c := float32(1)
d := float32(2)
if assert.Exactly(a, b) {
t.Error("Exactly should return false")
}
if assert.Exactly(a, d) {
t.Error("Exactly should return false")
}
if !assert.Exactly(a, c) {
t.Error("Exactly should return true")
}
if assert.Exactly(nil, a) {
t.Error("Exactly should return false")
}
if assert.Exactly(a, nil) {
t.Error("Exactly should return false")
}
}
func TestNotEqualWrapper(t *testing.T) {
assert := New(new(testing.T))
if !assert.NotEqual("Hello World", "Hello World!") {
t.Error("NotEqual should return true")
}
if !assert.NotEqual(123, 1234) {
t.Error("NotEqual should return true")
}
if !assert.NotEqual(123.5, 123.55) {
t.Error("NotEqual should return true")
}
if !assert.NotEqual([]byte("Hello World"), []byte("Hello World!")) {
t.Error("NotEqual should return true")
}
if !assert.NotEqual(nil, new(AssertionTesterConformingObject)) {
t.Error("NotEqual should return true")
}
}
func TestContainsWrapper(t *testing.T) {
assert := New(new(testing.T))
list := []string{"Foo", "Bar"}
if !assert.Contains("Hello World", "Hello") {
t.Error("Contains should return true: \"Hello World\" contains \"Hello\"")
}
if assert.Contains("Hello World", "Salut") {
t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"")
}
if !assert.Contains(list, "Foo") {
t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"")
}
if assert.Contains(list, "Salut") {
t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"")
}
}
func TestNotContainsWrapper(t *testing.T) {
assert := New(new(testing.T))
list := []string{"Foo", "Bar"}
if !assert.NotContains("Hello World", "Hello!") {
t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"")
}
if assert.NotContains("Hello World", "Hello") {
t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"")
}
if !assert.NotContains(list, "Foo!") {
t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"")
}
if assert.NotContains(list, "Foo") {
t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"")
}
}
func TestConditionWrapper(t *testing.T) {
assert := New(new(testing.T))
if !assert.Condition(func() bool { return true }, "Truth") {
t.Error("Condition should return true")
}
if assert.Condition(func() bool { return false }, "Lie") {
t.Error("Condition should return false")
}
}
func TestDidPanicWrapper(t *testing.T) {
if funcDidPanic, _ := didPanic(func() {
panic("Panic!")
}); !funcDidPanic {
t.Error("didPanic should return true")
}
if funcDidPanic, _ := didPanic(func() {
}); funcDidPanic {
t.Error("didPanic should return false")
}
}
func TestPanicsWrapper(t *testing.T) {
assert := New(new(testing.T))
if !assert.Panics(func() {
panic("Panic!")
}) {
t.Error("Panics should return true")
}
if assert.Panics(func() {
}) {
t.Error("Panics should return false")
}
}
func TestNotPanicsWrapper(t *testing.T) {
assert := New(new(testing.T))
if !assert.NotPanics(func() {
}) {
t.Error("NotPanics should return true")
}
if assert.NotPanics(func() {
panic("Panic!")
}) {
t.Error("NotPanics should return false")
}
}
func TestEqualWrapper_Funcs(t *testing.T) {
assert := New(t)
type f func() int
var f1 f = func() int { return 1 }
var f2 f = func() int { return 2 }
var f1_copy f = f1
assert.Equal(f1_copy, f1, "Funcs are the same and should be considered equal")
assert.NotEqual(f1, f2, "f1 and f2 are different")
}
func TestNoErrorWrapper(t *testing.T) {
assert := New(t)
mockAssert := New(new(testing.T))
// start with a nil error
var err error = nil
assert.True(mockAssert.NoError(err), "NoError should return True for nil arg")
// now set an error
err = errors.New("Some error")
assert.False(mockAssert.NoError(err), "NoError with error should return False")
}
func TestErrorWrapper(t *testing.T) {
assert := New(t)
mockAssert := New(new(testing.T))
// start with a nil error
var err error = nil
assert.False(mockAssert.Error(err), "Error should return False for nil arg")
// now set an error
err = errors.New("Some error")
assert.True(mockAssert.Error(err), "Error with error should return True")
}
func TestEqualErrorWrapper(t *testing.T) {
assert := New(t)
mockAssert := New(new(testing.T))
// start with a nil error
var err error
assert.False(mockAssert.EqualError(err, ""),
"EqualError should return false for nil arg")
// now set an error
err = errors.New("some error")
assert.False(mockAssert.EqualError(err, "Not some error"),
"EqualError should return false for different error string")
assert.True(mockAssert.EqualError(err, "some error"),
"EqualError should return true")
}
func TestEmptyWrapper(t *testing.T) {
assert := New(t)
mockAssert := New(new(testing.T))
assert.True(mockAssert.Empty(""), "Empty string is empty")
assert.True(mockAssert.Empty(nil), "Nil is empty")
assert.True(mockAssert.Empty([]string{}), "Empty string array is empty")
assert.True(mockAssert.Empty(0), "Zero int value is empty")
assert.True(mockAssert.Empty(false), "False value is empty")
assert.False(mockAssert.Empty("something"), "Non Empty string is not empty")
assert.False(mockAssert.Empty(errors.New("something")), "Non nil object is not empty")
assert.False(mockAssert.Empty([]string{"something"}), "Non empty string array is not empty")
assert.False(mockAssert.Empty(1), "Non-zero int value is not empty")
assert.False(mockAssert.Empty(true), "True value is not empty")
}
func TestNotEmptyWrapper(t *testing.T) {
assert := New(t)
mockAssert := New(new(testing.T))
assert.False(mockAssert.NotEmpty(""), "Empty string is empty")
assert.False(mockAssert.NotEmpty(nil), "Nil is empty")
assert.False(mockAssert.NotEmpty([]string{}), "Empty string array is empty")
assert.False(mockAssert.NotEmpty(0), "Zero int value is empty")
assert.False(mockAssert.NotEmpty(false), "False value is empty")
assert.True(mockAssert.NotEmpty("something"), "Non Empty string is not empty")
assert.True(mockAssert.NotEmpty(errors.New("something")), "Non nil object is not empty")
assert.True(mockAssert.NotEmpty([]string{"something"}), "Non empty string array is not empty")
assert.True(mockAssert.NotEmpty(1), "Non-zero int value is not empty")
assert.True(mockAssert.NotEmpty(true), "True value is not empty")
}
func TestLenWrapper(t *testing.T) {
assert := New(t)
mockAssert := New(new(testing.T))
assert.False(mockAssert.Len(nil, 0), "nil does not have length")
assert.False(mockAssert.Len(0, 0), "int does not have length")
assert.False(mockAssert.Len(true, 0), "true does not have length")
assert.False(mockAssert.Len(false, 0), "false does not have length")
assert.False(mockAssert.Len('A', 0), "Rune does not have length")
assert.False(mockAssert.Len(struct{}{}, 0), "Struct does not have length")
ch := make(chan int, 5)
ch <- 1
ch <- 2
ch <- 3
cases := []struct {
v interface{}
l int
}{
{[]int{1, 2, 3}, 3},
gitextract_qzbt7970/ ├── .gitignore ├── LICENSE ├── README.md ├── bench_test.go ├── cache.go ├── cache_test.go ├── cachecontrol.go ├── cachecontrol_test.go ├── cli/ │ └── httpcache.go ├── handler.go ├── header.go ├── httplog/ │ └── log.go ├── key.go ├── key_test.go ├── logger.go ├── resource.go ├── spec_test.go ├── util_test.go ├── validator.go ├── vendor/ │ ├── github.com/ │ │ ├── rainycape/ │ │ │ └── vfs/ │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── bench_test.go │ │ │ ├── chroot.go │ │ │ ├── doc.go │ │ │ ├── file.go │ │ │ ├── file_util.go │ │ │ ├── fs.go │ │ │ ├── map.go │ │ │ ├── mem.go │ │ │ ├── mounter.go │ │ │ ├── open.go │ │ │ ├── open_test.go │ │ │ ├── rewriter.go │ │ │ ├── ro.go │ │ │ ├── testdata/ │ │ │ │ ├── download-data.sh │ │ │ │ ├── fs/ │ │ │ │ │ ├── a/ │ │ │ │ │ │ └── b/ │ │ │ │ │ │ └── c/ │ │ │ │ │ │ └── d │ │ │ │ │ └── empty │ │ │ │ ├── fs.tar.bz2 │ │ │ │ └── update-fs.sh │ │ │ ├── util.go │ │ │ ├── vfs.go │ │ │ ├── vfs_test.go │ │ │ ├── write.go │ │ │ └── write_test.go │ │ └── stretchr/ │ │ └── testify/ │ │ ├── assert/ │ │ │ ├── assertions.go │ │ │ ├── assertions_test.go │ │ │ ├── doc.go │ │ │ ├── errors.go │ │ │ ├── forward_assertions.go │ │ │ ├── forward_assertions_test.go │ │ │ ├── http_assertions.go │ │ │ └── http_assertions_test.go │ │ └── require/ │ │ ├── doc.go │ │ ├── requirements.go │ │ └── requirements_test.go │ ├── gopkg.in/ │ │ └── djherbis/ │ │ └── stream.v1/ │ │ ├── LICENSE │ │ ├── README.md │ │ ├── fs.go │ │ ├── memfs.go │ │ ├── reader.go │ │ ├── stream.go │ │ ├── stream_test.go │ │ └── sync.go │ └── vendor.json └── wercker.yml
SYMBOL INDEX (615 symbols across 47 files)
FILE: bench_test.go
function BenchmarkCachingFiles (line 14) | func BenchmarkCachingFiles(b *testing.B) {
FILE: cache.go
constant headerPrefix (line 23) | headerPrefix = "header/"
constant bodyPrefix (line 24) | bodyPrefix = "body/"
constant formatPrefix (line 25) | formatPrefix = "v1/"
type Cache (line 31) | type Cache interface
type cache (line 40) | type cache struct
method vfsWrite (line 78) | func (c *cache) vfsWrite(path string, r io.Reader) error {
method Header (line 94) | func (c *cache) Header(key string) (Header, error) {
method Store (line 108) | func (c *cache) Store(res *Resource, keys ...string) error {
method storeBody (line 134) | func (c *cache) storeBody(r io.Reader, key string) error {
method storeHeader (line 141) | func (c *cache) storeHeader(code int, h http.Header, key string) error {
method Retrieve (line 153) | func (c *cache) Retrieve(key string) (*Resource, error) {
method Invalidate (line 178) | func (c *cache) Invalidate(keys ...string) {
method Freshen (line 185) | func (c *cache) Freshen(res *Resource, keys ...string) error {
type Header (line 47) | type Header struct
function NewVFSCache (line 53) | func NewVFSCache(fs vfs.VFS) Cache {
function NewMemoryCache (line 58) | func NewMemoryCache() Cache {
function NewDiskCache (line 63) | func NewDiskCache(dir string) (Cache, error) {
function hashKey (line 202) | func hashKey(key string) string {
function readHeaders (line 208) | func readHeaders(r *bufio.Reader) (Header, error) {
function headersToWriter (line 231) | func headersToWriter(h http.Header, w io.Writer) error {
FILE: cache_test.go
function TestSaveResource (line 12) | func TestSaveResource(t *testing.T) {
function TestSaveResourceWithIncorrectContentLength (line 34) | func TestSaveResourceWithIncorrectContentLength(t *testing.T) {
FILE: cachecontrol.go
constant CacheControlHeader (line 13) | CacheControlHeader = "Cache-Control"
type CacheControl (line 16) | type CacheControl
method Get (line 63) | func (cc CacheControl) Get(key string) (string, bool) {
method Add (line 71) | func (cc CacheControl) Add(key, val string) {
method Has (line 80) | func (cc CacheControl) Has(key string) bool {
method Duration (line 85) | func (cc CacheControl) Duration(key string) (time.Duration, error) {
method String (line 90) | func (cc CacheControl) String() string {
function ParseCacheControlHeaders (line 18) | func ParseCacheControlHeaders(h http.Header) (CacheControl, error) {
function ParseCacheControl (line 22) | func ParseCacheControl(input string) (CacheControl, error) {
FILE: cachecontrol_test.go
function TestParsingCacheControl (line 10) | func TestParsingCacheControl(t *testing.T) {
function BenchmarkCacheControlParsing (line 49) | func BenchmarkCacheControlParsing(b *testing.B) {
FILE: cli/httpcache.go
constant defaultListen (line 15) | defaultListen = "0.0.0.0:8080"
constant defaultDir (line 16) | defaultDir = "./cachedata"
function init (line 28) | func init() {
function main (line 42) | func main() {
FILE: handler.go
constant CacheHeader (line 20) | CacheHeader = "X-Cache"
constant ProxyDateHeader (line 21) | ProxyDateHeader = "Proxy-Date"
type Handler (line 47) | type Handler struct
method ServeHTTP (line 63) | func (h *Handler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
method freshness (line 131) | func (h *Handler) freshness(res *Resource, r *cacheRequest) (time.Dura...
method needsValidation (line 166) | func (h *Handler) needsValidation(res *Resource, r *cacheRequest) bool {
method pipeUpstream (line 206) | func (h *Handler) pipeUpstream(w http.ResponseWriter, r *cacheRequest) {
method passUpstream (line 239) | func (h *Handler) passUpstream(w http.ResponseWriter, r *cacheRequest) {
method isCacheable (line 316) | func (h *Handler) isCacheable(res *Resource, r *cacheRequest) bool {
method serveResource (line 361) | func (h *Handler) serveResource(res *Resource, w http.ResponseWriter, ...
method invalidateResource (line 401) | func (h *Handler) invalidateResource(res *Resource, r *cacheRequest) {
method storeResource (line 410) | func (h *Handler) storeResource(res *Resource, r *cacheRequest) {
method lookup (line 438) | func (h *Handler) lookup(req *cacheRequest) (*Resource, error) {
function NewHandler (line 54) | func NewHandler(cache Cache, upstream http.Handler) *Handler {
function correctedAge (line 290) | func correctedAge(h http.Header, reqTime, respTime time.Time) (time.Dura...
type cacheRequest (line 469) | type cacheRequest struct
method isStateChanging (line 494) | func (r *cacheRequest) isStateChanging() bool {
method isCacheable (line 502) | func (r *cacheRequest) isCacheable() bool {
function newCacheRequest (line 476) | func newCacheRequest(r *http.Request) (*cacheRequest, error) {
function newResponseStreamer (line 524) | func newResponseStreamer(w http.ResponseWriter) *responseStreamer {
type responseStreamer (line 536) | type responseStreamer struct
method WaitHeaders (line 545) | func (rw *responseStreamer) WaitHeaders() {
method WriteHeader (line 550) | func (rw *responseStreamer) WriteHeader(status int) {
method Write (line 556) | func (rw *responseStreamer) Write(b []byte) (int, error) {
method Close (line 560) | func (rw *responseStreamer) Close() error {
method Resource (line 565) | func (rw *responseStreamer) Resource() *Resource {
type errReadSeekCloser (line 581) | type errReadSeekCloser struct
method Error (line 585) | func (e errReadSeekCloser) Error() string {
method Close (line 588) | func (e errReadSeekCloser) Close() error { retur...
method Read (line 589) | func (e errReadSeekCloser) Read(_ []byte) (int, error) { retur...
method Seek (line 590) | func (e errReadSeekCloser) Seek(_ int64, _ int) (int64, error) { retur...
FILE: header.go
function timeHeader (line 12) | func timeHeader(key string, h http.Header) (time.Time, error) {
function intHeader (line 20) | func intHeader(key string, h http.Header) (int, error) {
FILE: httplog/log.go
constant CacheHeader (line 16) | CacheHeader = "X-Cache"
type responseWriter (line 19) | type responseWriter struct
method Header (line 27) | func (l *responseWriter) Header() http.Header {
method Write (line 31) | func (l *responseWriter) Write(b []byte) (int, error) {
method WriteHeader (line 43) | func (l *responseWriter) WriteHeader(s int) {
method Status (line 48) | func (l *responseWriter) Status() int {
method Size (line 52) | func (l *responseWriter) Size() int {
function NewResponseLogger (line 56) | func NewResponseLogger(delegate http.Handler) *ResponseLogger {
type ResponseLogger (line 60) | type ResponseLogger struct
method ServeHTTP (line 65) | func (l *ResponseLogger) ServeHTTP(w http.ResponseWriter, req *http.Re...
method writeLog (line 90) | func (l *ResponseLogger) writeLog(req *http.Request, respWr *responseW...
function isError (line 119) | func isError(code int) bool {
function writePrefixString (line 123) | func writePrefixString(s, prefix string, w io.Writer) {
FILE: key.go
type Key (line 12) | type Key struct
method ForMethod (line 49) | func (k Key) ForMethod(method string) Key {
method Vary (line 56) | func (k Key) Vary(varyHeader string, r *http.Request) Key {
method String (line 66) | func (k Key) String() string {
function NewKey (line 20) | func NewKey(method string, u *url.URL, h http.Header) Key {
function NewRequestKey (line 25) | func NewRequestKey(r *http.Request) Key {
function canonicalURL (line 81) | func canonicalURL(u *url.URL) *url.URL {
FILE: key_test.go
function mustParseUrl (line 11) | func mustParseUrl(u string) *url.URL {
function TestKeysDiffer (line 19) | func TestKeysDiffer(t *testing.T) {
function TestRequestKey (line 26) | func TestRequestKey(t *testing.T) {
function TestVaryKey (line 35) | func TestVaryKey(t *testing.T) {
function TestRequestKeyWithContentLocation (line 44) | func TestRequestKeyWithContentLocation(t *testing.T) {
function TestRequestKeyWithIllegalContentLocation (line 53) | func TestRequestKeyWithIllegalContentLocation(t *testing.T) {
FILE: logger.go
constant ansiRed (line 6) | ansiRed = "\x1b[31;1m"
constant ansiReset (line 7) | ansiReset = "\x1b[0m"
function debugf (line 12) | func debugf(format string, args ...interface{}) {
function errorf (line 18) | func errorf(format string, args ...interface{}) {
FILE: resource.go
constant lastModDivisor (line 14) | lastModDivisor = 10
constant viaPseudonym (line 15) | viaPseudonym = "httpcache"
type ReadSeekCloser (line 22) | type ReadSeekCloser interface
type byteReadSeekCloser (line 28) | type byteReadSeekCloser struct
method Close (line 32) | func (brsc *byteReadSeekCloser) Close() error { return nil }
type Resource (line 34) | type Resource struct
method IsNonErrorStatus (line 59) | func (r *Resource) IsNonErrorStatus() bool {
method Status (line 63) | func (r *Resource) Status() int {
method Header (line 67) | func (r *Resource) Header() http.Header {
method IsStale (line 71) | func (r *Resource) IsStale() bool {
method MarkStale (line 75) | func (r *Resource) MarkStale() {
method cacheControl (line 79) | func (r *Resource) cacheControl() (CacheControl, error) {
method LastModified (line 93) | func (r *Resource) LastModified() time.Time {
method Expires (line 105) | func (r *Resource) Expires() (time.Time, error) {
method MustValidate (line 113) | func (r *Resource) MustValidate(shared bool) bool {
method DateAfter (line 132) | func (r *Resource) DateAfter(d time.Time) bool {
method Age (line 144) | func (r *Resource) Age() (time.Duration, error) {
method MaxAge (line 162) | func (r *Resource) MaxAge(shared bool) (time.Duration, error) {
method RemovePrivateHeaders (line 195) | func (r *Resource) RemovePrivateHeaders() {
method HasValidators (line 207) | func (r *Resource) HasValidators() bool {
method HasExplicitExpiration (line 215) | func (r *Resource) HasExplicitExpiration() bool {
method HeuristicFreshness (line 237) | func (r *Resource) HeuristicFreshness() time.Duration {
method Via (line 245) | func (r *Resource) Via() string {
function NewResource (line 43) | func NewResource(statusCode int, body ReadSeekCloser, hdrs http.Header) ...
function NewResourceBytes (line 51) | func NewResourceBytes(statusCode int, b []byte, hdrs http.Header) *Resou...
FILE: spec_test.go
function testSetup (line 17) | func testSetup() (*client, *upstreamServer) {
function TestSpecResponseCacheControl (line 49) | func TestSpecResponseCacheControl(t *testing.T) {
function TestSpecResponseCacheControlWithPrivateHeaders (line 95) | func TestSpecResponseCacheControlWithPrivateHeaders(t *testing.T) {
function TestSpecResponseCacheControlWithAuthorizationHeaders (line 121) | func TestSpecResponseCacheControlWithAuthorizationHeaders(t *testing.T) {
function TestSpecRequestCacheControl (line 144) | func TestSpecRequestCacheControl(t *testing.T) {
function TestSpecRequestCacheControlWithOnlyIfCached (line 178) | func TestSpecRequestCacheControlWithOnlyIfCached(t *testing.T) {
function TestSpecCachingStatusCodes (line 192) | func TestSpecCachingStatusCodes(t *testing.T) {
function TestSpecConditionalCaching (line 215) | func TestSpecConditionalCaching(t *testing.T) {
function TestSpecRangeRequests (line 229) | func TestSpecRangeRequests(t *testing.T) {
function TestSpecHeuristicCaching (line 238) | func TestSpecHeuristicCaching(t *testing.T) {
function TestSpecCacheControlTrumpsExpires (line 250) | func TestSpecCacheControlTrumpsExpires(t *testing.T) {
function TestSpecNotCachedWithoutValidatorOrExpiration (line 263) | func TestSpecNotCachedWithoutValidatorOrExpiration(t *testing.T) {
function TestSpecNoCachingForInvalidExpires (line 273) | func TestSpecNoCachingForInvalidExpires(t *testing.T) {
function TestSpecRequestsWithoutHostHeader (line 281) | func TestSpecRequestsWithoutHostHeader(t *testing.T) {
function TestSpecCacheControlMaxStale (line 293) | func TestSpecCacheControlMaxStale(t *testing.T) {
function TestSpecValidatingStaleResponsesUnchanged (line 310) | func TestSpecValidatingStaleResponsesUnchanged(t *testing.T) {
function TestSpecValidatingStaleResponsesWithNewContent (line 325) | func TestSpecValidatingStaleResponsesWithNewContent(t *testing.T) {
function TestSpecValidatingStaleResponsesWithNewEtag (line 340) | func TestSpecValidatingStaleResponsesWithNewEtag(t *testing.T) {
function TestSpecVaryHeader (line 355) | func TestSpecVaryHeader(t *testing.T) {
function TestSpecHeadersPropagated (line 367) | func TestSpecHeadersPropagated(t *testing.T) {
function TestSpecAgeHeaderFromUpstream (line 381) | func TestSpecAgeHeaderFromUpstream(t *testing.T) {
function TestSpecAgeHeaderWithResponseDelay (line 391) | func TestSpecAgeHeaderWithResponseDelay(t *testing.T) {
function TestSpecAgeHeaderGeneratedWhereNoneExists (line 403) | func TestSpecAgeHeaderGeneratedWhereNoneExists(t *testing.T) {
function TestSpecWarningForOldContent (line 414) | func TestSpecWarningForOldContent(t *testing.T) {
function TestSpecHeadCanBeServedFromCacheOnlyWithExplicitFreshness (line 425) | func TestSpecHeadCanBeServedFromCacheOnlyWithExplicitFreshness(t *testin...
function TestSpecInvalidatingGetWithHeadRequest (line 438) | func TestSpecInvalidatingGetWithHeadRequest(t *testing.T) {
function TestSpecFresheningGetWithHeadRequest (line 448) | func TestSpecFresheningGetWithHeadRequest(t *testing.T) {
function TestSpecContentHeaderInRequestRespected (line 465) | func TestSpecContentHeaderInRequestRespected(t *testing.T) {
function TestSpecMultipleCacheControlHeaders (line 478) | func TestSpecMultipleCacheControlHeaders(t *testing.T) {
FILE: util_test.go
function newRequest (line 17) | func newRequest(method, url string, h ...string) *http.Request {
function newResponse (line 27) | func newResponse(status int, body []byte, h ...string) *http.Response {
function parseHeaders (line 41) | func parseHeaders(input []string) http.Header {
type client (line 51) | type client struct
method do (line 56) | func (c *client) do(r *http.Request) *clientResponse {
method get (line 84) | func (c *client) get(path string, headers ...string) *clientResponse {
method head (line 88) | func (c *client) head(path string, headers ...string) *clientResponse {
method put (line 92) | func (c *client) put(path string, headers ...string) *clientResponse {
method post (line 96) | func (c *client) post(path string, headers ...string) *clientResponse {
type clientResponse (line 100) | type clientResponse struct
type upstreamServer (line 109) | type upstreamServer struct
method timeTravel (line 123) | func (u *upstreamServer) timeTravel(d time.Duration) {
method assert (line 127) | func (u *upstreamServer) assert(f func(r *http.Request)) {
method ServeHTTP (line 131) | func (u *upstreamServer) ServeHTTP(rw http.ResponseWriter, req *http.R...
method RoundTrip (line 172) | func (u *upstreamServer) RoundTrip(req *http.Request) (*http.Response,...
function cc (line 182) | func cc(cc string) string {
function readAll (line 186) | func readAll(r io.Reader) []byte {
function readAllString (line 194) | func readAllString(r io.Reader) string {
FILE: validator.go
type Validator (line 9) | type Validator struct
method Validate (line 13) | func (v *Validator) Validate(req *http.Request, res *Resource) bool {
function headersEqual (line 43) | func headersEqual(h1, h2 http.Header) bool {
function cloneRequest (line 58) | func cloneRequest(r *http.Request) *http.Request {
FILE: vendor/github.com/rainycape/vfs/bench_test.go
function BenchmarkLoadGoSrc (line 11) | func BenchmarkLoadGoSrc(b *testing.B) {
function BenchmarkWalkGoSrc (line 32) | func BenchmarkWalkGoSrc(b *testing.B) {
FILE: vendor/github.com/rainycape/vfs/chroot.go
type chrootFileSystem (line 9) | type chrootFileSystem struct
method path (line 14) | func (fs *chrootFileSystem) path(p string) string {
method VFS (line 21) | func (fs *chrootFileSystem) VFS() VFS {
method Open (line 25) | func (fs *chrootFileSystem) Open(path string) (RFile, error) {
method OpenFile (line 29) | func (fs *chrootFileSystem) OpenFile(path string, flag int, perm os.Fi...
method Lstat (line 33) | func (fs *chrootFileSystem) Lstat(path string) (os.FileInfo, error) {
method Stat (line 37) | func (fs *chrootFileSystem) Stat(path string) (os.FileInfo, error) {
method ReadDir (line 41) | func (fs *chrootFileSystem) ReadDir(path string) ([]os.FileInfo, error) {
method Mkdir (line 45) | func (fs *chrootFileSystem) Mkdir(path string, perm os.FileMode) error {
method Remove (line 49) | func (fs *chrootFileSystem) Remove(path string) error {
method String (line 53) | func (fs *chrootFileSystem) String() string {
function Chroot (line 60) | func Chroot(root string, fs VFS) (VFS, error) {
FILE: vendor/github.com/rainycape/vfs/file.go
type EntryType (line 11) | type EntryType
constant EntryTypeFile (line 15) | EntryTypeFile EntryType = iota + 1
constant EntryTypeDir (line 17) | EntryTypeDir
constant ModeCompress (line 21) | ModeCompress os.FileMode = 1 << 16
type Entry (line 26) | type Entry interface
type File (line 41) | type File struct
method Type (line 52) | func (f *File) Type() EntryType {
method Size (line 56) | func (f *File) Size() int64 {
method FileMode (line 62) | func (f *File) FileMode() os.FileMode {
method ModificationTime (line 66) | func (f *File) ModificationTime() time.Time {
type Dir (line 75) | type Dir struct
method Type (line 88) | func (d *Dir) Type() EntryType {
method Size (line 92) | func (d *Dir) Size() int64 {
method FileMode (line 96) | func (d *Dir) FileMode() os.FileMode {
method ModificationTime (line 100) | func (d *Dir) ModificationTime() time.Time {
method Add (line 108) | func (d *Dir) Add(name string, entry Entry) error {
method Find (line 139) | func (d *Dir) Find(name string) (Entry, int, error) {
type EntryInfo (line 150) | type EntryInfo struct
method Name (line 158) | func (info *EntryInfo) Name() string {
method Size (line 162) | func (info *EntryInfo) Size() int64 {
method Mode (line 166) | func (info *EntryInfo) Mode() os.FileMode {
method ModTime (line 170) | func (info *EntryInfo) ModTime() time.Time {
method IsDir (line 174) | func (info *EntryInfo) IsDir() bool {
method Sys (line 179) | func (info *EntryInfo) Sys() interface{} {
type FileInfos (line 188) | type FileInfos
method Len (line 190) | func (f FileInfos) Len() int {
method Less (line 194) | func (f FileInfos) Less(i, j int) bool {
method Swap (line 198) | func (f FileInfos) Swap(i, j int) {
FILE: vendor/github.com/rainycape/vfs/file_util.go
function NewRFile (line 19) | func NewRFile(f *File) (RFile, error) {
function NewWFile (line 28) | func NewWFile(f *File, read bool, write bool) (WFile, error) {
function closeFile (line 38) | func closeFile(f *file) {
function fileData (line 42) | func fileData(f *File) ([]byte, error) {
type file (line 58) | type file struct
method Read (line 67) | func (f *file) Read(p []byte) (int, error) {
method Seek (line 87) | func (f *file) Seek(offset int64, whence int) (int64, error) {
method Write (line 111) | func (f *file) Write(p []byte) (int, error) {
method Close (line 130) | func (f *file) Close() error {
method IsCompressed (line 159) | func (f *file) IsCompressed() bool {
method SetCompressed (line 163) | func (f *file) SetCompressed(c bool) {
FILE: vendor/github.com/rainycape/vfs/fs.go
type fileSystem (line 17) | type fileSystem struct
method path (line 22) | func (fs *fileSystem) path(name string) string {
method Root (line 29) | func (fs *fileSystem) Root() string {
method IsTemporary (line 34) | func (fs *fileSystem) IsTemporary() bool {
method Open (line 38) | func (fs *fileSystem) Open(path string) (RFile, error) {
method OpenFile (line 46) | func (fs *fileSystem) OpenFile(path string, flag int, mode os.FileMode...
method Lstat (line 54) | func (fs *fileSystem) Lstat(path string) (os.FileInfo, error) {
method Stat (line 62) | func (fs *fileSystem) Stat(path string) (os.FileInfo, error) {
method ReadDir (line 70) | func (fs *fileSystem) ReadDir(path string) ([]os.FileInfo, error) {
method Mkdir (line 78) | func (fs *fileSystem) Mkdir(path string, perm os.FileMode) error {
method Remove (line 82) | func (fs *fileSystem) Remove(path string) error {
method String (line 86) | func (fs *fileSystem) String() string {
method Close (line 92) | func (f *fileSystem) Close() error {
function newFS (line 99) | func newFS(root string) (*fileSystem, error) {
function FS (line 112) | func FS(root string) (VFS, error) {
function TmpFS (line 121) | func TmpFS(prefix string) (TemporaryVFS, error) {
FILE: vendor/github.com/rainycape/vfs/map.go
function Map (line 13) | func Map(files map[string]*File) (VFS, error) {
FILE: vendor/github.com/rainycape/vfs/mem.go
type memoryFileSystem (line 18) | type memoryFileSystem struct
method entry (line 24) | func (fs *memoryFileSystem) entry(path string) (Entry, *Dir, int, erro...
method dirEntry (line 59) | func (fs *memoryFileSystem) dirEntry(path string) (*Dir, error) {
method Open (line 70) | func (fs *memoryFileSystem) Open(path string) (RFile, error) {
method OpenFile (line 81) | func (fs *memoryFileSystem) OpenFile(path string, flag int, mode os.Fi...
method Lstat (line 133) | func (fs *memoryFileSystem) Lstat(path string) (os.FileInfo, error) {
method Stat (line 137) | func (fs *memoryFileSystem) Stat(path string) (os.FileInfo, error) {
method ReadDir (line 145) | func (fs *memoryFileSystem) ReadDir(path string) ([]os.FileInfo, error) {
method readDir (line 151) | func (fs *memoryFileSystem) readDir(path string) ([]os.FileInfo, error) {
method Mkdir (line 172) | func (fs *memoryFileSystem) Mkdir(path string, perm os.FileMode) error {
method Remove (line 199) | func (fs *memoryFileSystem) Remove(path string) error {
method String (line 218) | func (fs *memoryFileSystem) String() string {
function newMemory (line 222) | func newMemory() *memoryFileSystem {
function Memory (line 233) | func Memory() VFS {
function cleanPath (line 237) | func cleanPath(path string) string {
FILE: vendor/github.com/rainycape/vfs/mounter.go
constant separator (line 11) | separator = "/"
function hasSubdir (line 14) | func hasSubdir(root, dir string) (string, bool) {
type mountPoint (line 26) | type mountPoint struct
method String (line 31) | func (m *mountPoint) String() string {
type Mounter (line 38) | type Mounter struct
method fs (line 42) | func (m *Mounter) fs(p string) (VFS, string, error) {
method Mount (line 53) | func (m *Mounter) Mount(fs VFS, point string) error {
method Umount (line 78) | func (m *Mounter) Umount(point string) error {
method Open (line 95) | func (m *Mounter) Open(path string) (RFile, error) {
method OpenFile (line 103) | func (m *Mounter) OpenFile(path string, flag int, perm os.FileMode) (W...
method Lstat (line 111) | func (m *Mounter) Lstat(path string) (os.FileInfo, error) {
method Stat (line 119) | func (m *Mounter) Stat(path string) (os.FileInfo, error) {
method ReadDir (line 127) | func (m *Mounter) ReadDir(path string) ([]os.FileInfo, error) {
method Mkdir (line 135) | func (m *Mounter) Mkdir(path string, perm os.FileMode) error {
method Remove (line 143) | func (m *Mounter) Remove(path string) error {
method String (line 153) | func (m *Mounter) String() string {
function mounterCompileTimeCheck (line 161) | func mounterCompileTimeCheck() VFS {
FILE: vendor/github.com/rainycape/vfs/open.go
function Zip (line 23) | func Zip(r io.Reader, size int64) (VFS, error) {
function Tar (line 62) | func Tar(r io.Reader) (VFS, error) {
function TarGzip (line 91) | func TarGzip(r io.Reader) (VFS, error) {
function TarBzip2 (line 102) | func TarBzip2(r io.Reader) (VFS, error) {
function Open (line 115) | func Open(filename string) (VFS, error) {
FILE: vendor/github.com/rainycape/vfs/open_test.go
function testOpenedVFS (line 8) | func testOpenedVFS(t *testing.T, fs VFS) {
function testOpenFilename (line 25) | func testOpenFilename(t *testing.T, filename string) {
function TestOpenZip (line 34) | func TestOpenZip(t *testing.T) {
function TestOpenTar (line 38) | func TestOpenTar(t *testing.T) {
function TestOpenTarGzip (line 42) | func TestOpenTarGzip(t *testing.T) {
function TestOpenTarBzip2 (line 46) | func TestOpenTarBzip2(t *testing.T) {
FILE: vendor/github.com/rainycape/vfs/rewriter.go
type rewriterFileSystem (line 8) | type rewriterFileSystem struct
method VFS (line 13) | func (fs *rewriterFileSystem) VFS() VFS {
method Open (line 17) | func (fs *rewriterFileSystem) Open(path string) (RFile, error) {
method OpenFile (line 21) | func (fs *rewriterFileSystem) OpenFile(path string, flag int, perm os....
method Lstat (line 25) | func (fs *rewriterFileSystem) Lstat(path string) (os.FileInfo, error) {
method Stat (line 29) | func (fs *rewriterFileSystem) Stat(path string) (os.FileInfo, error) {
method ReadDir (line 33) | func (fs *rewriterFileSystem) ReadDir(path string) ([]os.FileInfo, err...
method Mkdir (line 37) | func (fs *rewriterFileSystem) Mkdir(path string, perm os.FileMode) err...
method Remove (line 41) | func (fs *rewriterFileSystem) Remove(path string) error {
method String (line 45) | func (fs *rewriterFileSystem) String() string {
function Rewriter (line 51) | func Rewriter(fs VFS, rewriter func(oldPath string) (newPath string)) VFS {
FILE: vendor/github.com/rainycape/vfs/ro.go
type readOnlyFileSystem (line 15) | type readOnlyFileSystem struct
method VFS (line 19) | func (fs *readOnlyFileSystem) VFS() VFS {
method Open (line 23) | func (fs *readOnlyFileSystem) Open(path string) (RFile, error) {
method OpenFile (line 27) | func (fs *readOnlyFileSystem) OpenFile(path string, flag int, perm os....
method Lstat (line 34) | func (fs *readOnlyFileSystem) Lstat(path string) (os.FileInfo, error) {
method Stat (line 38) | func (fs *readOnlyFileSystem) Stat(path string) (os.FileInfo, error) {
method ReadDir (line 42) | func (fs *readOnlyFileSystem) ReadDir(path string) ([]os.FileInfo, err...
method Mkdir (line 46) | func (fs *readOnlyFileSystem) Mkdir(path string, perm os.FileMode) err...
method Remove (line 50) | func (fs *readOnlyFileSystem) Remove(path string) error {
method String (line 54) | func (fs *readOnlyFileSystem) String() string {
function ReadOnly (line 59) | func ReadOnly(fs VFS) VFS {
FILE: vendor/github.com/rainycape/vfs/util.go
type WalkFunc (line 23) | type WalkFunc
function walk (line 25) | func walk(fs VFS, p string, info os.FileInfo, fn WalkFunc) error {
function Walk (line 60) | func Walk(fs VFS, root string, fn WalkFunc) error {
function makeDir (line 68) | func makeDir(fs VFS, path string, perm os.FileMode) error {
function MkdirAll (line 85) | func MkdirAll(fs VFS, path string, perm os.FileMode) error {
function RemoveAll (line 103) | func RemoveAll(fs VFS, path string) error {
function ReadFile (line 128) | func ReadFile(fs VFS, path string) ([]byte, error) {
function WriteFile (line 140) | func WriteFile(fs VFS, path string, data []byte, perm os.FileMode) error {
function Clone (line 155) | func Clone(dst VFS, src VFS) error {
function IsExist (line 189) | func IsExist(err error) bool {
function IsNotExist (line 195) | func IsNotExist(err error) bool {
type Compressor (line 202) | type Compressor interface
function Compress (line 209) | func Compress(fs VFS) error {
FILE: vendor/github.com/rainycape/vfs/vfs.go
type Opener (line 11) | type Opener interface
type RFile (line 24) | type RFile interface
type WFile (line 35) | type WFile interface
type VFS (line 43) | type VFS interface
type TemporaryVFS (line 72) | type TemporaryVFS interface
type Container (line 82) | type Container interface
FILE: vendor/github.com/rainycape/vfs/vfs_test.go
constant goTestFile (line 15) | goTestFile = "go1.3.src.tar.gz"
type errNoTestFile (line 18) | type errNoTestFile
method Error (line 20) | func (e errNoTestFile) Error() string {
function openOptionalTestFile (line 24) | func openOptionalTestFile(t testing.TB, name string) *os.File {
function testVFS (line 33) | func testVFS(t *testing.T, fs VFS) {
function TestMapFS (line 134) | func TestMapFS(t *testing.T) {
function TestPopulatedMap (line 142) | func TestPopulatedMap(t *testing.T) {
function TestBadPopulatedMap (line 163) | func TestBadPopulatedMap(t *testing.T) {
function TestTmpFS (line 175) | func TestTmpFS(t *testing.T) {
constant go13FileCount (line 185) | go13FileCount = 4157
constant go13DirCount (line 187) | go13DirCount = 407 + 1
function countFileSystem (line 190) | func countFileSystem(fs VFS) (int, int, error) {
function testGoFileCount (line 206) | func testGoFileCount(t *testing.T, fs VFS) {
function TestGo13Files (line 219) | func TestGo13Files(t *testing.T) {
function TestMounter (line 229) | func TestMounter(t *testing.T) {
function TestClone (line 241) | func TestClone(t *testing.T) {
function measureVFSMemorySize (line 274) | func measureVFSMemorySize(t testing.TB, fs VFS) int {
function hashVFS (line 293) | func hashVFS(t testing.TB, fs VFS) string {
function TestCompress (line 315) | func TestCompress(t *testing.T) {
FILE: vendor/github.com/rainycape/vfs/write.go
function copyVFS (line 11) | func copyVFS(fs VFS, copier func(p string, info os.FileInfo, f io.Reader...
function WriteZip (line 29) | func WriteZip(w io.Writer, fs VFS) error {
function WriteTar (line 51) | func WriteTar(w io.Writer, fs VFS) error {
function WriteTarGzip (line 72) | func WriteTarGzip(w io.Writer, fs VFS) error {
FILE: vendor/github.com/rainycape/vfs/write_test.go
type writeTester (line 10) | type writeTester struct
function TestWrite (line 16) | func TestWrite(t *testing.T) {
FILE: vendor/github.com/stretchr/testify/assert/assertions.go
type TestingT (line 15) | type TestingT interface
type Comparison (line 20) | type Comparison
function ObjectsAreEqual (line 29) | func ObjectsAreEqual(expected, actual interface{}) bool {
function CallerInfo (line 65) | func CallerInfo() string {
function getWhitespaceString (line 89) | func getWhitespaceString() string {
function messageFromMsgAndArgs (line 102) | func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
function indentMessageLines (line 117) | func indentMessageLines(message string, tabs int) string {
function Fail (line 139) | func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) ...
function Implements (line 165) | func Implements(t TestingT, interfaceObject interface{}, object interfac...
function IsType (line 178) | func IsType(t TestingT, expectedType interface{}, object interface{}, ms...
function Equal (line 192) | func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...inter...
function Exactly (line 208) | func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...int...
function NotNil (line 226) | func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) b...
function isNil (line 248) | func isNil(object interface{}) bool {
function Nil (line 267) | func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
function isEmpty (line 290) | func isEmpty(object interface{}) bool {
function Empty (line 334) | func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bo...
function NotEmpty (line 353) | func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{})...
function getLen (line 366) | func getLen(x interface{}) (ok bool, length int) {
function Len (line 382) | func Len(t TestingT, object interface{}, length int, msgAndArgs ...inter...
function True (line 399) | func True(t TestingT, value bool, msgAndArgs ...interface{}) bool {
function False (line 414) | func False(t TestingT, value bool, msgAndArgs ...interface{}) bool {
function NotEqual (line 429) | func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...in...
function includeElement (line 443) | func includeElement(list interface{}, element interface{}) (ok, found bo...
function Contains (line 474) | func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interfa...
function NotContains (line 495) | func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...inte...
function Condition (line 510) | func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) b...
type PanicTestFunc (line 520) | type PanicTestFunc
function didPanic (line 523) | func didPanic(f PanicTestFunc) (bool, interface{}) {
function Panics (line 551) | func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
function NotPanics (line 567) | func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) b...
function WithinDuration (line 581) | func WithinDuration(t TestingT, expected, actual time.Time, delta time.D...
function toFloat (line 591) | func toFloat(x interface{}) (float64, bool) {
function InDelta (line 630) | func InDelta(t TestingT, expected, actual interface{}, delta float64, ms...
function calcEpsilonDelta (line 648) | func calcEpsilonDelta(expected, actual interface{}, epsilon float64) flo...
function InEpsilon (line 675) | func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64...
function NoError (line 693) | func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
function Error (line 709) | func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
function EqualError (line 725) | func EqualError(t TestingT, theError error, errString string, msgAndArgs...
function matchRegexp (line 737) | func matchRegexp(rx interface{}, str interface{}) bool {
function Regexp (line 756) | func Regexp(t TestingT, rx interface{}, str interface{}) bool {
function NotRegexp (line 773) | func NotRegexp(t TestingT, rx interface{}, str interface{}) bool {
FILE: vendor/github.com/stretchr/testify/assert/assertions_test.go
type AssertionTesterInterface (line 11) | type AssertionTesterInterface interface
type AssertionTesterConformingObject (line 16) | type AssertionTesterConformingObject struct
method TestMethod (line 19) | func (a *AssertionTesterConformingObject) TestMethod() {
type AssertionTesterNonConformingObject (line 23) | type AssertionTesterNonConformingObject struct
function TestObjectsAreEqual (line 26) | func TestObjectsAreEqual(t *testing.T) {
function TestImplements (line 46) | func TestImplements(t *testing.T) {
function TestIsType (line 59) | func TestIsType(t *testing.T) {
function TestEqual (line 72) | func TestEqual(t *testing.T) {
function TestNotNil (line 100) | func TestNotNil(t *testing.T) {
function TestNil (line 113) | func TestNil(t *testing.T) {
function TestTrue (line 126) | func TestTrue(t *testing.T) {
function TestFalse (line 139) | func TestFalse(t *testing.T) {
function TestExactly (line 152) | func TestExactly(t *testing.T) {
function TestNotEqual (line 180) | func TestNotEqual(t *testing.T) {
function TestContains (line 217) | func TestContains(t *testing.T) {
function TestNotContains (line 238) | func TestNotContains(t *testing.T) {
function Test_includeElement (line 259) | func Test_includeElement(t *testing.T) {
function TestCondition (line 302) | func TestCondition(t *testing.T) {
function TestDidPanic (line 315) | func TestDidPanic(t *testing.T) {
function TestPanics (line 330) | func TestPanics(t *testing.T) {
function TestNotPanics (line 347) | func TestNotPanics(t *testing.T) {
function TestEqual_Funcs (line 364) | func TestEqual_Funcs(t *testing.T) {
function TestNoError (line 377) | func TestNoError(t *testing.T) {
function TestError (line 393) | func TestError(t *testing.T) {
function TestEqualError (line 409) | func TestEqualError(t *testing.T) {
function Test_isEmpty (line 425) | func Test_isEmpty(t *testing.T) {
function TestEmpty (line 450) | func TestEmpty(t *testing.T) {
function TestNotEmpty (line 471) | func TestNotEmpty(t *testing.T) {
function Test_getLen (line 492) | func Test_getLen(t *testing.T) {
function TestLen (line 537) | func TestLen(t *testing.T) {
function TestWithinDuration (line 599) | func TestWithinDuration(t *testing.T) {
function TestInDelta (line 618) | func TestInDelta(t *testing.T) {
function TestInEpsilon (line 652) | func TestInEpsilon(t *testing.T) {
function TestRegexp (line 691) | func TestRegexp(t *testing.T) {
FILE: vendor/github.com/stretchr/testify/assert/forward_assertions.go
type Assertions (line 5) | type Assertions struct
method Fail (line 16) | func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interfa...
method Implements (line 23) | func (a *Assertions) Implements(interfaceObject interface{}, object in...
method IsType (line 28) | func (a *Assertions) IsType(expectedType interface{}, object interface...
method Equal (line 37) | func (a *Assertions) Equal(expected, actual interface{}, msgAndArgs .....
method Exactly (line 46) | func (a *Assertions) Exactly(expected, actual interface{}, msgAndArgs ...
method NotNil (line 55) | func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interfac...
method Nil (line 64) | func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}...
method Empty (line 74) | func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface...
method NotEmpty (line 86) | func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interf...
method Len (line 96) | func (a *Assertions) Len(object interface{}, length int, msgAndArgs .....
method True (line 105) | func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool {
method False (line 114) | func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool {
method NotEqual (line 123) | func (a *Assertions) NotEqual(expected, actual interface{}, msgAndArgs...
method Contains (line 132) | func (a *Assertions) Contains(s, contains interface{}, msgAndArgs ...i...
method NotContains (line 141) | func (a *Assertions) NotContains(s, contains interface{}, msgAndArgs ....
method Condition (line 146) | func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interfac...
method Panics (line 157) | func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}...
method NotPanics (line 168) | func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interfac...
method WithinDuration (line 177) | func (a *Assertions) WithinDuration(expected, actual time.Time, delta ...
method InDelta (line 186) | func (a *Assertions) InDelta(expected, actual interface{}, delta float...
method InEpsilon (line 193) | func (a *Assertions) InEpsilon(expected, actual interface{}, epsilon f...
method NoError (line 205) | func (a *Assertions) NoError(theError error, msgAndArgs ...interface{}...
method Error (line 217) | func (a *Assertions) Error(theError error, msgAndArgs ...interface{}) ...
method EqualError (line 230) | func (a *Assertions) EqualError(theError error, errString string, msgA...
method Regexp (line 240) | func (a *Assertions) Regexp(rx interface{}, str interface{}) bool {
method NotRegexp (line 250) | func (a *Assertions) NotRegexp(rx interface{}, str interface{}) bool {
function New (line 9) | func New(t TestingT) *Assertions {
FILE: vendor/github.com/stretchr/testify/assert/forward_assertions_test.go
function TestImplementsWrapper (line 10) | func TestImplementsWrapper(t *testing.T) {
function TestIsTypeWrapper (line 21) | func TestIsTypeWrapper(t *testing.T) {
function TestEqualWrapper (line 33) | func TestEqualWrapper(t *testing.T) {
function TestNotNilWrapper (line 53) | func TestNotNilWrapper(t *testing.T) {
function TestNilWrapper (line 65) | func TestNilWrapper(t *testing.T) {
function TestTrueWrapper (line 77) | func TestTrueWrapper(t *testing.T) {
function TestFalseWrapper (line 89) | func TestFalseWrapper(t *testing.T) {
function TestExactlyWrapper (line 101) | func TestExactlyWrapper(t *testing.T) {
function TestNotEqualWrapper (line 128) | func TestNotEqualWrapper(t *testing.T) {
function TestContainsWrapper (line 149) | func TestContainsWrapper(t *testing.T) {
function TestNotContainsWrapper (line 170) | func TestNotContainsWrapper(t *testing.T) {
function TestConditionWrapper (line 191) | func TestConditionWrapper(t *testing.T) {
function TestDidPanicWrapper (line 205) | func TestDidPanicWrapper(t *testing.T) {
function TestPanicsWrapper (line 220) | func TestPanicsWrapper(t *testing.T) {
function TestNotPanicsWrapper (line 237) | func TestNotPanicsWrapper(t *testing.T) {
function TestEqualWrapper_Funcs (line 254) | func TestEqualWrapper_Funcs(t *testing.T) {
function TestNoErrorWrapper (line 269) | func TestNoErrorWrapper(t *testing.T) {
function TestErrorWrapper (line 285) | func TestErrorWrapper(t *testing.T) {
function TestEqualErrorWrapper (line 301) | func TestEqualErrorWrapper(t *testing.T) {
function TestEmptyWrapper (line 318) | func TestEmptyWrapper(t *testing.T) {
function TestNotEmptyWrapper (line 336) | func TestNotEmptyWrapper(t *testing.T) {
function TestLenWrapper (line 354) | func TestLenWrapper(t *testing.T) {
function TestWithinDurationWrapper (line 394) | func TestWithinDurationWrapper(t *testing.T) {
function TestInDeltaWrapper (line 413) | func TestInDeltaWrapper(t *testing.T) {
function TestInEpsilonWrapper (line 447) | func TestInEpsilonWrapper(t *testing.T) {
function TestRegexpWrapper (line 485) | func TestRegexpWrapper(t *testing.T) {
FILE: vendor/github.com/stretchr/testify/assert/http_assertions.go
function httpCode (line 13) | func httpCode(handler http.HandlerFunc, mode, url string, values url.Val...
function HTTPSuccess (line 28) | func HTTPSuccess(t TestingT, handler http.HandlerFunc, mode, url string,...
function HTTPRedirect (line 41) | func HTTPRedirect(t TestingT, handler http.HandlerFunc, mode, url string...
function HTTPError (line 54) | func HTTPError(t TestingT, handler http.HandlerFunc, mode, url string, v...
function HttpBody (line 64) | func HttpBody(handler http.HandlerFunc, mode, url string, values url.Val...
function HTTPBodyContains (line 80) | func HTTPBodyContains(t TestingT, handler http.HandlerFunc, mode, url st...
function HTTPBodyNotContains (line 97) | func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, mode, url...
method HTTPSuccess (line 117) | func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, mode, url str...
method HTTPRedirect (line 126) | func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, mode, url st...
method HTTPError (line 135) | func (a *Assertions) HTTPError(handler http.HandlerFunc, mode, url strin...
method HTTPBodyContains (line 145) | func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, mode, ur...
method HTTPBodyNotContains (line 155) | func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, mode,...
FILE: vendor/github.com/stretchr/testify/assert/http_assertions_test.go
function httpOK (line 10) | func httpOK(w http.ResponseWriter, r *http.Request) {
function httpRedirect (line 14) | func httpRedirect(w http.ResponseWriter, r *http.Request) {
function httpError (line 18) | func httpError(w http.ResponseWriter, r *http.Request) {
function TestHTTPStatuses (line 22) | func TestHTTPStatuses(t *testing.T) {
function TestHTTPStatusesWrapper (line 39) | func TestHTTPStatusesWrapper(t *testing.T) {
function httpHelloName (line 56) | func httpHelloName(w http.ResponseWriter, r *http.Request) {
function TestHttpBody (line 61) | func TestHttpBody(t *testing.T) {
function TestHttpBodyWrappers (line 74) | func TestHttpBodyWrappers(t *testing.T) {
FILE: vendor/github.com/stretchr/testify/require/requirements.go
type TestingT (line 8) | type TestingT interface
function FailNow (line 14) | func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{...
function Implements (line 22) | func Implements(t TestingT, interfaceObject interface{}, object interfac...
function IsType (line 29) | func IsType(t TestingT, expectedType interface{}, object interface{}, ms...
function Equal (line 40) | func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...inter...
function Exactly (line 51) | func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...int...
function NotNil (line 62) | func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) {
function Nil (line 73) | func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) {
function Empty (line 85) | func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) {
function NotEmpty (line 98) | func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) {
function True (line 109) | func True(t TestingT, value bool, msgAndArgs ...interface{}) {
function False (line 120) | func False(t TestingT, value bool, msgAndArgs ...interface{}) {
function NotEqual (line 131) | func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...in...
function Contains (line 142) | func Contains(t TestingT, s, contains string, msgAndArgs ...interface{}) {
function NotContains (line 153) | func NotContains(t TestingT, s, contains string, msgAndArgs ...interface...
function Condition (line 160) | func Condition(t TestingT, comp assert.Comparison, msgAndArgs ...interfa...
function Panics (line 173) | func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{...
function NotPanics (line 186) | func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interfa...
function WithinDuration (line 197) | func WithinDuration(t TestingT, expected, actual time.Time, delta time.D...
function InDelta (line 208) | func InDelta(t TestingT, expected, actual interface{}, delta float64, ms...
function InEpsilon (line 217) | func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64...
function NoError (line 234) | func NoError(t TestingT, err error, msgAndArgs ...interface{}) {
function Error (line 248) | func Error(t TestingT, err error, msgAndArgs ...interface{}) {
function EqualError (line 263) | func EqualError(t TestingT, theError error, errString string, msgAndArgs...
FILE: vendor/github.com/stretchr/testify/require/requirements_test.go
type AssertionTesterInterface (line 10) | type AssertionTesterInterface interface
type AssertionTesterConformingObject (line 15) | type AssertionTesterConformingObject struct
method TestMethod (line 18) | func (a *AssertionTesterConformingObject) TestMethod() {
type AssertionTesterNonConformingObject (line 22) | type AssertionTesterNonConformingObject struct
type MockT (line 25) | type MockT struct
method FailNow (line 29) | func (t *MockT) FailNow() {
method Errorf (line 33) | func (t *MockT) Errorf(format string, args ...interface{}) {
function TestImplements (line 37) | func TestImplements(t *testing.T) {
function TestIsType (line 48) | func TestIsType(t *testing.T) {
function TestEqual (line 59) | func TestEqual(t *testing.T) {
function TestNotEqual (line 71) | func TestNotEqual(t *testing.T) {
function TestExactly (line 81) | func TestExactly(t *testing.T) {
function TestNotNil (line 96) | func TestNotNil(t *testing.T) {
function TestNil (line 107) | func TestNil(t *testing.T) {
function TestTrue (line 118) | func TestTrue(t *testing.T) {
function TestFalse (line 129) | func TestFalse(t *testing.T) {
function TestContains (line 140) | func TestContains(t *testing.T) {
function TestNotContains (line 151) | func TestNotContains(t *testing.T) {
function TestPanics (line 162) | func TestPanics(t *testing.T) {
function TestNotPanics (line 175) | func TestNotPanics(t *testing.T) {
function TestNoError (line 188) | func TestNoError(t *testing.T) {
function TestError (line 199) | func TestError(t *testing.T) {
function TestEqualError (line 210) | func TestEqualError(t *testing.T) {
function TestEmpty (line 221) | func TestEmpty(t *testing.T) {
function TestNotEmpty (line 232) | func TestNotEmpty(t *testing.T) {
function TestWithinDuration (line 243) | func TestWithinDuration(t *testing.T) {
function TestInDelta (line 257) | func TestInDelta(t *testing.T) {
FILE: vendor/gopkg.in/djherbis/stream.v1/fs.go
type File (line 9) | type File interface
type FileSystem (line 18) | type FileSystem interface
type stdFS (line 27) | type stdFS struct
method Create (line 29) | func (fs stdFS) Create(name string) (File, error) {
method Open (line 33) | func (fs stdFS) Open(name string) (File, error) {
method Remove (line 37) | func (fs stdFS) Remove(name string) error {
FILE: vendor/gopkg.in/djherbis/stream.v1/memfs.go
type memfs (line 13) | type memfs struct
method Create (line 25) | func (fs *memfs) Create(key string) (File, error) {
method Open (line 38) | func (fs *memfs) Open(key string) (File, error) {
method Remove (line 48) | func (fs *memfs) Remove(key string) error {
function NewMemFS (line 19) | func NewMemFS() FileSystem {
type memFile (line 55) | type memFile struct
method Name (line 62) | func (f *memFile) Name() string {
method Write (line 66) | func (f *memFile) Write(p []byte) (int, error) {
method Bytes (line 75) | func (f *memFile) Bytes() []byte {
method Close (line 81) | func (f *memFile) Close() error {
type memReader (line 85) | type memReader struct
method ReadAt (line 90) | func (r *memReader) ReadAt(p []byte, off int64) (n int, err error) {
method Read (line 99) | func (r *memReader) Read(p []byte) (n int, err error) {
method Close (line 105) | func (r *memReader) Close() error {
FILE: vendor/gopkg.in/djherbis/stream.v1/reader.go
type Reader (line 6) | type Reader struct
method Name (line 12) | func (r *Reader) Name() string { return r.file.Name() }
method ReadAt (line 17) | func (r *Reader) ReadAt(p []byte, off int64) (n int, err error) {
method Read (line 48) | func (r *Reader) Read(p []byte) (n int, err error) {
method Close (line 79) | func (r *Reader) Close() error {
FILE: vendor/gopkg.in/djherbis/stream.v1/stream.go
type Stream (line 13) | type Stream struct
method Name (line 40) | func (s *Stream) Name() string { return s.file.Name() }
method Write (line 43) | func (s *Stream) Write(p []byte) (int, error) {
method Close (line 52) | func (s *Stream) Close() error {
method Remove (line 63) | func (s *Stream) Remove() error {
method NextReader (line 72) | func (s *Stream) NextReader() (*Reader, error) {
method inc (line 91) | func (s *Stream) inc() { s.grp.Add(1) }
method dec (line 92) | func (s *Stream) dec() { s.grp.Done() }
function New (line 22) | func New(name string) (*Stream, error) {
function NewStream (line 27) | func NewStream(name string, fs FileSystem) (*Stream, error) {
FILE: vendor/gopkg.in/djherbis/stream.v1/stream_test.go
type badFs (line 17) | type badFs struct
method Create (line 28) | func (fs badFs) Create(name string) (File, error) { return os.Create(n...
method Open (line 29) | func (fs badFs) Open(name string) (File, error) {
method Remove (line 37) | func (fs badFs) Remove(name string) error { return os.Remove(name) }
type badFile (line 20) | type badFile struct
method Name (line 22) | func (r badFile) Name() string { return r.n...
method Read (line 23) | func (r badFile) Read(p []byte) (int, error) { return 0, ...
method ReadAt (line 24) | func (r badFile) ReadAt(p []byte, off int64) (int, error) { return 0, ...
method Write (line 25) | func (r badFile) Write(p []byte) (int, error) { return 0, ...
method Close (line 26) | func (r badFile) Close() error { return err...
function TestMemFs (line 39) | func TestMemFs(t *testing.T) {
function TestBadFile (line 47) | func TestBadFile(t *testing.T) {
function TestBadFs (line 78) | func TestBadFs(t *testing.T) {
function TestStd (line 97) | func TestStd(t *testing.T) {
function TestMem (line 109) | func TestMem(t *testing.T) {
function TestRemove (line 119) | func TestRemove(t *testing.T) {
function testFile (line 140) | func testFile(f *Stream, t *testing.T) {
function testReader (line 156) | func testReader(f *Stream, t *testing.T) {
FILE: vendor/gopkg.in/djherbis/stream.v1/sync.go
type broadcaster (line 8) | type broadcaster struct
method Wait (line 20) | func (b *broadcaster) Wait() {
method IsOpen (line 26) | func (b *broadcaster) IsOpen() bool {
method Close (line 30) | func (b *broadcaster) Close() error {
function newBroadcaster (line 14) | func newBroadcaster() *broadcaster {
Condensed preview — 65 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (262K chars).
[
{
"path": ".gitignore",
"chars": 39,
"preview": "cachedata/\nhttpcache\nGodeps/_workspace\n"
},
{
"path": "LICENSE",
"chars": 1098,
"preview": "The MIT License\n\nCopyright (c) 2010-2014 Lachlan Donald http://lachlan.me\n\nPermission is hereby granted, free of charge,"
},
{
"path": "README.md",
"chars": 1760,
"preview": "\n# httpcache\n\n`httpcache` provides an [rfc7234][] compliant golang [http.Handler](http://golang.org/pkg/net/http/#Handle"
},
{
"path": "bench_test.go",
"chars": 865,
"preview": "package httpcache_test\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/http/httputil\"\n\t\"net/url\"\n\t\"testing\"\n\n\t\"g"
},
{
"path": "cache.go",
"chars": 5335,
"preview": "package httpcache\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"crypto/sha256\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/textproto"
},
{
"path": "cache_test.go",
"chars": 1167,
"preview": "package httpcache_test\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/lox/httpcache\"\n\t\"github.com/stretchr/te"
},
{
"path": "cachecontrol.go",
"chars": 2058,
"preview": "package httpcache\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tCacheControlHeader = \"Cac"
},
{
"path": "cachecontrol_test.go",
"chars": 1264,
"preview": "package httpcache_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/lox/httpcache\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfun"
},
{
"path": "cli/httpcache.go",
"chars": 1695,
"preview": "package main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"os\"\n\n\t\"github.com/lox/httpcache\"\n\t\"github.com/l"
},
{
"path": "handler.go",
"chars": 14106,
"preview": "package httpcache\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"math\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"sync\"\n\t"
},
{
"path": "header.go",
"chars": 480,
"preview": "package httpcache\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar errNoHeader = errors.New(\"Header doesn't exi"
},
{
"path": "httplog/log.go",
"chars": 2729,
"preview": "package httplog\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\ncons"
},
{
"path": "key.go",
"chars": 1728,
"preview": "package httpcache\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n)\n\n// Key represents a unique identifier f"
},
{
"path": "key_test.go",
"chars": 1558,
"preview": "package httpcache_test\n\nimport (\n\t\"net/url\"\n\t\"testing\"\n\n\t\"github.com/lox/httpcache\"\n\t\"github.com/stretchr/testify/assert"
},
{
"path": "logger.go",
"chars": 325,
"preview": "package httpcache\n\nimport \"log\"\n\nconst (\n\tansiRed = \"\\x1b[31;1m\"\n\tansiReset = \"\\x1b[0m\"\n)\n\nvar DebugLogging = false\n\nf"
},
{
"path": "resource.go",
"chars": 5032,
"preview": "package httpcache\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tlastModDivisor = "
},
{
"path": "spec_test.go",
"chars": 16131,
"preview": "package httpcache_test\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/lox/httpcache\"\n"
},
{
"path": "util_test.go",
"chars": 4408,
"preview": "package httpcache_test\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strconv\"\n\t\"string"
},
{
"path": "validator.go",
"chars": 1556,
"preview": "package httpcache\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n)\n\ntype Validator struct {\n\tHandler http.Handler\n}\n\n"
},
{
"path": "vendor/github.com/rainycape/vfs/LICENSE",
"chars": 16726,
"preview": "Mozilla Public License Version 2.0\n==================================\n\n1. Definitions\n--------------\n\n1.1. \"Contributor\""
},
{
"path": "vendor/github.com/rainycape/vfs/README.md",
"chars": 193,
"preview": "# vfs\n\nvfs implements Virtual File Systems with read-write support in Go (golang)\n\n[\n\nfunc BenchmarkLoadGoSrc(b *testing.B) {"
},
{
"path": "vendor/github.com/rainycape/vfs/chroot.go",
"chars": 1726,
"preview": "package vfs\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n)\n\ntype chrootFileSystem struct {\n\troot string\n\tfs VFS\n}\n\nfunc (fs *chrootF"
},
{
"path": "vendor/github.com/rainycape/vfs/doc.go",
"chars": 1012,
"preview": "// Package vfs implements Virtual File Systems with read-write support.\n//\n// All implementatations use slash ('/') sepa"
},
{
"path": "vendor/github.com/rainycape/vfs/file.go",
"chars": 4698,
"preview": "package vfs\n\nimport (\n\t\"os\"\n\t\"path\"\n\t\"sync\"\n\t\"time\"\n)\n\n// EntryType indicates the type of the entry.\ntype EntryType uint"
},
{
"path": "vendor/github.com/rainycape/vfs/file_util.go",
"chars": 3060,
"preview": "package vfs\n\nimport (\n\t\"bytes\"\n\t\"compress/zlib\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"runtime\"\n\t\"time\"\n)\n\nvar (\n\terrFileClosed "
},
{
"path": "vendor/github.com/rainycape/vfs/fs.go",
"chars": 3466,
"preview": "package vfs\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"path/filepath\"\n)\n\n// IMPORTANT: Note about wrapping os. functi"
},
{
"path": "vendor/github.com/rainycape/vfs/map.go",
"chars": 1158,
"preview": "package vfs\n\nimport (\n\t\"path\"\n\t\"sort\"\n)\n\n// Map returns an in-memory file system using the given files argument to\n// po"
},
{
"path": "vendor/github.com/rainycape/vfs/mem.go",
"chars": 5122,
"preview": "package vfs\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\tpathpkg \"path\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar (\n\terrNoEmptyNameFile = e"
},
{
"path": "vendor/github.com/rainycape/vfs/mounter.go",
"chars": 3690,
"preview": "package vfs\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n)\n\nconst (\n\tseparator = \"/\"\n)\n\nfunc hasSubdir(root, dir string) (s"
},
{
"path": "vendor/github.com/rainycape/vfs/open.go",
"chars": 3058,
"preview": "package vfs\n\nimport (\n\t\"archive/tar\"\n\t\"archive/zip\"\n\t\"bytes\"\n\t\"compress/bzip2\"\n\t\"compress/gzip\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil"
},
{
"path": "vendor/github.com/rainycape/vfs/open_test.go",
"chars": 883,
"preview": "package vfs\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n)\n\nfunc testOpenedVFS(t *testing.T, fs VFS) {\n\tdata1, err := ReadFile("
},
{
"path": "vendor/github.com/rainycape/vfs/rewriter.go",
"chars": 1368,
"preview": "package vfs\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\ntype rewriterFileSystem struct {\n\tfs VFS\n\trewriter func(string) string\n}\n\nfu"
},
{
"path": "vendor/github.com/rainycape/vfs/ro.go",
"chars": 1409,
"preview": "package vfs\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n)\n\nvar (\n\t// ErrReadOnlyFileSystem is the error returned by read only file "
},
{
"path": "vendor/github.com/rainycape/vfs/testdata/download-data.sh",
"chars": 259,
"preview": "#!/bin/sh\n\nSRC=https://storage.googleapis.com/golang/go1.3.src.tar.gz\nif which curl > /dev/null 2>&1; then\n curl -O $"
},
{
"path": "vendor/github.com/rainycape/vfs/testdata/fs/a/b/c/d",
"chars": 2,
"preview": "go"
},
{
"path": "vendor/github.com/rainycape/vfs/testdata/fs/empty",
"chars": 0,
"preview": ""
},
{
"path": "vendor/github.com/rainycape/vfs/testdata/update-fs.sh",
"chars": 120,
"preview": "#!/bin/sh\n\nset -e\ncd fs\nzip -r ../fs.zip *\ntar cvvf ../fs.tar *\ntar cvvzf ../fs.tar.gz *\ntar cvvjf ../fs.tar.bz2 *\ncd -\n"
},
{
"path": "vendor/github.com/rainycape/vfs/util.go",
"chars": 5847,
"preview": "package vfs\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\tpathpkg \"path\"\n\t\"strings\"\n)\n\nvar (\n\t// SkipDir is used by a W"
},
{
"path": "vendor/github.com/rainycape/vfs/vfs.go",
"chars": 2893,
"preview": "package vfs\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\n// Opener is the interface which specifies the methods for\n// opening a file. All t"
},
{
"path": "vendor/github.com/rainycape/vfs/vfs_test.go",
"chars": 7543,
"preview": "package vfs\n\nimport (\n\t\"crypto/sha1\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nconst "
},
{
"path": "vendor/github.com/rainycape/vfs/write.go",
"chars": 1678,
"preview": "package vfs\n\nimport (\n\t\"archive/tar\"\n\t\"archive/zip\"\n\t\"compress/gzip\"\n\t\"io\"\n\t\"os\"\n)\n\nfunc copyVFS(fs VFS, copier func(p s"
},
{
"path": "vendor/github.com/rainycape/vfs/write_test.go",
"chars": 795,
"preview": "package vfs\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"path/filepath\"\n\t\"testing\"\n)\n\ntype writeTester struct {\n\tname string\n\twriter fun"
},
{
"path": "vendor/github.com/stretchr/testify/assert/assertions.go",
"chars": 20253,
"preview": "package assert\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n)\n\n// TestingT is a"
},
{
"path": "vendor/github.com/stretchr/testify/assert/assertions_test.go",
"chars": 17937,
"preview": "package assert\n\nimport (\n\t\"errors\"\n\t\"regexp\"\n\t\"testing\"\n\t\"time\"\n)\n\n// AssertionTesterInterface defines an interface to b"
},
{
"path": "vendor/github.com/stretchr/testify/assert/doc.go",
"chars": 4823,
"preview": "// A set of comprehensive testing tools for use with the normal Go testing system.\n//\n// Example Usage\n//\n// The followi"
},
{
"path": "vendor/github.com/stretchr/testify/assert/errors.go",
"chars": 326,
"preview": "package assert\n\nimport (\n\t\"errors\"\n)\n\n// AnError is an error instance useful for testing. If the code does not care\n// "
},
{
"path": "vendor/github.com/stretchr/testify/assert/forward_assertions.go",
"chars": 9199,
"preview": "package assert\n\nimport \"time\"\n\ntype Assertions struct {\n\tt TestingT\n}\n\nfunc New(t TestingT) *Assertions {\n\treturn &Asser"
},
{
"path": "vendor/github.com/stretchr/testify/assert/forward_assertions_test.go",
"chars": 14042,
"preview": "package assert\n\nimport (\n\t\"errors\"\n\t\"regexp\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestImplementsWrapper(t *testing.T) {\n\tassert :="
},
{
"path": "vendor/github.com/stretchr/testify/assert/http_assertions.go",
"chars": 5723,
"preview": "package assert\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"strings\"\n)\n\n// httpCode is a helper that r"
},
{
"path": "vendor/github.com/stretchr/testify/assert/http_assertions_test.go",
"chars": 3589,
"preview": "package assert\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"testing\"\n)\n\nfunc httpOK(w http.ResponseWriter, r *http.Request)"
},
{
"path": "vendor/github.com/stretchr/testify/require/doc.go",
"chars": 2465,
"preview": "// Alternative testing tools which stop test execution if test failed.\n//\n// Example Usage\n//\n// The following is a comp"
},
{
"path": "vendor/github.com/stretchr/testify/require/requirements.go",
"chars": 8453,
"preview": "package require\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"time\"\n)\n\ntype TestingT interface {\n\tErrorf(format stri"
},
{
"path": "vendor/github.com/stretchr/testify/require/requirements_test.go",
"chars": 4552,
"preview": "package require\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n)\n\n// AssertionTesterInterface defines an interface to be used fo"
},
{
"path": "vendor/gopkg.in/djherbis/stream.v1/LICENSE",
"chars": 1076,
"preview": "The MIT License (MIT)\n\nCopyright (c) 2015 Dustin H\n\nPermission is hereby granted, free of charge, to any person obtainin"
},
{
"path": "vendor/gopkg.in/djherbis/stream.v1/README.md",
"chars": 2874,
"preview": "stream \n==========\n\n[](https://godoc.org/github.com/djh"
},
{
"path": "vendor/gopkg.in/djherbis/stream.v1/fs.go",
"chars": 1071,
"preview": "package stream\n\nimport (\n\t\"io\"\n\t\"os\"\n)\n\n// File is a backing data-source for a Stream.\ntype File interface {\n\tName() str"
},
{
"path": "vendor/gopkg.in/djherbis/stream.v1/memfs.go",
"chars": 1805,
"preview": "package stream\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"io\"\n\t\"sync\"\n)\n\n// ErrNotFoundInMem is returned when an in-memory FileSyste"
},
{
"path": "vendor/gopkg.in/djherbis/stream.v1/reader.go",
"chars": 1564,
"preview": "package stream\n\nimport \"io\"\n\n// Reader is a concurrent-safe Stream Reader.\ntype Reader struct {\n\ts *Stream\n\tfile File"
},
{
"path": "vendor/gopkg.in/djherbis/stream.v1/stream.go",
"chars": 2399,
"preview": "// Package stream provides a way to read and write to a synchronous buffered pipe, with multiple reader support.\npackage"
},
{
"path": "vendor/gopkg.in/djherbis/stream.v1/stream_test.go",
"chars": 3503,
"preview": "package stream\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar (\n\ttestdata = []byte(\"hello\\nworld\\n\")"
},
{
"path": "vendor/gopkg.in/djherbis/stream.v1/sync.go",
"chars": 494,
"preview": "package stream\n\nimport (\n\t\"sync\"\n\t\"sync/atomic\"\n)\n\ntype broadcaster struct {\n\tsync.RWMutex\n\tclosed uint32\n\t*sync.Cond\n}\n"
},
{
"path": "vendor/vendor.json",
"chars": 916,
"preview": "{\n\t\"comment\": \"\",\n\t\"ignore\": \"\",\n\t\"package\": [\n\t\t{\n\t\t\t\"checksumSHA1\": \"uz5IFOxRG/odXyNSLahNaQmRfTw=\",\n\t\t\t\"path\": \"github"
},
{
"path": "wercker.yml",
"chars": 201,
"preview": "# https://registry.hub.docker.com/u/library/golang/\nbox: golang\nbuild:\n steps:\n - setup-go-workspace\n - script:\n "
}
]
// ... and 1 more files (download for full content)
About this extraction
This page contains the full source code of the lox/httpcache GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 65 files (232.5 KB), approximately 67.5k tokens, and a symbol index with 615 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.