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). [![wercker status](https://app.wercker.com/status/a76986990d27e72ea656bb37bb93f59f/m "wercker status")](https://app.wercker.com/project/bykey/a76986990d27e72ea656bb37bb93f59f) [![GoDoc](https://godoc.org/github.com/lox/httpcache?status.svg)](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) [![GoDoc](https://godoc.org/github.com/rainycape/vfs?status.svg)](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}, {[...]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 { assert.True(mockAssert.Len(c.v, c.l), "%#v have %d items", c.v, c.l) } } func TestWithinDurationWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) a := time.Now() b := a.Add(10 * time.Second) assert.True(mockAssert.WithinDuration(a, b, 10*time.Second), "A 10s difference is within a 10s time difference") assert.True(mockAssert.WithinDuration(b, a, 10*time.Second), "A 10s difference is within a 10s time difference") assert.False(mockAssert.WithinDuration(a, b, 9*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(b, a, 9*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(a, b, -9*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(b, a, -9*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(a, b, -11*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(b, a, -11*time.Second), "A 10s difference is not within a 9s time difference") } func TestInDeltaWrapper(t *testing.T) { assert := New(new(testing.T)) True(t, assert.InDelta(1.001, 1, 0.01), "|1.001 - 1| <= 0.01") True(t, assert.InDelta(1, 1.001, 0.01), "|1 - 1.001| <= 0.01") True(t, assert.InDelta(1, 2, 1), "|1 - 2| <= 1") False(t, assert.InDelta(1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail") False(t, assert.InDelta(2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail") False(t, assert.InDelta("", 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, assert.InDelta(tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta) } } func TestInEpsilonWrapper(t *testing.T) { assert := New(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, assert.InEpsilon(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, assert.InEpsilon(tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) } } func TestRegexpWrapper(t *testing.T) { assert := New(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, assert.Regexp(tc.rx, tc.str)) True(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str)) False(t, assert.NotRegexp(tc.rx, tc.str)) False(t, assert.NotRegexp(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, assert.Regexp(tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str) False(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str)) True(t, assert.NotRegexp(tc.rx, tc.str)) True(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str)) } } ================================================ FILE: vendor/github.com/stretchr/testify/assert/http_assertions.go ================================================ package assert import ( "fmt" "net/http" "net/http/httptest" "net/url" "strings" ) // httpCode is a helper that returns HTTP code of the response. It returns -1 // if building a new request fails. func httpCode(handler http.HandlerFunc, mode, url string, values url.Values) int { w := httptest.NewRecorder() req, err := http.NewRequest(mode, url+"?"+values.Encode(), nil) if err != nil { return -1 } handler(w, req) return w.Code } // HTTPSuccess asserts that a specified handler returns a success status code. // // assert.HTTPSuccess(t, myHandler, "POST", http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccess(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values) bool { code := httpCode(handler, mode, url, values) if code == -1 { return false } return code >= http.StatusOK && code <= http.StatusPartialContent } // HTTPRedirect asserts that a specified handler returns a redirect status code. // // assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPRedirect(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values) bool { code := httpCode(handler, mode, url, values) if code == -1 { return false } return code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect } // HTTPError asserts that a specified handler returns an error status code. // // assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPError(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values) bool { code := httpCode(handler, mode, url, values) if code == -1 { return false } return code >= http.StatusBadRequest } // HttpBody is a helper that returns HTTP body of the response. It returns // empty string if building a new request fails. func HttpBody(handler http.HandlerFunc, mode, url string, values url.Values) string { w := httptest.NewRecorder() req, err := http.NewRequest(mode, url+"?"+values.Encode(), nil) if err != nil { return "" } handler(w, req) return w.Body.String() } // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // // assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContains(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values, str interface{}) bool { body := HttpBody(handler, mode, url, values) contains := strings.Contains(body, fmt.Sprint(str)) if !contains { Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) } return contains } // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // // assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, mode, url string, values url.Values, str interface{}) bool { body := HttpBody(handler, mode, url, values) contains := strings.Contains(body, fmt.Sprint(str)) if contains { Fail(t, "Expected response body for %s to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body) } return !contains } // // Assertions Wrappers // // HTTPSuccess asserts that a specified handler returns a success status code. // // assert.HTTPSuccess(myHandler, "POST", http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, mode, url string, values url.Values) bool { return HTTPSuccess(a.t, handler, mode, url, values) } // HTTPRedirect asserts that a specified handler returns a redirect status code. // // assert.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, mode, url string, values url.Values) bool { return HTTPRedirect(a.t, handler, mode, url, values) } // HTTPError asserts that a specified handler returns an error status code. // // assert.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPError(handler http.HandlerFunc, mode, url string, values url.Values) bool { return HTTPError(a.t, handler, mode, url, values) } // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // // assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, mode, url string, values url.Values, str interface{}) bool { return HTTPBodyContains(a.t, handler, mode, url, values, str) } // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // // assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, mode, url string, values url.Values, str interface{}) bool { return HTTPBodyNotContains(a.t, handler, mode, url, values, str) } ================================================ FILE: vendor/github.com/stretchr/testify/assert/http_assertions_test.go ================================================ package assert import ( "fmt" "net/http" "net/url" "testing" ) func httpOK(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } func httpRedirect(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTemporaryRedirect) } func httpError(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) } func TestHTTPStatuses(t *testing.T) { assert := New(t) mockT := new(testing.T) assert.Equal(HTTPSuccess(mockT, httpOK, "GET", "/", nil), true) assert.Equal(HTTPSuccess(mockT, httpRedirect, "GET", "/", nil), false) assert.Equal(HTTPSuccess(mockT, httpError, "GET", "/", nil), false) assert.Equal(HTTPRedirect(mockT, httpOK, "GET", "/", nil), false) assert.Equal(HTTPRedirect(mockT, httpRedirect, "GET", "/", nil), true) assert.Equal(HTTPRedirect(mockT, httpError, "GET", "/", nil), false) assert.Equal(HTTPError(mockT, httpOK, "GET", "/", nil), false) assert.Equal(HTTPError(mockT, httpRedirect, "GET", "/", nil), false) assert.Equal(HTTPError(mockT, httpError, "GET", "/", nil), true) } func TestHTTPStatusesWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) assert.Equal(mockAssert.HTTPSuccess(httpOK, "GET", "/", nil), true) assert.Equal(mockAssert.HTTPSuccess(httpRedirect, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPSuccess(httpError, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPRedirect(httpOK, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPRedirect(httpRedirect, "GET", "/", nil), true) assert.Equal(mockAssert.HTTPRedirect(httpError, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPError(httpOK, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPError(httpRedirect, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPError(httpError, "GET", "/", nil), true) } func httpHelloName(w http.ResponseWriter, r *http.Request) { name := r.FormValue("name") w.Write([]byte(fmt.Sprintf("Hello, %s!", name))) } func TestHttpBody(t *testing.T) { assert := New(t) mockT := new(testing.T) assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) assert.False(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) assert.True(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) } func TestHttpBodyWrappers(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) assert.False(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) assert.True(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) } ================================================ FILE: vendor/github.com/stretchr/testify/require/doc.go ================================================ // Alternative testing tools which stop test execution if test failed. // // Example Usage // // The following is a complete example using require in a standard test function: // import ( // "testing" // "github.com/stretchr/testify/require" // ) // // func TestSomething(t *testing.T) { // // var a string = "Hello" // var b string = "Hello" // // require.Equal(t, a, b, "The two words should be the same.") // // } // // Assertions // // The `require` package have same global functions as in the `assert` package, // but instead of returning a boolean result they call `t.FailNow()`. // // 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: // // require.Equal(t, expected, actual [, message [, format-args]) // // require.NotEqual(t, notExpected, actual [, message [, format-args]]) // // require.True(t, actualBool [, message [, format-args]]) // // require.False(t, actualBool [, message [, format-args]]) // // require.Nil(t, actualObject [, message [, format-args]]) // // require.NotNil(t, actualObject [, message [, format-args]]) // // require.Empty(t, actualObject [, message [, format-args]]) // // require.NotEmpty(t, actualObject [, message [, format-args]]) // // require.Error(t, errorObject [, message [, format-args]]) // // require.NoError(t, errorObject [, message [, format-args]]) // // require.EqualError(t, theError, errString [, message [, format-args]]) // // require.Implements(t, (*MyInterface)(nil), new(MyObject) [,message [, format-args]]) // // require.IsType(t, expectedObject, actualObject [, message [, format-args]]) // // require.Contains(t, string, substring [, message [, format-args]]) // // require.NotContains(t, string, substring [, message [, format-args]]) // // require.Panics(t, func(){ // // // call code that should panic // // } [, message [, format-args]]) // // require.NotPanics(t, func(){ // // // call code that should not panic // // } [, message [, format-args]]) // // require.WithinDuration(t, timeA, timeB, deltaTime, [, message [, format-args]]) // // require.InDelta(t, numA, numB, delta, [, message [, format-args]]) // // require.InEpsilon(t, numA, numB, epsilon, [, message [, format-args]]) package require ================================================ FILE: vendor/github.com/stretchr/testify/require/requirements.go ================================================ package require import ( "github.com/stretchr/testify/assert" "time" ) type TestingT interface { Errorf(format string, args ...interface{}) FailNow() } // Fail reports a failure through func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) { assert.Fail(t, failureMessage, msgAndArgs...) t.FailNow() } // Implements asserts that an object is implemented by the specified interface. // // require.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject") func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { if !assert.Implements(t, interfaceObject, object, msgAndArgs...) { t.FailNow() } } // IsType asserts that the specified objects are of the same type. func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { if !assert.IsType(t, expectedType, object, msgAndArgs...) { t.FailNow() } } // Equal asserts that two objects are equal. // // require.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{}) { if !assert.Equal(t, expected, actual, msgAndArgs...) { t.FailNow() } } // Exactly asserts that two objects are equal is value and type. // // require.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{}) { if !assert.Exactly(t, expected, actual, msgAndArgs...) { t.FailNow() } } // NotNil asserts that the specified object is not nil. // // require.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{}) { if !assert.NotNil(t, object, msgAndArgs...) { t.FailNow() } } // Nil asserts that the specified object is nil. // // require.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{}) { if !assert.Nil(t, object, msgAndArgs...) { t.FailNow() } } // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // require.Empty(t, obj) // // Returns whether the assertion was successful (true) or not (false). func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) { if !assert.Empty(t, object, msgAndArgs...) { t.FailNow() } } // 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. // // require.NotEmpty(t, obj) // require.Equal(t, "one", obj[0]) // // Returns whether the assertion was successful (true) or not (false). func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) { if !assert.NotEmpty(t, object, msgAndArgs...) { t.FailNow() } } // True asserts that the specified value is true. // // require.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{}) { if !assert.True(t, value, msgAndArgs...) { t.FailNow() } } // False asserts that the specified value is true. // // require.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{}) { if !assert.False(t, value, msgAndArgs...) { t.FailNow() } } // NotEqual asserts that the specified values are NOT equal. // // require.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{}) { if !assert.NotEqual(t, expected, actual, msgAndArgs...) { t.FailNow() } } // Contains asserts that the specified string contains the specified substring. // // require.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 string, msgAndArgs ...interface{}) { if !assert.Contains(t, s, contains, msgAndArgs...) { t.FailNow() } } // NotContains asserts that the specified string does NOT contain the specified substring. // // require.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 string, msgAndArgs ...interface{}) { if !assert.NotContains(t, s, contains, msgAndArgs...) { t.FailNow() } } // Condition uses a Comparison to assert a complex condition. func Condition(t TestingT, comp assert.Comparison, msgAndArgs ...interface{}) { if !assert.Condition(t, comp, msgAndArgs...) { t.FailNow() } } // Panics asserts that the code inside the specified PanicTestFunc panics. // // require.Panics(t, func(){ // GoCrazy() // }, "Calling GoCrazy() should panic") // // Returns whether the assertion was successful (true) or not (false). func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if !assert.Panics(t, f, msgAndArgs...) { t.FailNow() } } // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // // require.NotPanics(t, func(){ // RemainCalm() // }, "Calling RemainCalm() should NOT panic") // // Returns whether the assertion was successful (true) or not (false). func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if !assert.NotPanics(t, f, msgAndArgs...) { t.FailNow() } } // WithinDuration asserts that the two times are within duration delta of each other. // // require.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{}) { if !assert.WithinDuration(t, expected, actual, delta, msgAndArgs...) { t.FailNow() } } // InDelta asserts that the two numerals are within delta of each other. // // require.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{}) { if !assert.InDelta(t, expected, actual, delta, msgAndArgs...) { t.FailNow() } } // 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{}) { if !assert.InEpsilon(t, expected, actual, epsilon, msgAndArgs...) { t.FailNow() } } /* Errors */ // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // require.NoError(t, err) // require.Equal(t, actualObj, expectedObj) // // Returns whether the assertion was successful (true) or not (false). func NoError(t TestingT, err error, msgAndArgs ...interface{}) { if !assert.NoError(t, err, msgAndArgs...) { t.FailNow() } } // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // require.Error(t, err, "An error was expected") // require.Equal(t, err, expectedError) // } // // Returns whether the assertion was successful (true) or not (false). func Error(t TestingT, err error, msgAndArgs ...interface{}) { if !assert.Error(t, err, msgAndArgs...) { t.FailNow() } } // EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // require.Error(t, err, "An error was expected") // require.Equal(t, err, expectedError) // } // // Returns whether the assertion was successful (true) or not (false). func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) { if !assert.EqualError(t, theError, errString, msgAndArgs...) { t.FailNow() } } ================================================ FILE: vendor/github.com/stretchr/testify/require/requirements_test.go ================================================ package require import ( "errors" "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 { } type MockT struct { Failed bool } func (t *MockT) FailNow() { t.Failed = true } func (t *MockT) Errorf(format string, args ...interface{}) { _, _ = format, args } func TestImplements(t *testing.T) { Implements(t, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) mockT := new(MockT) Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestIsType(t *testing.T) { IsType(t, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) mockT := new(MockT) IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestEqual(t *testing.T) { Equal(t, 1, 1) mockT := new(MockT) Equal(mockT, 1, 2) if !mockT.Failed { t.Error("Check should fail") } } func TestNotEqual(t *testing.T) { NotEqual(t, 1, 2) mockT := new(MockT) NotEqual(mockT, 2, 2) if !mockT.Failed { t.Error("Check should fail") } } func TestExactly(t *testing.T) { a := float32(1) b := float32(1) c := float64(1) Exactly(t, a, b) mockT := new(MockT) Exactly(mockT, a, c) if !mockT.Failed { t.Error("Check should fail") } } func TestNotNil(t *testing.T) { NotNil(t, new(AssertionTesterConformingObject)) mockT := new(MockT) NotNil(mockT, nil) if !mockT.Failed { t.Error("Check should fail") } } func TestNil(t *testing.T) { Nil(t, nil) mockT := new(MockT) Nil(mockT, new(AssertionTesterConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestTrue(t *testing.T) { True(t, true) mockT := new(MockT) True(mockT, false) if !mockT.Failed { t.Error("Check should fail") } } func TestFalse(t *testing.T) { False(t, false) mockT := new(MockT) False(mockT, true) if !mockT.Failed { t.Error("Check should fail") } } func TestContains(t *testing.T) { Contains(t, "Hello World", "Hello") mockT := new(MockT) Contains(mockT, "Hello World", "Salut") if !mockT.Failed { t.Error("Check should fail") } } func TestNotContains(t *testing.T) { NotContains(t, "Hello World", "Hello!") mockT := new(MockT) NotContains(mockT, "Hello World", "Hello") if !mockT.Failed { t.Error("Check should fail") } } func TestPanics(t *testing.T) { Panics(t, func() { panic("Panic!") }) mockT := new(MockT) Panics(mockT, func() {}) if !mockT.Failed { t.Error("Check should fail") } } func TestNotPanics(t *testing.T) { NotPanics(t, func() {}) mockT := new(MockT) NotPanics(mockT, func() { panic("Panic!") }) if !mockT.Failed { t.Error("Check should fail") } } func TestNoError(t *testing.T) { NoError(t, nil) mockT := new(MockT) NoError(mockT, errors.New("some error")) if !mockT.Failed { t.Error("Check should fail") } } func TestError(t *testing.T) { Error(t, errors.New("some error")) mockT := new(MockT) Error(mockT, nil) if !mockT.Failed { t.Error("Check should fail") } } func TestEqualError(t *testing.T) { EqualError(t, errors.New("some error"), "some error") mockT := new(MockT) EqualError(mockT, errors.New("some error"), "Not some error") if !mockT.Failed { t.Error("Check should fail") } } func TestEmpty(t *testing.T) { Empty(t, "") mockT := new(MockT) Empty(mockT, "x") if !mockT.Failed { t.Error("Check should fail") } } func TestNotEmpty(t *testing.T) { NotEmpty(t, "x") mockT := new(MockT) NotEmpty(mockT, "") if !mockT.Failed { t.Error("Check should fail") } } func TestWithinDuration(t *testing.T) { a := time.Now() b := a.Add(10 * time.Second) WithinDuration(t, a, b, 15*time.Second) mockT := new(MockT) WithinDuration(mockT, a, b, 5*time.Second) if !mockT.Failed { t.Error("Check should fail") } } func TestInDelta(t *testing.T) { InDelta(t, 1.001, 1, 0.01) mockT := new(MockT) InDelta(mockT, 1, 2, 0.5) if !mockT.Failed { t.Error("Check should fail") } } ================================================ FILE: vendor/gopkg.in/djherbis/stream.v1/LICENSE ================================================ The MIT License (MIT) Copyright (c) 2015 Dustin H 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: vendor/gopkg.in/djherbis/stream.v1/README.md ================================================ stream ========== [![GoDoc](https://godoc.org/github.com/djherbis/stream?status.svg)](https://godoc.org/github.com/djherbis/stream) [![Release](https://img.shields.io/github/release/djherbis/stream.svg)](https://github.com/djherbis/stream/releases/latest) [![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](LICENSE.txt) [![Build Status](https://travis-ci.org/djherbis/stream.svg?branch=master)](https://travis-ci.org/djherbis/stream) [![Coverage Status](https://coveralls.io/repos/djherbis/stream/badge.svg?branch=master)](https://coveralls.io/r/djherbis/stream?branch=master) Usage ------------ Write and Read concurrently, and independently. To explain further, if you need to write to multiple places you can use io.MultiWriter, if you need multiple Readers on something you can use io.TeeReader. If you want concurrency you can use io.Pipe(). However all of these methods "tie" each Read/Write together, your readers can't read from different places in the stream, each write must be distributed to all readers in sequence. This package provides a way for multiple Readers to read off the same Writer, without waiting for the others. This is done by writing to a "File" interface which buffers the input so it can be read at any time from many independent readers. Readers can even be created while writing or after the stream is closed. They will all see a consistent view of the stream and will block until the section of the stream they request is written, all while being unaffected by the actions of the other readers. The use case for this stems from my other project djherbis/fscache. I needed a byte caching mechanism which allowed many independent clients to have access to the data while it was being written, rather than re-generating the byte stream for each of them or waiting for a complete copy of the stream which could be stored and then re-used. ```go import( "io" "log" "os" "time" "github.com/djherbis/stream" ) func main(){ w, err := stream.New("mystream") if err != nil { log.Fatal(err) } go func(){ io.WriteString(w, "Hello World!") <-time.After(time.Second) io.WriteString(w, "Streaming updates...") w.Close() }() waitForReader := make(chan struct{}) go func(){ // Read from the stream r, err := w.NextReader() if err != nil { log.Fatal(err) } io.Copy(os.Stdout, r) // Hello World! (1 second) Streaming updates... r.Close() close(waitForReader) }() // Full copy of the stream! r, err := w.NextReader() if err != nil { log.Fatal(err) } io.Copy(os.Stdout, r) // Hello World! (1 second) Streaming updates... // r supports io.ReaderAt too. p := make([]byte, 4) r.ReadAt(p, 1) // Read "ello" into p r.Close() <-waitForReader // don't leave main before go-routine finishes } ``` Installation ------------ ```sh go get github.com/djherbis/stream ``` ================================================ FILE: vendor/gopkg.in/djherbis/stream.v1/fs.go ================================================ package stream import ( "io" "os" ) // File is a backing data-source for a Stream. type File interface { Name() string // The name used to Create/Open the File io.Reader // Reader must continue reading after EOF on subsequent calls after more Writes. io.ReaderAt // Similarly to Reader io.Writer // Concurrent reading/writing must be supported. io.Closer // Close should do any cleanup when done with the File. } // FileSystem is used to manage Files type FileSystem interface { Create(name string) (File, error) // Create must return a new File for Writing Open(name string) (File, error) // Open must return an existing File for Reading Remove(name string) error // Remove deletes an existing File } // StdFileSystem is backed by the os package. var StdFileSystem FileSystem = stdFS{} type stdFS struct{} func (fs stdFS) Create(name string) (File, error) { return os.Create(name) } func (fs stdFS) Open(name string) (File, error) { return os.Open(name) } func (fs stdFS) Remove(name string) error { return os.Remove(name) } ================================================ FILE: vendor/gopkg.in/djherbis/stream.v1/memfs.go ================================================ package stream import ( "bytes" "errors" "io" "sync" ) // ErrNotFoundInMem is returned when an in-memory FileSystem cannot find a file. var ErrNotFoundInMem = errors.New("not found") type memfs struct { mu sync.RWMutex files map[string]*memFile } // NewMemFS returns a New in-memory FileSystem func NewMemFS() FileSystem { return &memfs{ files: make(map[string]*memFile), } } func (fs *memfs) Create(key string) (File, error) { fs.mu.Lock() defer fs.mu.Unlock() file := &memFile{ name: key, r: bytes.NewBuffer(nil), } file.memReader.memFile = file fs.files[key] = file return file, nil } func (fs *memfs) Open(key string) (File, error) { fs.mu.RLock() defer fs.mu.RUnlock() if f, ok := fs.files[key]; ok { return &memReader{memFile: f}, nil } return nil, ErrNotFoundInMem } func (fs *memfs) Remove(key string) error { fs.mu.Lock() defer fs.mu.Unlock() delete(fs.files, key) return nil } type memFile struct { mu sync.RWMutex name string r *bytes.Buffer memReader } func (f *memFile) Name() string { return f.name } func (f *memFile) Write(p []byte) (int, error) { if len(p) > 0 { f.mu.Lock() defer f.mu.Unlock() return f.r.Write(p) } return len(p), nil } func (f *memFile) Bytes() []byte { f.mu.RLock() defer f.mu.RUnlock() return f.r.Bytes() } func (f *memFile) Close() error { return nil } type memReader struct { *memFile n int } func (r *memReader) ReadAt(p []byte, off int64) (n int, err error) { data := r.Bytes() if int64(len(data)) < off { return 0, io.EOF } n, err = bytes.NewReader(data[off:]).ReadAt(p, 0) return n, err } func (r *memReader) Read(p []byte) (n int, err error) { n, err = bytes.NewReader(r.Bytes()[r.n:]).Read(p) r.n += n return n, err } func (r *memReader) Close() error { return nil } ================================================ FILE: vendor/gopkg.in/djherbis/stream.v1/reader.go ================================================ package stream import "io" // Reader is a concurrent-safe Stream Reader. type Reader struct { s *Stream file File } // Name returns the name of the underlying File in the FileSystem. func (r *Reader) Name() string { return r.file.Name() } // ReadAt lets you Read from specific offsets in the Stream. // ReadAt blocks while waiting for the requested section of the Stream to be written, // unless the Stream is closed in which case it will always return immediately. func (r *Reader) ReadAt(p []byte, off int64) (n int, err error) { r.s.b.RLock() defer r.s.b.RUnlock() var m int for { m, err = r.file.ReadAt(p[n:], off+int64(n)) n += m if r.s.b.IsOpen() { switch { case n != 0 && err == nil: return n, err case err == io.EOF: r.s.b.Wait() case err != nil: return n, err } } else { return n, err } } } // Read reads from the Stream. If the end of an open Stream is reached, Read // blocks until more data is written or the Stream is Closed. func (r *Reader) Read(p []byte) (n int, err error) { r.s.b.RLock() defer r.s.b.RUnlock() var m int for { m, err = r.file.Read(p[n:]) n += m if r.s.b.IsOpen() { switch { case n != 0 && err == nil: return n, err case err == io.EOF: r.s.b.Wait() case err != nil: return n, err } } else { return n, err } } } // Close closes this Reader on the Stream. This must be called when done with the // Reader or else the Stream cannot be Removed. func (r *Reader) Close() error { defer r.s.dec() return r.file.Close() } ================================================ FILE: vendor/gopkg.in/djherbis/stream.v1/stream.go ================================================ // Package stream provides a way to read and write to a synchronous buffered pipe, with multiple reader support. package stream import ( "errors" "sync" ) // ErrRemoving is returned when requesting a Reader on a Stream which is being Removed. var ErrRemoving = errors.New("cannot open a new reader while removing file") // Stream is used to concurrently Write and Read from a File. type Stream struct { grp sync.WaitGroup b *broadcaster file File fs FileSystem removing chan struct{} } // New creates a new Stream from the StdFileSystem with Name "name". func New(name string) (*Stream, error) { return NewStream(name, StdFileSystem) } // NewStream creates a new Stream with Name "name" in FileSystem fs. func NewStream(name string, fs FileSystem) (*Stream, error) { f, err := fs.Create(name) sf := &Stream{ file: f, fs: fs, b: newBroadcaster(), removing: make(chan struct{}), } sf.inc() return sf, err } // Name returns the name of the underlying File in the FileSystem. func (s *Stream) Name() string { return s.file.Name() } // Write writes p to the Stream. It's concurrent safe to be called with Stream's other methods. func (s *Stream) Write(p []byte) (int, error) { defer s.b.Broadcast() s.b.Lock() defer s.b.Unlock() return s.file.Write(p) } // Close will close the active stream. This will cause Readers to return EOF once they have // read the entire stream. func (s *Stream) Close() error { defer s.dec() defer s.b.Close() s.b.Lock() defer s.b.Unlock() return s.file.Close() } // Remove will block until the Stream and all its Readers have been Closed, // at which point it will delete the underlying file. NextReader() will return // ErrRemoving if called after Remove. func (s *Stream) Remove() error { close(s.removing) s.grp.Wait() return s.fs.Remove(s.file.Name()) } // NextReader will return a concurrent-safe Reader for this stream. Each Reader will // see a complete and independent view of the stream, and can Read will the stream // is written to. func (s *Stream) NextReader() (*Reader, error) { s.inc() select { case <-s.removing: s.dec() return nil, ErrRemoving default: } file, err := s.fs.Open(s.file.Name()) if err != nil { s.dec() return nil, err } return &Reader{file: file, s: s}, nil } func (s *Stream) inc() { s.grp.Add(1) } func (s *Stream) dec() { s.grp.Done() } ================================================ FILE: vendor/gopkg.in/djherbis/stream.v1/stream_test.go ================================================ package stream import ( "bytes" "errors" "io" "os" "testing" "time" ) var ( testdata = []byte("hello\nworld\n") errFail = errors.New("fail") ) type badFs struct { readers []File } type badFile struct{ name string } func (r badFile) Name() string { return r.name } func (r badFile) Read(p []byte) (int, error) { return 0, errFail } func (r badFile) ReadAt(p []byte, off int64) (int, error) { return 0, errFail } func (r badFile) Write(p []byte) (int, error) { return 0, errFail } func (r badFile) Close() error { return errFail } func (fs badFs) Create(name string) (File, error) { return os.Create(name) } func (fs badFs) Open(name string) (File, error) { if len(fs.readers) > 0 { f := fs.readers[len(fs.readers)-1] fs.readers = fs.readers[:len(fs.readers)-1] return f, nil } return nil, errFail } func (fs badFs) Remove(name string) error { return os.Remove(name) } func TestMemFs(t *testing.T) { fs := NewMemFS() if _, err := fs.Open("not found"); err != ErrNotFoundInMem { t.Error(err) t.FailNow() } } func TestBadFile(t *testing.T) { fs := badFs{readers: make([]File, 0, 1)} fs.readers = append(fs.readers, badFile{name: "test"}) f, err := NewStream("test", fs) if err != nil { t.Error(err) t.FailNow() } defer f.Remove() defer f.Close() r, err := f.NextReader() if err != nil { t.Error(err) t.FailNow() } defer r.Close() if r.Name() != "test" { t.Errorf("expected name to to be 'test' got %s", r.Name()) t.FailNow() } if _, err := r.ReadAt(nil, 0); err == nil { t.Error("expected ReadAt error") t.FailNow() } if _, err := r.Read(nil); err == nil { t.Error("expected Read error") t.FailNow() } } func TestBadFs(t *testing.T) { f, err := NewStream("test", badFs{}) if err != nil { t.Error(err) t.FailNow() } defer f.Remove() defer f.Close() r, err := f.NextReader() if err == nil { t.Error("expected open error") t.FailNow() } else { return } r.Close() } func TestStd(t *testing.T) { f, err := New("test.txt") if err != nil { t.Error(err) t.FailNow() } if f.Name() != "test.txt" { t.Errorf("expected name to be test.txt: %s", f.Name()) } testFile(f, t) } func TestMem(t *testing.T) { f, err := NewStream("test.txt", NewMemFS()) if err != nil { t.Error(err) t.FailNow() } f.Write(nil) testFile(f, t) } func TestRemove(t *testing.T) { f, err := NewStream("test.txt", NewMemFS()) if err != nil { t.Error(err) t.FailNow() } defer f.Close() go f.Remove() <-time.After(100 * time.Millisecond) r, err := f.NextReader() switch err { case ErrRemoving: case nil: t.Error("expected error on NextReader()") r.Close() default: t.Error("expected diff error on NextReader()", err) } } func testFile(f *Stream, t *testing.T) { for i := 0; i < 10; i++ { go testReader(f, t) } for i := 0; i < 10; i++ { f.Write(testdata) <-time.After(10 * time.Millisecond) } f.Close() testReader(f, t) f.Remove() } func testReader(f *Stream, t *testing.T) { r, err := f.NextReader() if err != nil { t.Error(err) t.FailNow() } defer r.Close() buf := bytes.NewBuffer(nil) sr := io.NewSectionReader(r, 1+int64(len(testdata)*5), 5) io.Copy(buf, sr) if !bytes.Equal(buf.Bytes(), testdata[1:6]) { t.Errorf("unequal %s", buf.Bytes()) return } buf.Reset() io.Copy(buf, r) if !bytes.Equal(buf.Bytes(), bytes.Repeat(testdata, 10)) { t.Errorf("unequal %s", buf.Bytes()) return } } ================================================ FILE: vendor/gopkg.in/djherbis/stream.v1/sync.go ================================================ package stream import ( "sync" "sync/atomic" ) type broadcaster struct { sync.RWMutex closed uint32 *sync.Cond } func newBroadcaster() *broadcaster { var b broadcaster b.Cond = sync.NewCond(b.RWMutex.RLocker()) return &b } func (b *broadcaster) Wait() { if b.IsOpen() { b.Cond.Wait() } } func (b *broadcaster) IsOpen() bool { return atomic.LoadUint32(&b.closed) == 0 } func (b *broadcaster) Close() error { atomic.StoreUint32(&b.closed, 1) b.Cond.Broadcast() return nil } ================================================ FILE: vendor/vendor.json ================================================ { "comment": "", "ignore": "", "package": [ { "checksumSHA1": "uz5IFOxRG/odXyNSLahNaQmRfTw=", "path": "github.com/rainycape/vfs", "revision": "a62fd22bcf7010946a44f6a1250a82c03110a14b", "revisionTime": "2015-06-11T13:38:00Z" }, { "checksumSHA1": "l0Y/7HWT3FyVZDag6I+nPvklh0g=", "path": "github.com/stretchr/testify/assert", "revision": "de7fcff264cd05cc0c90c509ea789a436a0dd206", "revisionTime": "2014-09-15T02:00:11Z" }, { "checksumSHA1": "AFPcO/L4YHgqiLJb1hMFvwBI59M=", "path": "github.com/stretchr/testify/require", "revision": "de7fcff264cd05cc0c90c509ea789a436a0dd206", "revisionTime": "2014-09-15T02:00:11Z" }, { "checksumSHA1": "r2P3nttwhwKuAdSecDkyU+t2d/s=", "path": "gopkg.in/djherbis/stream.v1", "revision": "26a761059928627ca84837000dfb33447c66a146", "revisionTime": "2016-02-04T06:24:40Z" } ], "rootPath": "github.com/lox/httpcache" } ================================================ FILE: wercker.yml ================================================ # https://registry.hub.docker.com/u/library/golang/ box: golang build: steps: - setup-go-workspace - script: name: go test code: | go test . ./cli/... ./httplog/...