diff --git a/hack/update-bazel.sh b/hack/update-bazel.sh index c52b03a9cf31..401406628c63 100755 --- a/hack/update-bazel.sh +++ b/hack/update-bazel.sh @@ -20,6 +20,12 @@ set -o pipefail TESTINFRA_ROOT=$(git rev-parse --show-toplevel) TMP_GOPATH=$(mktemp -d) +# no unit tests in vendor +# previously we used godeps which did this, but `dep` does not handle this +# properly yet. some of these tests don't build well. see: +# ref: https://github.com/kubernetes/test-infra/pull/5411 +find ${TESTINFRA_ROOT}/vendor/ -name "*_test.go" -delete + "${TESTINFRA_ROOT}/hack/go_install_from_commit.sh" \ github.com/kubernetes/repo-infra/kazel \ e26fc85d14a1d3dc25569831acc06919673c545a \ diff --git a/hack/verify-bazel.sh b/hack/verify-bazel.sh index 7cd2fc8a987d..f0f275dee065 100755 --- a/hack/verify-bazel.sh +++ b/hack/verify-bazel.sh @@ -45,9 +45,16 @@ kazel_diff=$("${TMP_GOPATH}/bin/kazel" \ -print-diff \ -root="${TESTINFRA_ROOT}") -if [[ -n "${gazelle_diff}" || -n "${kazel_diff}" ]]; then +# check if there are vendor/*_test.go +# previously we used godeps which did this, but `dep` does not handle this +# properly yet. some of these tests don't build well. see: +# ref: https://github.com/kubernetes/test-infra/pull/5411 +vendor_tests=$(find ${TESTINFRA_ROOT}/vendor/ -name "*_test.go" | wc -l) + +if [[ -n "${gazelle_diff}" || -n "${kazel_diff}" || "${vendor_tests}" -ne "0" ]]; then echo "${gazelle_diff}" echo "${kazel_diff}" + echo "number of vendor/*_test.go: ${vendor_tests} (want: 0)" echo echo "Run ./hack/update-bazel.sh" exit 1 diff --git a/vendor/bitbucket.org/ww/goautoneg/BUILD b/vendor/bitbucket.org/ww/goautoneg/BUILD index 8616afc6eee1..5704685c2f71 100644 --- a/vendor/bitbucket.org/ww/goautoneg/BUILD +++ b/vendor/bitbucket.org/ww/goautoneg/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -7,13 +7,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = ["autoneg_test.go"], - importpath = "bitbucket.org/ww/goautoneg", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/bitbucket.org/ww/goautoneg/autoneg_test.go b/vendor/bitbucket.org/ww/goautoneg/autoneg_test.go deleted file mode 100644 index 41d328f1d5f9..000000000000 --- a/vendor/bitbucket.org/ww/goautoneg/autoneg_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package goautoneg - -import ( - "testing" -) - -var chrome = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5" - -func TestParseAccept(t *testing.T) { - alternatives := []string{"text/html", "image/png"} - content_type := Negotiate(chrome, alternatives) - if content_type != "image/png" { - t.Errorf("got %s expected image/png", content_type) - } - - alternatives = []string{"text/html", "text/plain", "text/n3"} - content_type = Negotiate(chrome, alternatives) - if content_type != "text/html" { - t.Errorf("got %s expected text/html", content_type) - } - - alternatives = []string{"text/n3", "text/plain"} - content_type = Negotiate(chrome, alternatives) - if content_type != "text/plain" { - t.Errorf("got %s expected text/plain", content_type) - } - - alternatives = []string{"text/n3", "application/rdf+xml"} - content_type = Negotiate(chrome, alternatives) - if content_type != "text/n3" { - t.Errorf("got %s expected text/n3", content_type) - } -} diff --git a/vendor/github.com/NYTimes/gziphandler/BUILD b/vendor/github.com/NYTimes/gziphandler/BUILD index 1f5ab60b24da..7bfacf3181c2 100644 --- a/vendor/github.com/NYTimes/gziphandler/BUILD +++ b/vendor/github.com/NYTimes/gziphandler/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -7,14 +7,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = ["gzip_test.go"], - importpath = "github.com/NYTimes/gziphandler", - library = ":go_default_library", - deps = ["//vendor/github.com/stretchr/testify/assert:go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/NYTimes/gziphandler/gzip_test.go b/vendor/github.com/NYTimes/gziphandler/gzip_test.go deleted file mode 100644 index 9a62bcbaa2b9..000000000000 --- a/vendor/github.com/NYTimes/gziphandler/gzip_test.go +++ /dev/null @@ -1,134 +0,0 @@ -package gziphandler - -import ( - "bytes" - "compress/gzip" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestParseEncodings(t *testing.T) { - - examples := map[string]codings{ - - // Examples from RFC 2616 - "compress, gzip": codings{"compress": 1.0, "gzip": 1.0}, - "": codings{}, - "*": codings{"*": 1.0}, - "compress;q=0.5, gzip;q=1.0": codings{"compress": 0.5, "gzip": 1.0}, - "gzip;q=1.0, identity; q=0.5, *;q=0": codings{"gzip": 1.0, "identity": 0.5, "*": 0.0}, - - // More random stuff - "AAA;q=1": codings{"aaa": 1.0}, - "BBB ; q = 2": codings{"bbb": 1.0}, - } - - for eg, exp := range examples { - act, _ := parseEncodings(eg) - assert.Equal(t, exp, act) - } -} - -func TestGzipHandler(t *testing.T) { - testBody := "aaabbbccc" - - // This just exists to provide something for GzipHandler to wrap. - handler := newTestHandler(testBody) - - // requests without accept-encoding are passed along as-is - - req1, _ := http.NewRequest("GET", "/whatever", nil) - res1 := httptest.NewRecorder() - handler.ServeHTTP(res1, req1) - - assert.Equal(t, 200, res1.Code) - assert.Equal(t, "", res1.Header().Get("Content-Encoding")) - assert.Equal(t, "Accept-Encoding", res1.Header().Get("Vary")) - assert.Equal(t, testBody, res1.Body.String()) - - // but requests with accept-encoding:gzip are compressed if possible - - req2, _ := http.NewRequest("GET", "/whatever", nil) - req2.Header.Set("Accept-Encoding", "gzip") - res2 := httptest.NewRecorder() - handler.ServeHTTP(res2, req2) - - assert.Equal(t, 200, res2.Code) - assert.Equal(t, "gzip", res2.Header().Get("Content-Encoding")) - assert.Equal(t, "Accept-Encoding", res2.Header().Get("Vary")) - assert.Equal(t, gzipStr(testBody), res2.Body.Bytes()) - - // content-type header is correctly set based on uncompressed body - - req3, _ := http.NewRequest("GET", "/whatever", nil) - req3.Header.Set("Accept-Encoding", "gzip") - res3 := httptest.NewRecorder() - handler.ServeHTTP(res3, req3) - - assert.Equal(t, http.DetectContentType([]byte(testBody)), res3.Header().Get("Content-Type")) -} - -// -------------------------------------------------------------------- - -func BenchmarkGzipHandler_S2k(b *testing.B) { benchmark(b, false, 2048) } -func BenchmarkGzipHandler_S20k(b *testing.B) { benchmark(b, false, 20480) } -func BenchmarkGzipHandler_S100k(b *testing.B) { benchmark(b, false, 102400) } -func BenchmarkGzipHandler_P2k(b *testing.B) { benchmark(b, true, 2048) } -func BenchmarkGzipHandler_P20k(b *testing.B) { benchmark(b, true, 20480) } -func BenchmarkGzipHandler_P100k(b *testing.B) { benchmark(b, true, 102400) } - -// -------------------------------------------------------------------- - -func gzipStr(s string) []byte { - var b bytes.Buffer - w := gzip.NewWriter(&b) - io.WriteString(w, s) - w.Close() - return b.Bytes() -} - -func benchmark(b *testing.B, parallel bool, size int) { - bin, err := ioutil.ReadFile("testdata/benchmark.json") - if err != nil { - b.Fatal(err) - } - - req, _ := http.NewRequest("GET", "/whatever", nil) - req.Header.Set("Accept-Encoding", "gzip") - handler := newTestHandler(string(bin[:size])) - - if parallel { - b.ResetTimer() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - runBenchmark(b, req, handler) - } - }) - } else { - b.ResetTimer() - for i := 0; i < b.N; i++ { - runBenchmark(b, req, handler) - } - } -} - -func runBenchmark(b *testing.B, req *http.Request, handler http.Handler) { - res := httptest.NewRecorder() - handler.ServeHTTP(res, req) - if code := res.Code; code != 200 { - b.Fatalf("Expected 200 but got %d", code) - } else if blen := res.Body.Len(); blen < 500 { - b.Fatalf("Expected complete response body, but got %d bytes", blen) - } -} - -func newTestHandler(body string) http.Handler { - return GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, body) - })) -} diff --git a/vendor/github.com/beorn7/perks/quantile/BUILD b/vendor/github.com/beorn7/perks/quantile/BUILD index 975dd8d0db53..369208299860 100644 --- a/vendor/github.com/beorn7/perks/quantile/BUILD +++ b/vendor/github.com/beorn7/perks/quantile/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -7,23 +7,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = [ - "bench_test.go", - "stream_test.go", - ], - importpath = "github.com/beorn7/perks/quantile", - library = ":go_default_library", -) - -go_test( - name = "go_default_xtest", - srcs = ["example_test.go"], - importpath = "github.com/beorn7/perks/quantile_test", - deps = [":go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/beorn7/perks/quantile/bench_test.go b/vendor/github.com/beorn7/perks/quantile/bench_test.go deleted file mode 100644 index 0bd0e4e77521..000000000000 --- a/vendor/github.com/beorn7/perks/quantile/bench_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package quantile - -import ( - "testing" -) - -func BenchmarkInsertTargeted(b *testing.B) { - b.ReportAllocs() - - s := NewTargeted(Targets) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkInsertTargetedSmallEpsilon(b *testing.B) { - s := NewTargeted(TargetsSmallEpsilon) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkInsertBiased(b *testing.B) { - s := NewLowBiased(0.01) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkInsertBiasedSmallEpsilon(b *testing.B) { - s := NewLowBiased(0.0001) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkQuery(b *testing.B) { - s := NewTargeted(Targets) - for i := float64(0); i < 1e6; i++ { - s.Insert(i) - } - b.ResetTimer() - n := float64(b.N) - for i := float64(0); i < n; i++ { - s.Query(i / n) - } -} - -func BenchmarkQuerySmallEpsilon(b *testing.B) { - s := NewTargeted(TargetsSmallEpsilon) - for i := float64(0); i < 1e6; i++ { - s.Insert(i) - } - b.ResetTimer() - n := float64(b.N) - for i := float64(0); i < n; i++ { - s.Query(i / n) - } -} diff --git a/vendor/github.com/beorn7/perks/quantile/example_test.go b/vendor/github.com/beorn7/perks/quantile/example_test.go deleted file mode 100644 index ab3293aaf2a0..000000000000 --- a/vendor/github.com/beorn7/perks/quantile/example_test.go +++ /dev/null @@ -1,121 +0,0 @@ -// +build go1.1 - -package quantile_test - -import ( - "bufio" - "fmt" - "log" - "os" - "strconv" - "time" - - "github.com/beorn7/perks/quantile" -) - -func Example_simple() { - ch := make(chan float64) - go sendFloats(ch) - - // Compute the 50th, 90th, and 99th percentile. - q := quantile.NewTargeted(map[float64]float64{ - 0.50: 0.005, - 0.90: 0.001, - 0.99: 0.0001, - }) - for v := range ch { - q.Insert(v) - } - - fmt.Println("perc50:", q.Query(0.50)) - fmt.Println("perc90:", q.Query(0.90)) - fmt.Println("perc99:", q.Query(0.99)) - fmt.Println("count:", q.Count()) - // Output: - // perc50: 5 - // perc90: 16 - // perc99: 223 - // count: 2388 -} - -func Example_mergeMultipleStreams() { - // Scenario: - // We have multiple database shards. On each shard, there is a process - // collecting query response times from the database logs and inserting - // them into a Stream (created via NewTargeted(0.90)), much like the - // Simple example. These processes expose a network interface for us to - // ask them to serialize and send us the results of their - // Stream.Samples so we may Merge and Query them. - // - // NOTES: - // * These sample sets are small, allowing us to get them - // across the network much faster than sending the entire list of data - // points. - // - // * For this to work correctly, we must supply the same quantiles - // a priori the process collecting the samples supplied to NewTargeted, - // even if we do not plan to query them all here. - ch := make(chan quantile.Samples) - getDBQuerySamples(ch) - q := quantile.NewTargeted(map[float64]float64{0.90: 0.001}) - for samples := range ch { - q.Merge(samples) - } - fmt.Println("perc90:", q.Query(0.90)) -} - -func Example_window() { - // Scenario: We want the 90th, 95th, and 99th percentiles for each - // minute. - - ch := make(chan float64) - go sendStreamValues(ch) - - tick := time.NewTicker(1 * time.Minute) - q := quantile.NewTargeted(map[float64]float64{ - 0.90: 0.001, - 0.95: 0.0005, - 0.99: 0.0001, - }) - for { - select { - case t := <-tick.C: - flushToDB(t, q.Samples()) - q.Reset() - case v := <-ch: - q.Insert(v) - } - } -} - -func sendStreamValues(ch chan float64) { - // Use your imagination -} - -func flushToDB(t time.Time, samples quantile.Samples) { - // Use your imagination -} - -// This is a stub for the above example. In reality this would hit the remote -// servers via http or something like it. -func getDBQuerySamples(ch chan quantile.Samples) {} - -func sendFloats(ch chan<- float64) { - f, err := os.Open("exampledata.txt") - if err != nil { - log.Fatal(err) - } - sc := bufio.NewScanner(f) - for sc.Scan() { - b := sc.Bytes() - v, err := strconv.ParseFloat(string(b), 64) - if err != nil { - log.Fatal(err) - } - ch <- v - } - if sc.Err() != nil { - log.Fatal(sc.Err()) - } - close(ch) -} diff --git a/vendor/github.com/beorn7/perks/quantile/stream_test.go b/vendor/github.com/beorn7/perks/quantile/stream_test.go deleted file mode 100644 index 4dba05449cb4..000000000000 --- a/vendor/github.com/beorn7/perks/quantile/stream_test.go +++ /dev/null @@ -1,188 +0,0 @@ -package quantile - -import ( - "math" - "math/rand" - "sort" - "testing" -) - -var ( - Targets = map[float64]float64{ - 0.01: 0.001, - 0.10: 0.01, - 0.50: 0.05, - 0.90: 0.01, - 0.99: 0.001, - } - TargetsSmallEpsilon = map[float64]float64{ - 0.01: 0.0001, - 0.10: 0.001, - 0.50: 0.005, - 0.90: 0.001, - 0.99: 0.0001, - } - LowQuantiles = []float64{0.01, 0.1, 0.5} - HighQuantiles = []float64{0.99, 0.9, 0.5} -) - -const RelativeEpsilon = 0.01 - -func verifyPercsWithAbsoluteEpsilon(t *testing.T, a []float64, s *Stream) { - sort.Float64s(a) - for quantile, epsilon := range Targets { - n := float64(len(a)) - k := int(quantile * n) - lower := int((quantile - epsilon) * n) - if lower < 1 { - lower = 1 - } - upper := int(math.Ceil((quantile + epsilon) * n)) - if upper > len(a) { - upper = len(a) - } - w, min, max := a[k-1], a[lower-1], a[upper-1] - if g := s.Query(quantile); g < min || g > max { - t.Errorf("q=%f: want %v [%f,%f], got %v", quantile, w, min, max, g) - } - } -} - -func verifyLowPercsWithRelativeEpsilon(t *testing.T, a []float64, s *Stream) { - sort.Float64s(a) - for _, qu := range LowQuantiles { - n := float64(len(a)) - k := int(qu * n) - - lowerRank := int((1 - RelativeEpsilon) * qu * n) - upperRank := int(math.Ceil((1 + RelativeEpsilon) * qu * n)) - w, min, max := a[k-1], a[lowerRank-1], a[upperRank-1] - if g := s.Query(qu); g < min || g > max { - t.Errorf("q=%f: want %v [%f,%f], got %v", qu, w, min, max, g) - } - } -} - -func verifyHighPercsWithRelativeEpsilon(t *testing.T, a []float64, s *Stream) { - sort.Float64s(a) - for _, qu := range HighQuantiles { - n := float64(len(a)) - k := int(qu * n) - - lowerRank := int((1 - (1+RelativeEpsilon)*(1-qu)) * n) - upperRank := int(math.Ceil((1 - (1-RelativeEpsilon)*(1-qu)) * n)) - w, min, max := a[k-1], a[lowerRank-1], a[upperRank-1] - if g := s.Query(qu); g < min || g > max { - t.Errorf("q=%f: want %v [%f,%f], got %v", qu, w, min, max, g) - } - } -} - -func populateStream(s *Stream) []float64 { - a := make([]float64, 0, 1e5+100) - for i := 0; i < cap(a); i++ { - v := rand.NormFloat64() - // Add 5% asymmetric outliers. - if i%20 == 0 { - v = v*v + 1 - } - s.Insert(v) - a = append(a, v) - } - return a -} - -func TestTargetedQuery(t *testing.T) { - rand.Seed(42) - s := NewTargeted(Targets) - a := populateStream(s) - verifyPercsWithAbsoluteEpsilon(t, a, s) -} - -func TestLowBiasedQuery(t *testing.T) { - rand.Seed(42) - s := NewLowBiased(RelativeEpsilon) - a := populateStream(s) - verifyLowPercsWithRelativeEpsilon(t, a, s) -} - -func TestHighBiasedQuery(t *testing.T) { - rand.Seed(42) - s := NewHighBiased(RelativeEpsilon) - a := populateStream(s) - verifyHighPercsWithRelativeEpsilon(t, a, s) -} - -// BrokenTestTargetedMerge is broken, see Merge doc comment. -func BrokenTestTargetedMerge(t *testing.T) { - rand.Seed(42) - s1 := NewTargeted(Targets) - s2 := NewTargeted(Targets) - a := populateStream(s1) - a = append(a, populateStream(s2)...) - s1.Merge(s2.Samples()) - verifyPercsWithAbsoluteEpsilon(t, a, s1) -} - -// BrokenTestLowBiasedMerge is broken, see Merge doc comment. -func BrokenTestLowBiasedMerge(t *testing.T) { - rand.Seed(42) - s1 := NewLowBiased(RelativeEpsilon) - s2 := NewLowBiased(RelativeEpsilon) - a := populateStream(s1) - a = append(a, populateStream(s2)...) - s1.Merge(s2.Samples()) - verifyLowPercsWithRelativeEpsilon(t, a, s2) -} - -// BrokenTestHighBiasedMerge is broken, see Merge doc comment. -func BrokenTestHighBiasedMerge(t *testing.T) { - rand.Seed(42) - s1 := NewHighBiased(RelativeEpsilon) - s2 := NewHighBiased(RelativeEpsilon) - a := populateStream(s1) - a = append(a, populateStream(s2)...) - s1.Merge(s2.Samples()) - verifyHighPercsWithRelativeEpsilon(t, a, s2) -} - -func TestUncompressed(t *testing.T) { - q := NewTargeted(Targets) - for i := 100; i > 0; i-- { - q.Insert(float64(i)) - } - if g := q.Count(); g != 100 { - t.Errorf("want count 100, got %d", g) - } - // Before compression, Query should have 100% accuracy. - for quantile := range Targets { - w := quantile * 100 - if g := q.Query(quantile); g != w { - t.Errorf("want %f, got %f", w, g) - } - } -} - -func TestUncompressedSamples(t *testing.T) { - q := NewTargeted(map[float64]float64{0.99: 0.001}) - for i := 1; i <= 100; i++ { - q.Insert(float64(i)) - } - if g := q.Samples().Len(); g != 100 { - t.Errorf("want count 100, got %d", g) - } -} - -func TestUncompressedOne(t *testing.T) { - q := NewTargeted(map[float64]float64{0.99: 0.01}) - q.Insert(3.14) - if g := q.Query(0.90); g != 3.14 { - t.Error("want PI, got", g) - } -} - -func TestDefaults(t *testing.T) { - if g := NewTargeted(map[float64]float64{0.99: 0.001}).Query(0.99); g != 0 { - t.Errorf("want 0, got %f", g) - } -} diff --git a/vendor/github.com/bwmarrin/snowflake/BUILD b/vendor/github.com/bwmarrin/snowflake/BUILD index 6d63ff571708..31e0022205e5 100644 --- a/vendor/github.com/bwmarrin/snowflake/BUILD +++ b/vendor/github.com/bwmarrin/snowflake/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -7,13 +7,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = ["snowflake_test.go"], - importpath = "github.com/bwmarrin/snowflake", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/bwmarrin/snowflake/snowflake_test.go b/vendor/github.com/bwmarrin/snowflake/snowflake_test.go deleted file mode 100644 index f2ba51df8ca9..000000000000 --- a/vendor/github.com/bwmarrin/snowflake/snowflake_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package snowflake - -import ( - "bytes" - "testing" -) - -func TestMarshalJSON(t *testing.T) { - id := ID(13587) - expected := "\"13587\"" - - bytes, err := id.MarshalJSON() - if err != nil { - t.Error("Unexpected error during MarshalJSON") - } - - if string(bytes) != expected { - t.Errorf("Got %s, expected %s", string(bytes), expected) - } -} - -func TestMarshalsIntBytes(t *testing.T) { - id := ID(13587).IntBytes() - expected := []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x35, 0x13} - if !bytes.Equal(id[:], expected) { - t.Errorf("Expected ID to be encoded as %v, got %v", expected, id) - } -} - -func TestUnmarshalJSON(t *testing.T) { - strID := "\"13587\"" - expected := ID(13587) - - var id ID - err := id.UnmarshalJSON([]byte(strID)) - if err != nil { - t.Error("Unexpected error during UnmarshalJSON") - } - - if id != expected { - t.Errorf("Got %d, expected %d", id, expected) - } -} - -func TestBase58(t *testing.T) { - - node, _ := NewNode(1) - - for i := 0; i < 10; i++ { - - sf := node.Generate() - b58 := sf.Base58() - psf, err := ParseBase58([]byte(b58)) - if err != nil { - t.Fatal(err) - } - if sf != psf { - t.Fatal("Parsed does not match String.") - } - } -} -func BenchmarkParseBase58(b *testing.B) { - - node, _ := NewNode(1) - sf := node.Generate() - b58 := sf.Base58() - - b.ReportAllocs() - - b.ResetTimer() - for n := 0; n < b.N; n++ { - ParseBase58([]byte(b58)) - } -} -func BenchmarkBase58(b *testing.B) { - - node, _ := NewNode(1) - sf := node.Generate() - - b.ReportAllocs() - - b.ResetTimer() - for n := 0; n < b.N; n++ { - sf.Base58() - } -} -func BenchmarkGenerate(b *testing.B) { - - node, _ := NewNode(1) - - b.ReportAllocs() - - b.ResetTimer() - for n := 0; n < b.N; n++ { - _ = node.Generate() - } -} - -func BenchmarkUnmarshal(b *testing.B) { - // Generate the ID to unmarshal - node, _ := NewNode(1) - id := node.Generate() - bytes, _ := id.MarshalJSON() - - var id2 ID - - b.ReportAllocs() - b.ResetTimer() - for n := 0; n < b.N; n++ { - _ = id2.UnmarshalJSON(bytes) - } -} - -func BenchmarkMarshal(b *testing.B) { - // Generate the ID to marshal - node, _ := NewNode(1) - id := node.Generate() - - b.ReportAllocs() - b.ResetTimer() - for n := 0; n < b.N; n++ { - _, _ = id.MarshalJSON() - } -} diff --git a/vendor/github.com/ghodss/yaml/BUILD b/vendor/github.com/ghodss/yaml/BUILD index b3f2ebaa8789..1599a67fff37 100644 --- a/vendor/github.com/ghodss/yaml/BUILD +++ b/vendor/github.com/ghodss/yaml/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -11,13 +11,6 @@ go_library( deps = ["//vendor/gopkg.in/yaml.v2:go_default_library"], ) -go_test( - name = "go_default_test", - srcs = ["yaml_test.go"], - importpath = "github.com/ghodss/yaml", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/ghodss/yaml/yaml_test.go b/vendor/github.com/ghodss/yaml/yaml_test.go deleted file mode 100644 index 0ae0954e9013..000000000000 --- a/vendor/github.com/ghodss/yaml/yaml_test.go +++ /dev/null @@ -1,271 +0,0 @@ -package yaml - -import ( - "fmt" - "math" - "reflect" - "strconv" - "testing" -) - -type MarshalTest struct { - A string - B int64 - // Would like to test float64, but it's not supported in go-yaml. - // (See https://github.com/go-yaml/yaml/issues/83.) - C float32 -} - -func TestMarshal(t *testing.T) { - f32String := strconv.FormatFloat(math.MaxFloat32, 'g', -1, 32) - s := MarshalTest{"a", math.MaxInt64, math.MaxFloat32} - e := []byte(fmt.Sprintf("A: a\nB: %d\nC: %s\n", math.MaxInt64, f32String)) - - y, err := Marshal(s) - if err != nil { - t.Errorf("error marshaling YAML: %v", err) - } - - if !reflect.DeepEqual(y, e) { - t.Errorf("marshal YAML was unsuccessful, expected: %#v, got: %#v", - string(e), string(y)) - } -} - -type UnmarshalString struct { - A string - True string -} - -type UnmarshalStringMap struct { - A map[string]string -} - -type UnmarshalNestedString struct { - A NestedString -} - -type NestedString struct { - A string -} - -type UnmarshalSlice struct { - A []NestedSlice -} - -type NestedSlice struct { - B string - C *string -} - -func TestUnmarshal(t *testing.T) { - y := []byte("a: 1") - s1 := UnmarshalString{} - e1 := UnmarshalString{A: "1"} - unmarshal(t, y, &s1, &e1) - - y = []byte("a: true") - s1 = UnmarshalString{} - e1 = UnmarshalString{A: "true"} - unmarshal(t, y, &s1, &e1) - - y = []byte("true: 1") - s1 = UnmarshalString{} - e1 = UnmarshalString{True: "1"} - unmarshal(t, y, &s1, &e1) - - y = []byte("a:\n a: 1") - s2 := UnmarshalNestedString{} - e2 := UnmarshalNestedString{NestedString{"1"}} - unmarshal(t, y, &s2, &e2) - - y = []byte("a:\n - b: abc\n c: def\n - b: 123\n c: 456\n") - s3 := UnmarshalSlice{} - e3 := UnmarshalSlice{[]NestedSlice{NestedSlice{"abc", strPtr("def")}, NestedSlice{"123", strPtr("456")}}} - unmarshal(t, y, &s3, &e3) - - y = []byte("a:\n b: 1") - s4 := UnmarshalStringMap{} - e4 := UnmarshalStringMap{map[string]string{"b": "1"}} - unmarshal(t, y, &s4, &e4) -} - -func unmarshal(t *testing.T, y []byte, s, e interface{}) { - err := Unmarshal(y, s) - if err != nil { - t.Errorf("error unmarshaling YAML: %v", err) - } - - if !reflect.DeepEqual(s, e) { - t.Errorf("unmarshal YAML was unsuccessful, expected: %+#v, got: %+#v", - e, s) - } -} - -type Case struct { - input string - output string - // By default we test that reversing the output == input. But if there is a - // difference in the reversed output, you can optionally specify it here. - reverse *string -} - -type RunType int - -const ( - RunTypeJSONToYAML RunType = iota - RunTypeYAMLToJSON -) - -func TestJSONToYAML(t *testing.T) { - cases := []Case{ - { - `{"t":"a"}`, - "t: a\n", - nil, - }, { - `{"t":null}`, - "t: null\n", - nil, - }, - } - - runCases(t, RunTypeJSONToYAML, cases) -} - -func TestYAMLToJSON(t *testing.T) { - cases := []Case{ - { - "t: a\n", - `{"t":"a"}`, - nil, - }, { - "t: \n", - `{"t":null}`, - strPtr("t: null\n"), - }, { - "t: null\n", - `{"t":null}`, - nil, - }, { - "1: a\n", - `{"1":"a"}`, - strPtr("\"1\": a\n"), - }, { - "1000000000000000000000000000000000000: a\n", - `{"1e+36":"a"}`, - strPtr("\"1e+36\": a\n"), - }, { - "1e+36: a\n", - `{"1e+36":"a"}`, - strPtr("\"1e+36\": a\n"), - }, { - "\"1e+36\": a\n", - `{"1e+36":"a"}`, - nil, - }, { - "\"1.2\": a\n", - `{"1.2":"a"}`, - nil, - }, { - "- t: a\n", - `[{"t":"a"}]`, - nil, - }, { - "- t: a\n" + - "- t:\n" + - " b: 1\n" + - " c: 2\n", - `[{"t":"a"},{"t":{"b":1,"c":2}}]`, - nil, - }, { - `[{t: a}, {t: {b: 1, c: 2}}]`, - `[{"t":"a"},{"t":{"b":1,"c":2}}]`, - strPtr("- t: a\n" + - "- t:\n" + - " b: 1\n" + - " c: 2\n"), - }, { - "- t: \n", - `[{"t":null}]`, - strPtr("- t: null\n"), - }, { - "- t: null\n", - `[{"t":null}]`, - nil, - }, - } - - // Cases that should produce errors. - _ = []Case{ - { - "~: a", - `{"null":"a"}`, - nil, - }, { - "a: !!binary gIGC\n", - "{\"a\":\"\x80\x81\x82\"}", - nil, - }, - } - - runCases(t, RunTypeYAMLToJSON, cases) -} - -func runCases(t *testing.T, runType RunType, cases []Case) { - var f func([]byte) ([]byte, error) - var invF func([]byte) ([]byte, error) - var msg string - var invMsg string - if runType == RunTypeJSONToYAML { - f = JSONToYAML - invF = YAMLToJSON - msg = "JSON to YAML" - invMsg = "YAML back to JSON" - } else { - f = YAMLToJSON - invF = JSONToYAML - msg = "YAML to JSON" - invMsg = "JSON back to YAML" - } - - for _, c := range cases { - // Convert the string. - t.Logf("converting %s\n", c.input) - output, err := f([]byte(c.input)) - if err != nil { - t.Errorf("Failed to convert %s, input: `%s`, err: %v", msg, c.input, err) - } - - // Check it against the expected output. - if string(output) != c.output { - t.Errorf("Failed to convert %s, input: `%s`, expected `%s`, got `%s`", - msg, c.input, c.output, string(output)) - } - - // Set the string that we will compare the reversed output to. - reverse := c.input - // If a special reverse string was specified, use that instead. - if c.reverse != nil { - reverse = *c.reverse - } - - // Reverse the output. - input, err := invF(output) - if err != nil { - t.Errorf("Failed to convert %s, input: `%s`, err: %v", invMsg, string(output), err) - } - - // Check the reverse is equal to the input (or to *c.reverse). - if string(input) != reverse { - t.Errorf("Failed to convert %s, input: `%s`, expected `%s`, got `%s`", - invMsg, string(output), reverse, string(input)) - } - } - -} - -// To be able to easily fill in the *Case.reverse string above. -func strPtr(s string) *string { - return &s -} diff --git a/vendor/github.com/go-sql-driver/mysql/BUILD b/vendor/github.com/go-sql-driver/mysql/BUILD index e5999086ca6c..e9e2878822f5 100644 --- a/vendor/github.com/go-sql-driver/mysql/BUILD +++ b/vendor/github.com/go-sql-driver/mysql/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -22,19 +22,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = [ - "benchmark_test.go", - "driver_test.go", - "dsn_test.go", - "errors_test.go", - "utils_test.go", - ], - importpath = "github.com/go-sql-driver/mysql", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/go-sql-driver/mysql/benchmark_test.go b/vendor/github.com/go-sql-driver/mysql/benchmark_test.go deleted file mode 100644 index 8f721139b994..000000000000 --- a/vendor/github.com/go-sql-driver/mysql/benchmark_test.go +++ /dev/null @@ -1,246 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -import ( - "bytes" - "database/sql" - "database/sql/driver" - "math" - "strings" - "sync" - "sync/atomic" - "testing" - "time" -) - -type TB testing.B - -func (tb *TB) check(err error) { - if err != nil { - tb.Fatal(err) - } -} - -func (tb *TB) checkDB(db *sql.DB, err error) *sql.DB { - tb.check(err) - return db -} - -func (tb *TB) checkRows(rows *sql.Rows, err error) *sql.Rows { - tb.check(err) - return rows -} - -func (tb *TB) checkStmt(stmt *sql.Stmt, err error) *sql.Stmt { - tb.check(err) - return stmt -} - -func initDB(b *testing.B, queries ...string) *sql.DB { - tb := (*TB)(b) - db := tb.checkDB(sql.Open("mysql", dsn)) - for _, query := range queries { - if _, err := db.Exec(query); err != nil { - if w, ok := err.(MySQLWarnings); ok { - b.Logf("warning on %q: %v", query, w) - } else { - b.Fatalf("error on %q: %v", query, err) - } - } - } - return db -} - -const concurrencyLevel = 10 - -func BenchmarkQuery(b *testing.B) { - tb := (*TB)(b) - b.StopTimer() - b.ReportAllocs() - db := initDB(b, - "DROP TABLE IF EXISTS foo", - "CREATE TABLE foo (id INT PRIMARY KEY, val CHAR(50))", - `INSERT INTO foo VALUES (1, "one")`, - `INSERT INTO foo VALUES (2, "two")`, - ) - db.SetMaxIdleConns(concurrencyLevel) - defer db.Close() - - stmt := tb.checkStmt(db.Prepare("SELECT val FROM foo WHERE id=?")) - defer stmt.Close() - - remain := int64(b.N) - var wg sync.WaitGroup - wg.Add(concurrencyLevel) - defer wg.Wait() - b.StartTimer() - - for i := 0; i < concurrencyLevel; i++ { - go func() { - for { - if atomic.AddInt64(&remain, -1) < 0 { - wg.Done() - return - } - - var got string - tb.check(stmt.QueryRow(1).Scan(&got)) - if got != "one" { - b.Errorf("query = %q; want one", got) - wg.Done() - return - } - } - }() - } -} - -func BenchmarkExec(b *testing.B) { - tb := (*TB)(b) - b.StopTimer() - b.ReportAllocs() - db := tb.checkDB(sql.Open("mysql", dsn)) - db.SetMaxIdleConns(concurrencyLevel) - defer db.Close() - - stmt := tb.checkStmt(db.Prepare("DO 1")) - defer stmt.Close() - - remain := int64(b.N) - var wg sync.WaitGroup - wg.Add(concurrencyLevel) - defer wg.Wait() - b.StartTimer() - - for i := 0; i < concurrencyLevel; i++ { - go func() { - for { - if atomic.AddInt64(&remain, -1) < 0 { - wg.Done() - return - } - - if _, err := stmt.Exec(); err != nil { - b.Fatal(err.Error()) - } - } - }() - } -} - -// data, but no db writes -var roundtripSample []byte - -func initRoundtripBenchmarks() ([]byte, int, int) { - if roundtripSample == nil { - roundtripSample = []byte(strings.Repeat("0123456789abcdef", 1024*1024)) - } - return roundtripSample, 16, len(roundtripSample) -} - -func BenchmarkRoundtripTxt(b *testing.B) { - b.StopTimer() - sample, min, max := initRoundtripBenchmarks() - sampleString := string(sample) - b.ReportAllocs() - tb := (*TB)(b) - db := tb.checkDB(sql.Open("mysql", dsn)) - defer db.Close() - b.StartTimer() - var result string - for i := 0; i < b.N; i++ { - length := min + i - if length > max { - length = max - } - test := sampleString[0:length] - rows := tb.checkRows(db.Query(`SELECT "` + test + `"`)) - if !rows.Next() { - rows.Close() - b.Fatalf("crashed") - } - err := rows.Scan(&result) - if err != nil { - rows.Close() - b.Fatalf("crashed") - } - if result != test { - rows.Close() - b.Errorf("mismatch") - } - rows.Close() - } -} - -func BenchmarkRoundtripBin(b *testing.B) { - b.StopTimer() - sample, min, max := initRoundtripBenchmarks() - b.ReportAllocs() - tb := (*TB)(b) - db := tb.checkDB(sql.Open("mysql", dsn)) - defer db.Close() - stmt := tb.checkStmt(db.Prepare("SELECT ?")) - defer stmt.Close() - b.StartTimer() - var result sql.RawBytes - for i := 0; i < b.N; i++ { - length := min + i - if length > max { - length = max - } - test := sample[0:length] - rows := tb.checkRows(stmt.Query(test)) - if !rows.Next() { - rows.Close() - b.Fatalf("crashed") - } - err := rows.Scan(&result) - if err != nil { - rows.Close() - b.Fatalf("crashed") - } - if !bytes.Equal(result, test) { - rows.Close() - b.Errorf("mismatch") - } - rows.Close() - } -} - -func BenchmarkInterpolation(b *testing.B) { - mc := &mysqlConn{ - cfg: &Config{ - InterpolateParams: true, - Loc: time.UTC, - }, - maxPacketAllowed: maxPacketSize, - maxWriteSize: maxPacketSize - 1, - buf: newBuffer(nil), - } - - args := []driver.Value{ - int64(42424242), - float64(math.Pi), - false, - time.Unix(1423411542, 807015000), - []byte("bytes containing special chars ' \" \a \x00"), - "string containing special chars ' \" \a \x00", - } - q := "SELECT ?, ?, ?, ?, ?, ?" - - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, err := mc.interpolateParams(q, args) - if err != nil { - b.Fatal(err) - } - } -} diff --git a/vendor/github.com/go-sql-driver/mysql/driver_test.go b/vendor/github.com/go-sql-driver/mysql/driver_test.go deleted file mode 100644 index efbc4925c618..000000000000 --- a/vendor/github.com/go-sql-driver/mysql/driver_test.go +++ /dev/null @@ -1,1857 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -import ( - "bytes" - "crypto/tls" - "database/sql" - "database/sql/driver" - "fmt" - "io" - "io/ioutil" - "log" - "net" - "net/url" - "os" - "strings" - "sync" - "sync/atomic" - "testing" - "time" -) - -var ( - user string - pass string - prot string - addr string - dbname string - dsn string - netAddr string - available bool -) - -var ( - tDate = time.Date(2012, 6, 14, 0, 0, 0, 0, time.UTC) - sDate = "2012-06-14" - tDateTime = time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC) - sDateTime = "2011-11-20 21:27:37" - tDate0 = time.Time{} - sDate0 = "0000-00-00" - sDateTime0 = "0000-00-00 00:00:00" -) - -// See https://github.com/go-sql-driver/mysql/wiki/Testing -func init() { - // get environment variables - env := func(key, defaultValue string) string { - if value := os.Getenv(key); value != "" { - return value - } - return defaultValue - } - user = env("MYSQL_TEST_USER", "root") - pass = env("MYSQL_TEST_PASS", "") - prot = env("MYSQL_TEST_PROT", "tcp") - addr = env("MYSQL_TEST_ADDR", "localhost:3306") - dbname = env("MYSQL_TEST_DBNAME", "gotest") - netAddr = fmt.Sprintf("%s(%s)", prot, addr) - dsn = fmt.Sprintf("%s:%s@%s/%s?timeout=30s&strict=true", user, pass, netAddr, dbname) - c, err := net.Dial(prot, addr) - if err == nil { - available = true - c.Close() - } -} - -type DBTest struct { - *testing.T - db *sql.DB -} - -func runTestsWithMultiStatement(t *testing.T, dsn string, tests ...func(dbt *DBTest)) { - if !available { - t.Skipf("MySQL server not running on %s", netAddr) - } - - dsn += "&multiStatements=true" - var db *sql.DB - if _, err := ParseDSN(dsn); err != errInvalidDSNUnsafeCollation { - db, err = sql.Open("mysql", dsn) - if err != nil { - t.Fatalf("error connecting: %s", err.Error()) - } - defer db.Close() - } - - dbt := &DBTest{t, db} - for _, test := range tests { - test(dbt) - dbt.db.Exec("DROP TABLE IF EXISTS test") - } -} - -func runTests(t *testing.T, dsn string, tests ...func(dbt *DBTest)) { - if !available { - t.Skipf("MySQL server not running on %s", netAddr) - } - - db, err := sql.Open("mysql", dsn) - if err != nil { - t.Fatalf("error connecting: %s", err.Error()) - } - defer db.Close() - - db.Exec("DROP TABLE IF EXISTS test") - - dsn2 := dsn + "&interpolateParams=true" - var db2 *sql.DB - if _, err := ParseDSN(dsn2); err != errInvalidDSNUnsafeCollation { - db2, err = sql.Open("mysql", dsn2) - if err != nil { - t.Fatalf("error connecting: %s", err.Error()) - } - defer db2.Close() - } - - dsn3 := dsn + "&multiStatements=true" - var db3 *sql.DB - if _, err := ParseDSN(dsn3); err != errInvalidDSNUnsafeCollation { - db3, err = sql.Open("mysql", dsn3) - if err != nil { - t.Fatalf("error connecting: %s", err.Error()) - } - defer db3.Close() - } - - dbt := &DBTest{t, db} - dbt2 := &DBTest{t, db2} - dbt3 := &DBTest{t, db3} - for _, test := range tests { - test(dbt) - dbt.db.Exec("DROP TABLE IF EXISTS test") - if db2 != nil { - test(dbt2) - dbt2.db.Exec("DROP TABLE IF EXISTS test") - } - if db3 != nil { - test(dbt3) - dbt3.db.Exec("DROP TABLE IF EXISTS test") - } - } -} - -func (dbt *DBTest) fail(method, query string, err error) { - if len(query) > 300 { - query = "[query too large to print]" - } - dbt.Fatalf("error on %s %s: %s", method, query, err.Error()) -} - -func (dbt *DBTest) mustExec(query string, args ...interface{}) (res sql.Result) { - res, err := dbt.db.Exec(query, args...) - if err != nil { - dbt.fail("exec", query, err) - } - return res -} - -func (dbt *DBTest) mustQuery(query string, args ...interface{}) (rows *sql.Rows) { - rows, err := dbt.db.Query(query, args...) - if err != nil { - dbt.fail("query", query, err) - } - return rows -} - -func TestEmptyQuery(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - // just a comment, no query - rows := dbt.mustQuery("--") - // will hang before #255 - if rows.Next() { - dbt.Errorf("next on rows must be false") - } - }) -} - -func TestCRUD(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - // Create Table - dbt.mustExec("CREATE TABLE test (value BOOL)") - - // Test for unexpected data - var out bool - rows := dbt.mustQuery("SELECT * FROM test") - if rows.Next() { - dbt.Error("unexpected data in empty table") - } - - // Create Data - res := dbt.mustExec("INSERT INTO test VALUES (1)") - count, err := res.RowsAffected() - if err != nil { - dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error()) - } - if count != 1 { - dbt.Fatalf("expected 1 affected row, got %d", count) - } - - id, err := res.LastInsertId() - if err != nil { - dbt.Fatalf("res.LastInsertId() returned error: %s", err.Error()) - } - if id != 0 { - dbt.Fatalf("expected InsertId 0, got %d", id) - } - - // Read - rows = dbt.mustQuery("SELECT value FROM test") - if rows.Next() { - rows.Scan(&out) - if true != out { - dbt.Errorf("true != %t", out) - } - - if rows.Next() { - dbt.Error("unexpected data") - } - } else { - dbt.Error("no data") - } - - // Update - res = dbt.mustExec("UPDATE test SET value = ? WHERE value = ?", false, true) - count, err = res.RowsAffected() - if err != nil { - dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error()) - } - if count != 1 { - dbt.Fatalf("expected 1 affected row, got %d", count) - } - - // Check Update - rows = dbt.mustQuery("SELECT value FROM test") - if rows.Next() { - rows.Scan(&out) - if false != out { - dbt.Errorf("false != %t", out) - } - - if rows.Next() { - dbt.Error("unexpected data") - } - } else { - dbt.Error("no data") - } - - // Delete - res = dbt.mustExec("DELETE FROM test WHERE value = ?", false) - count, err = res.RowsAffected() - if err != nil { - dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error()) - } - if count != 1 { - dbt.Fatalf("expected 1 affected row, got %d", count) - } - - // Check for unexpected rows - res = dbt.mustExec("DELETE FROM test") - count, err = res.RowsAffected() - if err != nil { - dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error()) - } - if count != 0 { - dbt.Fatalf("expected 0 affected row, got %d", count) - } - }) -} - -func TestMultiQuery(t *testing.T) { - runTestsWithMultiStatement(t, dsn, func(dbt *DBTest) { - // Create Table - dbt.mustExec("CREATE TABLE `test` (`id` int(11) NOT NULL, `value` int(11) NOT NULL) ") - - // Create Data - res := dbt.mustExec("INSERT INTO test VALUES (1, 1)") - count, err := res.RowsAffected() - if err != nil { - dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error()) - } - if count != 1 { - dbt.Fatalf("expected 1 affected row, got %d", count) - } - - // Update - res = dbt.mustExec("UPDATE test SET value = 3 WHERE id = 1; UPDATE test SET value = 4 WHERE id = 1; UPDATE test SET value = 5 WHERE id = 1;") - count, err = res.RowsAffected() - if err != nil { - dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error()) - } - if count != 1 { - dbt.Fatalf("expected 1 affected row, got %d", count) - } - - // Read - var out int - rows := dbt.mustQuery("SELECT value FROM test WHERE id=1;") - if rows.Next() { - rows.Scan(&out) - if 5 != out { - dbt.Errorf("5 != %d", out) - } - - if rows.Next() { - dbt.Error("unexpected data") - } - } else { - dbt.Error("no data") - } - - }) -} - -func TestInt(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - types := [5]string{"TINYINT", "SMALLINT", "MEDIUMINT", "INT", "BIGINT"} - in := int64(42) - var out int64 - var rows *sql.Rows - - // SIGNED - for _, v := range types { - dbt.mustExec("CREATE TABLE test (value " + v + ")") - - dbt.mustExec("INSERT INTO test VALUES (?)", in) - - rows = dbt.mustQuery("SELECT value FROM test") - if rows.Next() { - rows.Scan(&out) - if in != out { - dbt.Errorf("%s: %d != %d", v, in, out) - } - } else { - dbt.Errorf("%s: no data", v) - } - - dbt.mustExec("DROP TABLE IF EXISTS test") - } - - // UNSIGNED ZEROFILL - for _, v := range types { - dbt.mustExec("CREATE TABLE test (value " + v + " ZEROFILL)") - - dbt.mustExec("INSERT INTO test VALUES (?)", in) - - rows = dbt.mustQuery("SELECT value FROM test") - if rows.Next() { - rows.Scan(&out) - if in != out { - dbt.Errorf("%s ZEROFILL: %d != %d", v, in, out) - } - } else { - dbt.Errorf("%s ZEROFILL: no data", v) - } - - dbt.mustExec("DROP TABLE IF EXISTS test") - } - }) -} - -func TestFloat32(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - types := [2]string{"FLOAT", "DOUBLE"} - in := float32(42.23) - var out float32 - var rows *sql.Rows - for _, v := range types { - dbt.mustExec("CREATE TABLE test (value " + v + ")") - dbt.mustExec("INSERT INTO test VALUES (?)", in) - rows = dbt.mustQuery("SELECT value FROM test") - if rows.Next() { - rows.Scan(&out) - if in != out { - dbt.Errorf("%s: %g != %g", v, in, out) - } - } else { - dbt.Errorf("%s: no data", v) - } - dbt.mustExec("DROP TABLE IF EXISTS test") - } - }) -} - -func TestFloat64(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - types := [2]string{"FLOAT", "DOUBLE"} - var expected float64 = 42.23 - var out float64 - var rows *sql.Rows - for _, v := range types { - dbt.mustExec("CREATE TABLE test (value " + v + ")") - dbt.mustExec("INSERT INTO test VALUES (42.23)") - rows = dbt.mustQuery("SELECT value FROM test") - if rows.Next() { - rows.Scan(&out) - if expected != out { - dbt.Errorf("%s: %g != %g", v, expected, out) - } - } else { - dbt.Errorf("%s: no data", v) - } - dbt.mustExec("DROP TABLE IF EXISTS test") - } - }) -} - -func TestFloat64Placeholder(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - types := [2]string{"FLOAT", "DOUBLE"} - var expected float64 = 42.23 - var out float64 - var rows *sql.Rows - for _, v := range types { - dbt.mustExec("CREATE TABLE test (id int, value " + v + ")") - dbt.mustExec("INSERT INTO test VALUES (1, 42.23)") - rows = dbt.mustQuery("SELECT value FROM test WHERE id = ?", 1) - if rows.Next() { - rows.Scan(&out) - if expected != out { - dbt.Errorf("%s: %g != %g", v, expected, out) - } - } else { - dbt.Errorf("%s: no data", v) - } - dbt.mustExec("DROP TABLE IF EXISTS test") - } - }) -} - -func TestString(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - types := [6]string{"CHAR(255)", "VARCHAR(255)", "TINYTEXT", "TEXT", "MEDIUMTEXT", "LONGTEXT"} - in := "κόσμε üöäßñóùéàâÿœ'îë Árvíztűrő いろはにほへとちりぬるを イロハニホヘト דג סקרן чащах น่าฟังเอย" - var out string - var rows *sql.Rows - - for _, v := range types { - dbt.mustExec("CREATE TABLE test (value " + v + ") CHARACTER SET utf8") - - dbt.mustExec("INSERT INTO test VALUES (?)", in) - - rows = dbt.mustQuery("SELECT value FROM test") - if rows.Next() { - rows.Scan(&out) - if in != out { - dbt.Errorf("%s: %s != %s", v, in, out) - } - } else { - dbt.Errorf("%s: no data", v) - } - - dbt.mustExec("DROP TABLE IF EXISTS test") - } - - // BLOB - dbt.mustExec("CREATE TABLE test (id int, value BLOB) CHARACTER SET utf8") - - id := 2 - in = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, " + - "sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, " + - "sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. " + - "Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. " + - "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, " + - "sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, " + - "sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. " + - "Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet." - dbt.mustExec("INSERT INTO test VALUES (?, ?)", id, in) - - err := dbt.db.QueryRow("SELECT value FROM test WHERE id = ?", id).Scan(&out) - if err != nil { - dbt.Fatalf("Error on BLOB-Query: %s", err.Error()) - } else if out != in { - dbt.Errorf("BLOB: %s != %s", in, out) - } - }) -} - -type timeTests struct { - dbtype string - tlayout string - tests []timeTest -} - -type timeTest struct { - s string // leading "!": do not use t as value in queries - t time.Time -} - -type timeMode byte - -func (t timeMode) String() string { - switch t { - case binaryString: - return "binary:string" - case binaryTime: - return "binary:time.Time" - case textString: - return "text:string" - } - panic("unsupported timeMode") -} - -func (t timeMode) Binary() bool { - switch t { - case binaryString, binaryTime: - return true - } - return false -} - -const ( - binaryString timeMode = iota - binaryTime - textString -) - -func (t timeTest) genQuery(dbtype string, mode timeMode) string { - var inner string - if mode.Binary() { - inner = "?" - } else { - inner = `"%s"` - } - return `SELECT cast(` + inner + ` as ` + dbtype + `)` -} - -func (t timeTest) run(dbt *DBTest, dbtype, tlayout string, mode timeMode) { - var rows *sql.Rows - query := t.genQuery(dbtype, mode) - switch mode { - case binaryString: - rows = dbt.mustQuery(query, t.s) - case binaryTime: - rows = dbt.mustQuery(query, t.t) - case textString: - query = fmt.Sprintf(query, t.s) - rows = dbt.mustQuery(query) - default: - panic("unsupported mode") - } - defer rows.Close() - var err error - if !rows.Next() { - err = rows.Err() - if err == nil { - err = fmt.Errorf("no data") - } - dbt.Errorf("%s [%s]: %s", dbtype, mode, err) - return - } - var dst interface{} - err = rows.Scan(&dst) - if err != nil { - dbt.Errorf("%s [%s]: %s", dbtype, mode, err) - return - } - switch val := dst.(type) { - case []uint8: - str := string(val) - if str == t.s { - return - } - if mode.Binary() && dbtype == "DATETIME" && len(str) == 26 && str[:19] == t.s { - // a fix mainly for TravisCI: - // accept full microsecond resolution in result for DATETIME columns - // where the binary protocol was used - return - } - dbt.Errorf("%s [%s] to string: expected %q, got %q", - dbtype, mode, - t.s, str, - ) - case time.Time: - if val == t.t { - return - } - dbt.Errorf("%s [%s] to string: expected %q, got %q", - dbtype, mode, - t.s, val.Format(tlayout), - ) - default: - fmt.Printf("%#v\n", []interface{}{dbtype, tlayout, mode, t.s, t.t}) - dbt.Errorf("%s [%s]: unhandled type %T (is '%v')", - dbtype, mode, - val, val, - ) - } -} - -func TestDateTime(t *testing.T) { - afterTime := func(t time.Time, d string) time.Time { - dur, err := time.ParseDuration(d) - if err != nil { - panic(err) - } - return t.Add(dur) - } - // NOTE: MySQL rounds DATETIME(x) up - but that's not included in the tests - format := "2006-01-02 15:04:05.999999" - t0 := time.Time{} - tstr0 := "0000-00-00 00:00:00.000000" - testcases := []timeTests{ - {"DATE", format[:10], []timeTest{ - {t: time.Date(2011, 11, 20, 0, 0, 0, 0, time.UTC)}, - {t: t0, s: tstr0[:10]}, - }}, - {"DATETIME", format[:19], []timeTest{ - {t: time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC)}, - {t: t0, s: tstr0[:19]}, - }}, - {"DATETIME(0)", format[:21], []timeTest{ - {t: time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC)}, - {t: t0, s: tstr0[:19]}, - }}, - {"DATETIME(1)", format[:21], []timeTest{ - {t: time.Date(2011, 11, 20, 21, 27, 37, 100000000, time.UTC)}, - {t: t0, s: tstr0[:21]}, - }}, - {"DATETIME(6)", format, []timeTest{ - {t: time.Date(2011, 11, 20, 21, 27, 37, 123456000, time.UTC)}, - {t: t0, s: tstr0}, - }}, - {"TIME", format[11:19], []timeTest{ - {t: afterTime(t0, "12345s")}, - {s: "!-12:34:56"}, - {s: "!-838:59:59"}, - {s: "!838:59:59"}, - {t: t0, s: tstr0[11:19]}, - }}, - {"TIME(0)", format[11:19], []timeTest{ - {t: afterTime(t0, "12345s")}, - {s: "!-12:34:56"}, - {s: "!-838:59:59"}, - {s: "!838:59:59"}, - {t: t0, s: tstr0[11:19]}, - }}, - {"TIME(1)", format[11:21], []timeTest{ - {t: afterTime(t0, "12345600ms")}, - {s: "!-12:34:56.7"}, - {s: "!-838:59:58.9"}, - {s: "!838:59:58.9"}, - {t: t0, s: tstr0[11:21]}, - }}, - {"TIME(6)", format[11:], []timeTest{ - {t: afterTime(t0, "1234567890123000ns")}, - {s: "!-12:34:56.789012"}, - {s: "!-838:59:58.999999"}, - {s: "!838:59:58.999999"}, - {t: t0, s: tstr0[11:]}, - }}, - } - dsns := []string{ - dsn + "&parseTime=true", - dsn + "&parseTime=false", - } - for _, testdsn := range dsns { - runTests(t, testdsn, func(dbt *DBTest) { - microsecsSupported := false - zeroDateSupported := false - var rows *sql.Rows - var err error - rows, err = dbt.db.Query(`SELECT cast("00:00:00.1" as TIME(1)) = "00:00:00.1"`) - if err == nil { - rows.Scan(µsecsSupported) - rows.Close() - } - rows, err = dbt.db.Query(`SELECT cast("0000-00-00" as DATE) = "0000-00-00"`) - if err == nil { - rows.Scan(&zeroDateSupported) - rows.Close() - } - for _, setups := range testcases { - if t := setups.dbtype; !microsecsSupported && t[len(t)-1:] == ")" { - // skip fractional second tests if unsupported by server - continue - } - for _, setup := range setups.tests { - allowBinTime := true - if setup.s == "" { - // fill time string whereever Go can reliable produce it - setup.s = setup.t.Format(setups.tlayout) - } else if setup.s[0] == '!' { - // skip tests using setup.t as source in queries - allowBinTime = false - // fix setup.s - remove the "!" - setup.s = setup.s[1:] - } - if !zeroDateSupported && setup.s == tstr0[:len(setup.s)] { - // skip disallowed 0000-00-00 date - continue - } - setup.run(dbt, setups.dbtype, setups.tlayout, textString) - setup.run(dbt, setups.dbtype, setups.tlayout, binaryString) - if allowBinTime { - setup.run(dbt, setups.dbtype, setups.tlayout, binaryTime) - } - } - } - }) - } -} - -func TestTimestampMicros(t *testing.T) { - format := "2006-01-02 15:04:05.999999" - f0 := format[:19] - f1 := format[:21] - f6 := format[:26] - runTests(t, dsn, func(dbt *DBTest) { - // check if microseconds are supported. - // Do not use timestamp(x) for that check - before 5.5.6, x would mean display width - // and not precision. - // Se last paragraph at http://dev.mysql.com/doc/refman/5.6/en/fractional-seconds.html - microsecsSupported := false - if rows, err := dbt.db.Query(`SELECT cast("00:00:00.1" as TIME(1)) = "00:00:00.1"`); err == nil { - rows.Scan(µsecsSupported) - rows.Close() - } - if !microsecsSupported { - // skip test - return - } - _, err := dbt.db.Exec(` - CREATE TABLE test ( - value0 TIMESTAMP NOT NULL DEFAULT '` + f0 + `', - value1 TIMESTAMP(1) NOT NULL DEFAULT '` + f1 + `', - value6 TIMESTAMP(6) NOT NULL DEFAULT '` + f6 + `' - )`, - ) - if err != nil { - dbt.Error(err) - } - defer dbt.mustExec("DROP TABLE IF EXISTS test") - dbt.mustExec("INSERT INTO test SET value0=?, value1=?, value6=?", f0, f1, f6) - var res0, res1, res6 string - rows := dbt.mustQuery("SELECT * FROM test") - if !rows.Next() { - dbt.Errorf("test contained no selectable values") - } - err = rows.Scan(&res0, &res1, &res6) - if err != nil { - dbt.Error(err) - } - if res0 != f0 { - dbt.Errorf("expected %q, got %q", f0, res0) - } - if res1 != f1 { - dbt.Errorf("expected %q, got %q", f1, res1) - } - if res6 != f6 { - dbt.Errorf("expected %q, got %q", f6, res6) - } - }) -} - -func TestNULL(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - nullStmt, err := dbt.db.Prepare("SELECT NULL") - if err != nil { - dbt.Fatal(err) - } - defer nullStmt.Close() - - nonNullStmt, err := dbt.db.Prepare("SELECT 1") - if err != nil { - dbt.Fatal(err) - } - defer nonNullStmt.Close() - - // NullBool - var nb sql.NullBool - // Invalid - if err = nullStmt.QueryRow().Scan(&nb); err != nil { - dbt.Fatal(err) - } - if nb.Valid { - dbt.Error("valid NullBool which should be invalid") - } - // Valid - if err = nonNullStmt.QueryRow().Scan(&nb); err != nil { - dbt.Fatal(err) - } - if !nb.Valid { - dbt.Error("invalid NullBool which should be valid") - } else if nb.Bool != true { - dbt.Errorf("Unexpected NullBool value: %t (should be true)", nb.Bool) - } - - // NullFloat64 - var nf sql.NullFloat64 - // Invalid - if err = nullStmt.QueryRow().Scan(&nf); err != nil { - dbt.Fatal(err) - } - if nf.Valid { - dbt.Error("valid NullFloat64 which should be invalid") - } - // Valid - if err = nonNullStmt.QueryRow().Scan(&nf); err != nil { - dbt.Fatal(err) - } - if !nf.Valid { - dbt.Error("invalid NullFloat64 which should be valid") - } else if nf.Float64 != float64(1) { - dbt.Errorf("unexpected NullFloat64 value: %f (should be 1.0)", nf.Float64) - } - - // NullInt64 - var ni sql.NullInt64 - // Invalid - if err = nullStmt.QueryRow().Scan(&ni); err != nil { - dbt.Fatal(err) - } - if ni.Valid { - dbt.Error("valid NullInt64 which should be invalid") - } - // Valid - if err = nonNullStmt.QueryRow().Scan(&ni); err != nil { - dbt.Fatal(err) - } - if !ni.Valid { - dbt.Error("invalid NullInt64 which should be valid") - } else if ni.Int64 != int64(1) { - dbt.Errorf("unexpected NullInt64 value: %d (should be 1)", ni.Int64) - } - - // NullString - var ns sql.NullString - // Invalid - if err = nullStmt.QueryRow().Scan(&ns); err != nil { - dbt.Fatal(err) - } - if ns.Valid { - dbt.Error("valid NullString which should be invalid") - } - // Valid - if err = nonNullStmt.QueryRow().Scan(&ns); err != nil { - dbt.Fatal(err) - } - if !ns.Valid { - dbt.Error("invalid NullString which should be valid") - } else if ns.String != `1` { - dbt.Error("unexpected NullString value:" + ns.String + " (should be `1`)") - } - - // nil-bytes - var b []byte - // Read nil - if err = nullStmt.QueryRow().Scan(&b); err != nil { - dbt.Fatal(err) - } - if b != nil { - dbt.Error("non-nil []byte wich should be nil") - } - // Read non-nil - if err = nonNullStmt.QueryRow().Scan(&b); err != nil { - dbt.Fatal(err) - } - if b == nil { - dbt.Error("nil []byte wich should be non-nil") - } - // Insert nil - b = nil - success := false - if err = dbt.db.QueryRow("SELECT ? IS NULL", b).Scan(&success); err != nil { - dbt.Fatal(err) - } - if !success { - dbt.Error("inserting []byte(nil) as NULL failed") - } - // Check input==output with input==nil - b = nil - if err = dbt.db.QueryRow("SELECT ?", b).Scan(&b); err != nil { - dbt.Fatal(err) - } - if b != nil { - dbt.Error("non-nil echo from nil input") - } - // Check input==output with input!=nil - b = []byte("") - if err = dbt.db.QueryRow("SELECT ?", b).Scan(&b); err != nil { - dbt.Fatal(err) - } - if b == nil { - dbt.Error("nil echo from non-nil input") - } - - // Insert NULL - dbt.mustExec("CREATE TABLE test (dummmy1 int, value int, dummy2 int)") - - dbt.mustExec("INSERT INTO test VALUES (?, ?, ?)", 1, nil, 2) - - var out interface{} - rows := dbt.mustQuery("SELECT * FROM test") - if rows.Next() { - rows.Scan(&out) - if out != nil { - dbt.Errorf("%v != nil", out) - } - } else { - dbt.Error("no data") - } - }) -} - -func TestUint64(t *testing.T) { - const ( - u0 = uint64(0) - uall = ^u0 - uhigh = uall >> 1 - utop = ^uhigh - s0 = int64(0) - sall = ^s0 - shigh = int64(uhigh) - stop = ^shigh - ) - runTests(t, dsn, func(dbt *DBTest) { - stmt, err := dbt.db.Prepare(`SELECT ?, ?, ? ,?, ?, ?, ?, ?`) - if err != nil { - dbt.Fatal(err) - } - defer stmt.Close() - row := stmt.QueryRow( - u0, uhigh, utop, uall, - s0, shigh, stop, sall, - ) - - var ua, ub, uc, ud uint64 - var sa, sb, sc, sd int64 - - err = row.Scan(&ua, &ub, &uc, &ud, &sa, &sb, &sc, &sd) - if err != nil { - dbt.Fatal(err) - } - switch { - case ua != u0, - ub != uhigh, - uc != utop, - ud != uall, - sa != s0, - sb != shigh, - sc != stop, - sd != sall: - dbt.Fatal("unexpected result value") - } - }) -} - -func TestLongData(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - var maxAllowedPacketSize int - err := dbt.db.QueryRow("select @@max_allowed_packet").Scan(&maxAllowedPacketSize) - if err != nil { - dbt.Fatal(err) - } - maxAllowedPacketSize-- - - // don't get too ambitious - if maxAllowedPacketSize > 1<<25 { - maxAllowedPacketSize = 1 << 25 - } - - dbt.mustExec("CREATE TABLE test (value LONGBLOB)") - - in := strings.Repeat(`a`, maxAllowedPacketSize+1) - var out string - var rows *sql.Rows - - // Long text data - const nonDataQueryLen = 28 // length query w/o value - inS := in[:maxAllowedPacketSize-nonDataQueryLen] - dbt.mustExec("INSERT INTO test VALUES('" + inS + "')") - rows = dbt.mustQuery("SELECT value FROM test") - if rows.Next() { - rows.Scan(&out) - if inS != out { - dbt.Fatalf("LONGBLOB: length in: %d, length out: %d", len(inS), len(out)) - } - if rows.Next() { - dbt.Error("LONGBLOB: unexpexted row") - } - } else { - dbt.Fatalf("LONGBLOB: no data") - } - - // Empty table - dbt.mustExec("TRUNCATE TABLE test") - - // Long binary data - dbt.mustExec("INSERT INTO test VALUES(?)", in) - rows = dbt.mustQuery("SELECT value FROM test WHERE 1=?", 1) - if rows.Next() { - rows.Scan(&out) - if in != out { - dbt.Fatalf("LONGBLOB: length in: %d, length out: %d", len(in), len(out)) - } - if rows.Next() { - dbt.Error("LONGBLOB: unexpexted row") - } - } else { - if err = rows.Err(); err != nil { - dbt.Fatalf("LONGBLOB: no data (err: %s)", err.Error()) - } else { - dbt.Fatal("LONGBLOB: no data (err: )") - } - } - }) -} - -func TestLoadData(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - verifyLoadDataResult := func() { - rows, err := dbt.db.Query("SELECT * FROM test") - if err != nil { - dbt.Fatal(err.Error()) - } - - i := 0 - values := [4]string{ - "a string", - "a string containing a \t", - "a string containing a \n", - "a string containing both \t\n", - } - - var id int - var value string - - for rows.Next() { - i++ - err = rows.Scan(&id, &value) - if err != nil { - dbt.Fatal(err.Error()) - } - if i != id { - dbt.Fatalf("%d != %d", i, id) - } - if values[i-1] != value { - dbt.Fatalf("%q != %q", values[i-1], value) - } - } - err = rows.Err() - if err != nil { - dbt.Fatal(err.Error()) - } - - if i != 4 { - dbt.Fatalf("rows count mismatch. Got %d, want 4", i) - } - } - file, err := ioutil.TempFile("", "gotest") - defer os.Remove(file.Name()) - if err != nil { - dbt.Fatal(err) - } - file.WriteString("1\ta string\n2\ta string containing a \\t\n3\ta string containing a \\n\n4\ta string containing both \\t\\n\n") - file.Close() - - dbt.db.Exec("DROP TABLE IF EXISTS test") - dbt.mustExec("CREATE TABLE test (id INT NOT NULL PRIMARY KEY, value TEXT NOT NULL) CHARACTER SET utf8") - - // Local File - RegisterLocalFile(file.Name()) - dbt.mustExec(fmt.Sprintf("LOAD DATA LOCAL INFILE %q INTO TABLE test", file.Name())) - verifyLoadDataResult() - // negative test - _, err = dbt.db.Exec("LOAD DATA LOCAL INFILE 'doesnotexist' INTO TABLE test") - if err == nil { - dbt.Fatal("load non-existent file didn't fail") - } else if err.Error() != "local file 'doesnotexist' is not registered" { - dbt.Fatal(err.Error()) - } - - // Empty table - dbt.mustExec("TRUNCATE TABLE test") - - // Reader - RegisterReaderHandler("test", func() io.Reader { - file, err = os.Open(file.Name()) - if err != nil { - dbt.Fatal(err) - } - return file - }) - dbt.mustExec("LOAD DATA LOCAL INFILE 'Reader::test' INTO TABLE test") - verifyLoadDataResult() - // negative test - _, err = dbt.db.Exec("LOAD DATA LOCAL INFILE 'Reader::doesnotexist' INTO TABLE test") - if err == nil { - dbt.Fatal("load non-existent Reader didn't fail") - } else if err.Error() != "Reader 'doesnotexist' is not registered" { - dbt.Fatal(err.Error()) - } - }) -} - -func TestFoundRows(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - dbt.mustExec("CREATE TABLE test (id INT NOT NULL ,data INT NOT NULL)") - dbt.mustExec("INSERT INTO test (id, data) VALUES (0, 0),(0, 0),(1, 0),(1, 0),(1, 1)") - - res := dbt.mustExec("UPDATE test SET data = 1 WHERE id = 0") - count, err := res.RowsAffected() - if err != nil { - dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error()) - } - if count != 2 { - dbt.Fatalf("Expected 2 affected rows, got %d", count) - } - res = dbt.mustExec("UPDATE test SET data = 1 WHERE id = 1") - count, err = res.RowsAffected() - if err != nil { - dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error()) - } - if count != 2 { - dbt.Fatalf("Expected 2 affected rows, got %d", count) - } - }) - runTests(t, dsn+"&clientFoundRows=true", func(dbt *DBTest) { - dbt.mustExec("CREATE TABLE test (id INT NOT NULL ,data INT NOT NULL)") - dbt.mustExec("INSERT INTO test (id, data) VALUES (0, 0),(0, 0),(1, 0),(1, 0),(1, 1)") - - res := dbt.mustExec("UPDATE test SET data = 1 WHERE id = 0") - count, err := res.RowsAffected() - if err != nil { - dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error()) - } - if count != 2 { - dbt.Fatalf("Expected 2 matched rows, got %d", count) - } - res = dbt.mustExec("UPDATE test SET data = 1 WHERE id = 1") - count, err = res.RowsAffected() - if err != nil { - dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error()) - } - if count != 3 { - dbt.Fatalf("Expected 3 matched rows, got %d", count) - } - }) -} - -func TestStrict(t *testing.T) { - // ALLOW_INVALID_DATES to get rid of stricter modes - we want to test for warnings, not errors - relaxedDsn := dsn + "&sql_mode='ALLOW_INVALID_DATES,NO_AUTO_CREATE_USER'" - // make sure the MySQL version is recent enough with a separate connection - // before running the test - conn, err := MySQLDriver{}.Open(relaxedDsn) - if conn != nil { - conn.Close() - } - if me, ok := err.(*MySQLError); ok && me.Number == 1231 { - // Error 1231: Variable 'sql_mode' can't be set to the value of 'ALLOW_INVALID_DATES' - // => skip test, MySQL server version is too old - return - } - runTests(t, relaxedDsn, func(dbt *DBTest) { - dbt.mustExec("CREATE TABLE test (a TINYINT NOT NULL, b CHAR(4))") - - var queries = [...]struct { - in string - codes []string - }{ - {"DROP TABLE IF EXISTS no_such_table", []string{"1051"}}, - {"INSERT INTO test VALUES(10,'mysql'),(NULL,'test'),(300,'Open Source')", []string{"1265", "1048", "1264", "1265"}}, - } - var err error - - var checkWarnings = func(err error, mode string, idx int) { - if err == nil { - dbt.Errorf("expected STRICT error on query [%s] %s", mode, queries[idx].in) - } - - if warnings, ok := err.(MySQLWarnings); ok { - var codes = make([]string, len(warnings)) - for i := range warnings { - codes[i] = warnings[i].Code - } - if len(codes) != len(queries[idx].codes) { - dbt.Errorf("unexpected STRICT error count on query [%s] %s: Wanted %v, Got %v", mode, queries[idx].in, queries[idx].codes, codes) - } - - for i := range warnings { - if codes[i] != queries[idx].codes[i] { - dbt.Errorf("unexpected STRICT error codes on query [%s] %s: Wanted %v, Got %v", mode, queries[idx].in, queries[idx].codes, codes) - return - } - } - - } else { - dbt.Errorf("unexpected error on query [%s] %s: %s", mode, queries[idx].in, err.Error()) - } - } - - // text protocol - for i := range queries { - _, err = dbt.db.Exec(queries[i].in) - checkWarnings(err, "text", i) - } - - var stmt *sql.Stmt - - // binary protocol - for i := range queries { - stmt, err = dbt.db.Prepare(queries[i].in) - if err != nil { - dbt.Errorf("error on preparing query %s: %s", queries[i].in, err.Error()) - } - - _, err = stmt.Exec() - checkWarnings(err, "binary", i) - - err = stmt.Close() - if err != nil { - dbt.Errorf("error on closing stmt for query %s: %s", queries[i].in, err.Error()) - } - } - }) -} - -func TestTLS(t *testing.T) { - tlsTest := func(dbt *DBTest) { - if err := dbt.db.Ping(); err != nil { - if err == ErrNoTLS { - dbt.Skip("server does not support TLS") - } else { - dbt.Fatalf("error on Ping: %s", err.Error()) - } - } - - rows := dbt.mustQuery("SHOW STATUS LIKE 'Ssl_cipher'") - - var variable, value *sql.RawBytes - for rows.Next() { - if err := rows.Scan(&variable, &value); err != nil { - dbt.Fatal(err.Error()) - } - - if value == nil { - dbt.Fatal("no Cipher") - } - } - } - - runTests(t, dsn+"&tls=skip-verify", tlsTest) - - // Verify that registering / using a custom cfg works - RegisterTLSConfig("custom-skip-verify", &tls.Config{ - InsecureSkipVerify: true, - }) - runTests(t, dsn+"&tls=custom-skip-verify", tlsTest) -} - -func TestReuseClosedConnection(t *testing.T) { - // this test does not use sql.database, it uses the driver directly - if !available { - t.Skipf("MySQL server not running on %s", netAddr) - } - - md := &MySQLDriver{} - conn, err := md.Open(dsn) - if err != nil { - t.Fatalf("error connecting: %s", err.Error()) - } - stmt, err := conn.Prepare("DO 1") - if err != nil { - t.Fatalf("error preparing statement: %s", err.Error()) - } - _, err = stmt.Exec(nil) - if err != nil { - t.Fatalf("error executing statement: %s", err.Error()) - } - err = conn.Close() - if err != nil { - t.Fatalf("error closing connection: %s", err.Error()) - } - - defer func() { - if err := recover(); err != nil { - t.Errorf("panic after reusing a closed connection: %v", err) - } - }() - _, err = stmt.Exec(nil) - if err != nil && err != driver.ErrBadConn { - t.Errorf("unexpected error '%s', expected '%s'", - err.Error(), driver.ErrBadConn.Error()) - } -} - -func TestCharset(t *testing.T) { - if !available { - t.Skipf("MySQL server not running on %s", netAddr) - } - - mustSetCharset := func(charsetParam, expected string) { - runTests(t, dsn+"&"+charsetParam, func(dbt *DBTest) { - rows := dbt.mustQuery("SELECT @@character_set_connection") - defer rows.Close() - - if !rows.Next() { - dbt.Fatalf("error getting connection charset: %s", rows.Err()) - } - - var got string - rows.Scan(&got) - - if got != expected { - dbt.Fatalf("expected connection charset %s but got %s", expected, got) - } - }) - } - - // non utf8 test - mustSetCharset("charset=ascii", "ascii") - - // when the first charset is invalid, use the second - mustSetCharset("charset=none,utf8", "utf8") - - // when the first charset is valid, use it - mustSetCharset("charset=ascii,utf8", "ascii") - mustSetCharset("charset=utf8,ascii", "utf8") -} - -func TestFailingCharset(t *testing.T) { - runTests(t, dsn+"&charset=none", func(dbt *DBTest) { - // run query to really establish connection... - _, err := dbt.db.Exec("SELECT 1") - if err == nil { - dbt.db.Close() - t.Fatalf("connection must not succeed without a valid charset") - } - }) -} - -func TestCollation(t *testing.T) { - if !available { - t.Skipf("MySQL server not running on %s", netAddr) - } - - defaultCollation := "utf8_general_ci" - testCollations := []string{ - "", // do not set - defaultCollation, // driver default - "latin1_general_ci", - "binary", - "utf8_unicode_ci", - "cp1257_bin", - } - - for _, collation := range testCollations { - var expected, tdsn string - if collation != "" { - tdsn = dsn + "&collation=" + collation - expected = collation - } else { - tdsn = dsn - expected = defaultCollation - } - - runTests(t, tdsn, func(dbt *DBTest) { - var got string - if err := dbt.db.QueryRow("SELECT @@collation_connection").Scan(&got); err != nil { - dbt.Fatal(err) - } - - if got != expected { - dbt.Fatalf("expected connection collation %s but got %s", expected, got) - } - }) - } -} - -func TestColumnsWithAlias(t *testing.T) { - runTests(t, dsn+"&columnsWithAlias=true", func(dbt *DBTest) { - rows := dbt.mustQuery("SELECT 1 AS A") - defer rows.Close() - cols, _ := rows.Columns() - if len(cols) != 1 { - t.Fatalf("expected 1 column, got %d", len(cols)) - } - if cols[0] != "A" { - t.Fatalf("expected column name \"A\", got \"%s\"", cols[0]) - } - rows.Close() - - rows = dbt.mustQuery("SELECT * FROM (SELECT 1 AS one) AS A") - cols, _ = rows.Columns() - if len(cols) != 1 { - t.Fatalf("expected 1 column, got %d", len(cols)) - } - if cols[0] != "A.one" { - t.Fatalf("expected column name \"A.one\", got \"%s\"", cols[0]) - } - }) -} - -func TestRawBytesResultExceedsBuffer(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - // defaultBufSize from buffer.go - expected := strings.Repeat("abc", defaultBufSize) - - rows := dbt.mustQuery("SELECT '" + expected + "'") - defer rows.Close() - if !rows.Next() { - dbt.Error("expected result, got none") - } - var result sql.RawBytes - rows.Scan(&result) - if expected != string(result) { - dbt.Error("result did not match expected value") - } - }) -} - -func TestTimezoneConversion(t *testing.T) { - zones := []string{"UTC", "US/Central", "US/Pacific", "Local"} - - // Regression test for timezone handling - tzTest := func(dbt *DBTest) { - - // Create table - dbt.mustExec("CREATE TABLE test (ts TIMESTAMP)") - - // Insert local time into database (should be converted) - usCentral, _ := time.LoadLocation("US/Central") - reftime := time.Date(2014, 05, 30, 18, 03, 17, 0, time.UTC).In(usCentral) - dbt.mustExec("INSERT INTO test VALUE (?)", reftime) - - // Retrieve time from DB - rows := dbt.mustQuery("SELECT ts FROM test") - if !rows.Next() { - dbt.Fatal("did not get any rows out") - } - - var dbTime time.Time - err := rows.Scan(&dbTime) - if err != nil { - dbt.Fatal("Err", err) - } - - // Check that dates match - if reftime.Unix() != dbTime.Unix() { - dbt.Errorf("times do not match.\n") - dbt.Errorf(" Now(%v)=%v\n", usCentral, reftime) - dbt.Errorf(" Now(UTC)=%v\n", dbTime) - } - } - - for _, tz := range zones { - runTests(t, dsn+"&parseTime=true&loc="+url.QueryEscape(tz), tzTest) - } -} - -// Special cases - -func TestRowsClose(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - rows, err := dbt.db.Query("SELECT 1") - if err != nil { - dbt.Fatal(err) - } - - err = rows.Close() - if err != nil { - dbt.Fatal(err) - } - - if rows.Next() { - dbt.Fatal("unexpected row after rows.Close()") - } - - err = rows.Err() - if err != nil { - dbt.Fatal(err) - } - }) -} - -// dangling statements -// http://code.google.com/p/go/issues/detail?id=3865 -func TestCloseStmtBeforeRows(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - stmt, err := dbt.db.Prepare("SELECT 1") - if err != nil { - dbt.Fatal(err) - } - - rows, err := stmt.Query() - if err != nil { - stmt.Close() - dbt.Fatal(err) - } - defer rows.Close() - - err = stmt.Close() - if err != nil { - dbt.Fatal(err) - } - - if !rows.Next() { - dbt.Fatal("getting row failed") - } else { - err = rows.Err() - if err != nil { - dbt.Fatal(err) - } - - var out bool - err = rows.Scan(&out) - if err != nil { - dbt.Fatalf("error on rows.Scan(): %s", err.Error()) - } - if out != true { - dbt.Errorf("true != %t", out) - } - } - }) -} - -// It is valid to have multiple Rows for the same Stmt -// http://code.google.com/p/go/issues/detail?id=3734 -func TestStmtMultiRows(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - stmt, err := dbt.db.Prepare("SELECT 1 UNION SELECT 0") - if err != nil { - dbt.Fatal(err) - } - - rows1, err := stmt.Query() - if err != nil { - stmt.Close() - dbt.Fatal(err) - } - defer rows1.Close() - - rows2, err := stmt.Query() - if err != nil { - stmt.Close() - dbt.Fatal(err) - } - defer rows2.Close() - - var out bool - - // 1 - if !rows1.Next() { - dbt.Fatal("first rows1.Next failed") - } else { - err = rows1.Err() - if err != nil { - dbt.Fatal(err) - } - - err = rows1.Scan(&out) - if err != nil { - dbt.Fatalf("error on rows.Scan(): %s", err.Error()) - } - if out != true { - dbt.Errorf("true != %t", out) - } - } - - if !rows2.Next() { - dbt.Fatal("first rows2.Next failed") - } else { - err = rows2.Err() - if err != nil { - dbt.Fatal(err) - } - - err = rows2.Scan(&out) - if err != nil { - dbt.Fatalf("error on rows.Scan(): %s", err.Error()) - } - if out != true { - dbt.Errorf("true != %t", out) - } - } - - // 2 - if !rows1.Next() { - dbt.Fatal("second rows1.Next failed") - } else { - err = rows1.Err() - if err != nil { - dbt.Fatal(err) - } - - err = rows1.Scan(&out) - if err != nil { - dbt.Fatalf("error on rows.Scan(): %s", err.Error()) - } - if out != false { - dbt.Errorf("false != %t", out) - } - - if rows1.Next() { - dbt.Fatal("unexpected row on rows1") - } - err = rows1.Close() - if err != nil { - dbt.Fatal(err) - } - } - - if !rows2.Next() { - dbt.Fatal("second rows2.Next failed") - } else { - err = rows2.Err() - if err != nil { - dbt.Fatal(err) - } - - err = rows2.Scan(&out) - if err != nil { - dbt.Fatalf("error on rows.Scan(): %s", err.Error()) - } - if out != false { - dbt.Errorf("false != %t", out) - } - - if rows2.Next() { - dbt.Fatal("unexpected row on rows2") - } - err = rows2.Close() - if err != nil { - dbt.Fatal(err) - } - } - }) -} - -// Regression test for -// * more than 32 NULL parameters (issue 209) -// * more parameters than fit into the buffer (issue 201) -func TestPreparedManyCols(t *testing.T) { - const numParams = defaultBufSize - runTests(t, dsn, func(dbt *DBTest) { - query := "SELECT ?" + strings.Repeat(",?", numParams-1) - stmt, err := dbt.db.Prepare(query) - if err != nil { - dbt.Fatal(err) - } - defer stmt.Close() - // create more parameters than fit into the buffer - // which will take nil-values - params := make([]interface{}, numParams) - rows, err := stmt.Query(params...) - if err != nil { - stmt.Close() - dbt.Fatal(err) - } - defer rows.Close() - }) -} - -func TestConcurrent(t *testing.T) { - if enabled, _ := readBool(os.Getenv("MYSQL_TEST_CONCURRENT")); !enabled { - t.Skip("MYSQL_TEST_CONCURRENT env var not set") - } - - runTests(t, dsn, func(dbt *DBTest) { - var max int - err := dbt.db.QueryRow("SELECT @@max_connections").Scan(&max) - if err != nil { - dbt.Fatalf("%s", err.Error()) - } - dbt.Logf("testing up to %d concurrent connections \r\n", max) - - var remaining, succeeded int32 = int32(max), 0 - - var wg sync.WaitGroup - wg.Add(max) - - var fatalError string - var once sync.Once - fatalf := func(s string, vals ...interface{}) { - once.Do(func() { - fatalError = fmt.Sprintf(s, vals...) - }) - } - - for i := 0; i < max; i++ { - go func(id int) { - defer wg.Done() - - tx, err := dbt.db.Begin() - atomic.AddInt32(&remaining, -1) - - if err != nil { - if err.Error() != "Error 1040: Too many connections" { - fatalf("error on conn %d: %s", id, err.Error()) - } - return - } - - // keep the connection busy until all connections are open - for remaining > 0 { - if _, err = tx.Exec("DO 1"); err != nil { - fatalf("error on conn %d: %s", id, err.Error()) - return - } - } - - if err = tx.Commit(); err != nil { - fatalf("error on conn %d: %s", id, err.Error()) - return - } - - // everything went fine with this connection - atomic.AddInt32(&succeeded, 1) - }(i) - } - - // wait until all conections are open - wg.Wait() - - if fatalError != "" { - dbt.Fatal(fatalError) - } - - dbt.Logf("reached %d concurrent connections\r\n", succeeded) - }) -} - -// Tests custom dial functions -func TestCustomDial(t *testing.T) { - if !available { - t.Skipf("MySQL server not running on %s", netAddr) - } - - // our custom dial function which justs wraps net.Dial here - RegisterDial("mydial", func(addr string) (net.Conn, error) { - return net.Dial(prot, addr) - }) - - db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@mydial(%s)/%s?timeout=30s&strict=true", user, pass, addr, dbname)) - if err != nil { - t.Fatalf("error connecting: %s", err.Error()) - } - defer db.Close() - - if _, err = db.Exec("DO 1"); err != nil { - t.Fatalf("connection failed: %s", err.Error()) - } -} - -func TestSQLInjection(t *testing.T) { - createTest := func(arg string) func(dbt *DBTest) { - return func(dbt *DBTest) { - dbt.mustExec("CREATE TABLE test (v INTEGER)") - dbt.mustExec("INSERT INTO test VALUES (?)", 1) - - var v int - // NULL can't be equal to anything, the idea here is to inject query so it returns row - // This test verifies that escapeQuotes and escapeBackslash are working properly - err := dbt.db.QueryRow("SELECT v FROM test WHERE NULL = ?", arg).Scan(&v) - if err == sql.ErrNoRows { - return // success, sql injection failed - } else if err == nil { - dbt.Errorf("sql injection successful with arg: %s", arg) - } else { - dbt.Errorf("error running query with arg: %s; err: %s", arg, err.Error()) - } - } - } - - dsns := []string{ - dsn, - dsn + "&sql_mode='NO_BACKSLASH_ESCAPES,NO_AUTO_CREATE_USER'", - } - for _, testdsn := range dsns { - runTests(t, testdsn, createTest("1 OR 1=1")) - runTests(t, testdsn, createTest("' OR '1'='1")) - } -} - -// Test if inserted data is correctly retrieved after being escaped -func TestInsertRetrieveEscapedData(t *testing.T) { - testData := func(dbt *DBTest) { - dbt.mustExec("CREATE TABLE test (v VARCHAR(255))") - - // All sequences that are escaped by escapeQuotes and escapeBackslash - v := "foo \x00\n\r\x1a\"'\\" - dbt.mustExec("INSERT INTO test VALUES (?)", v) - - var out string - err := dbt.db.QueryRow("SELECT v FROM test").Scan(&out) - if err != nil { - dbt.Fatalf("%s", err.Error()) - } - - if out != v { - dbt.Errorf("%q != %q", out, v) - } - } - - dsns := []string{ - dsn, - dsn + "&sql_mode='NO_BACKSLASH_ESCAPES,NO_AUTO_CREATE_USER'", - } - for _, testdsn := range dsns { - runTests(t, testdsn, testData) - } -} - -func TestUnixSocketAuthFail(t *testing.T) { - runTests(t, dsn, func(dbt *DBTest) { - // Save the current logger so we can restore it. - oldLogger := errLog - - // Set a new logger so we can capture its output. - buffer := bytes.NewBuffer(make([]byte, 0, 64)) - newLogger := log.New(buffer, "prefix: ", 0) - SetLogger(newLogger) - - // Restore the logger. - defer SetLogger(oldLogger) - - // Make a new DSN that uses the MySQL socket file and a bad password, which - // we can make by simply appending any character to the real password. - badPass := pass + "x" - socket := "" - if prot == "unix" { - socket = addr - } else { - // Get socket file from MySQL. - err := dbt.db.QueryRow("SELECT @@socket").Scan(&socket) - if err != nil { - t.Fatalf("error on SELECT @@socket: %s", err.Error()) - } - } - t.Logf("socket: %s", socket) - badDSN := fmt.Sprintf("%s:%s@unix(%s)/%s?timeout=30s&strict=true", user, badPass, socket, dbname) - db, err := sql.Open("mysql", badDSN) - if err != nil { - t.Fatalf("error connecting: %s", err.Error()) - } - defer db.Close() - - // Connect to MySQL for real. This will cause an auth failure. - err = db.Ping() - if err == nil { - t.Error("expected Ping() to return an error") - } - - // The driver should not log anything. - if actual := buffer.String(); actual != "" { - t.Errorf("expected no output, got %q", actual) - } - }) -} diff --git a/vendor/github.com/go-sql-driver/mysql/dsn_test.go b/vendor/github.com/go-sql-driver/mysql/dsn_test.go deleted file mode 100644 index 80949e18ab1c..000000000000 --- a/vendor/github.com/go-sql-driver/mysql/dsn_test.go +++ /dev/null @@ -1,207 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2016 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -import ( - "crypto/tls" - "fmt" - "net/url" - "testing" -) - -var testDSNs = []struct { - in string - out string -}{ - {"username:password@protocol(address)/dbname?param=value", "&{User:username Passwd:password Net:protocol Addr:address DBName:dbname Params:map[param:value] Collation:utf8_general_ci Loc:UTC TLSConfig: tls: Timeout:0 ReadTimeout:0 WriteTimeout:0 AllowAllFiles:false AllowCleartextPasswords:false AllowOldPasswords:false ClientFoundRows:false ColumnsWithAlias:false InterpolateParams:false MultiStatements:false ParseTime:false Strict:false}"}, - {"username:password@protocol(address)/dbname?param=value&columnsWithAlias=true", "&{User:username Passwd:password Net:protocol Addr:address DBName:dbname Params:map[param:value] Collation:utf8_general_ci Loc:UTC TLSConfig: tls: Timeout:0 ReadTimeout:0 WriteTimeout:0 AllowAllFiles:false AllowCleartextPasswords:false AllowOldPasswords:false ClientFoundRows:false ColumnsWithAlias:true InterpolateParams:false MultiStatements:false ParseTime:false Strict:false}"}, - {"username:password@protocol(address)/dbname?param=value&columnsWithAlias=true&multiStatements=true", "&{User:username Passwd:password Net:protocol Addr:address DBName:dbname Params:map[param:value] Collation:utf8_general_ci Loc:UTC TLSConfig: tls: Timeout:0 ReadTimeout:0 WriteTimeout:0 AllowAllFiles:false AllowCleartextPasswords:false AllowOldPasswords:false ClientFoundRows:false ColumnsWithAlias:true InterpolateParams:false MultiStatements:true ParseTime:false Strict:false}"}, - {"user@unix(/path/to/socket)/dbname?charset=utf8", "&{User:user Passwd: Net:unix Addr:/path/to/socket DBName:dbname Params:map[charset:utf8] Collation:utf8_general_ci Loc:UTC TLSConfig: tls: Timeout:0 ReadTimeout:0 WriteTimeout:0 AllowAllFiles:false AllowCleartextPasswords:false AllowOldPasswords:false ClientFoundRows:false ColumnsWithAlias:false InterpolateParams:false MultiStatements:false ParseTime:false Strict:false}"}, - {"user:password@tcp(localhost:5555)/dbname?charset=utf8&tls=true", "&{User:user Passwd:password Net:tcp Addr:localhost:5555 DBName:dbname Params:map[charset:utf8] Collation:utf8_general_ci Loc:UTC TLSConfig:true tls: Timeout:0 ReadTimeout:0 WriteTimeout:0 AllowAllFiles:false AllowCleartextPasswords:false AllowOldPasswords:false ClientFoundRows:false ColumnsWithAlias:false InterpolateParams:false MultiStatements:false ParseTime:false Strict:false}"}, - {"user:password@tcp(localhost:5555)/dbname?charset=utf8mb4,utf8&tls=skip-verify", "&{User:user Passwd:password Net:tcp Addr:localhost:5555 DBName:dbname Params:map[charset:utf8mb4,utf8] Collation:utf8_general_ci Loc:UTC TLSConfig:skip-verify tls: Timeout:0 ReadTimeout:0 WriteTimeout:0 AllowAllFiles:false AllowCleartextPasswords:false AllowOldPasswords:false ClientFoundRows:false ColumnsWithAlias:false InterpolateParams:false MultiStatements:false ParseTime:false Strict:false}"}, - {"user:password@/dbname?loc=UTC&timeout=30s&readTimeout=1s&writeTimeout=1s&allowAllFiles=1&clientFoundRows=true&allowOldPasswords=TRUE&collation=utf8mb4_unicode_ci", "&{User:user Passwd:password Net:tcp Addr:127.0.0.1:3306 DBName:dbname Params:map[] Collation:utf8mb4_unicode_ci Loc:UTC TLSConfig: tls: Timeout:30s ReadTimeout:1s WriteTimeout:1s AllowAllFiles:true AllowCleartextPasswords:false AllowOldPasswords:true ClientFoundRows:true ColumnsWithAlias:false InterpolateParams:false MultiStatements:false ParseTime:false Strict:false}"}, - {"user:p@ss(word)@tcp([de:ad:be:ef::ca:fe]:80)/dbname?loc=Local", "&{User:user Passwd:p@ss(word) Net:tcp Addr:[de:ad:be:ef::ca:fe]:80 DBName:dbname Params:map[] Collation:utf8_general_ci Loc:Local TLSConfig: tls: Timeout:0 ReadTimeout:0 WriteTimeout:0 AllowAllFiles:false AllowCleartextPasswords:false AllowOldPasswords:false ClientFoundRows:false ColumnsWithAlias:false InterpolateParams:false MultiStatements:false ParseTime:false Strict:false}"}, - {"/dbname", "&{User: Passwd: Net:tcp Addr:127.0.0.1:3306 DBName:dbname Params:map[] Collation:utf8_general_ci Loc:UTC TLSConfig: tls: Timeout:0 ReadTimeout:0 WriteTimeout:0 AllowAllFiles:false AllowCleartextPasswords:false AllowOldPasswords:false ClientFoundRows:false ColumnsWithAlias:false InterpolateParams:false MultiStatements:false ParseTime:false Strict:false}"}, - {"@/", "&{User: Passwd: Net:tcp Addr:127.0.0.1:3306 DBName: Params:map[] Collation:utf8_general_ci Loc:UTC TLSConfig: tls: Timeout:0 ReadTimeout:0 WriteTimeout:0 AllowAllFiles:false AllowCleartextPasswords:false AllowOldPasswords:false ClientFoundRows:false ColumnsWithAlias:false InterpolateParams:false MultiStatements:false ParseTime:false Strict:false}"}, - {"/", "&{User: Passwd: Net:tcp Addr:127.0.0.1:3306 DBName: Params:map[] Collation:utf8_general_ci Loc:UTC TLSConfig: tls: Timeout:0 ReadTimeout:0 WriteTimeout:0 AllowAllFiles:false AllowCleartextPasswords:false AllowOldPasswords:false ClientFoundRows:false ColumnsWithAlias:false InterpolateParams:false MultiStatements:false ParseTime:false Strict:false}"}, - {"", "&{User: Passwd: Net:tcp Addr:127.0.0.1:3306 DBName: Params:map[] Collation:utf8_general_ci Loc:UTC TLSConfig: tls: Timeout:0 ReadTimeout:0 WriteTimeout:0 AllowAllFiles:false AllowCleartextPasswords:false AllowOldPasswords:false ClientFoundRows:false ColumnsWithAlias:false InterpolateParams:false MultiStatements:false ParseTime:false Strict:false}"}, - {"user:p@/ssword@/", "&{User:user Passwd:p@/ssword Net:tcp Addr:127.0.0.1:3306 DBName: Params:map[] Collation:utf8_general_ci Loc:UTC TLSConfig: tls: Timeout:0 ReadTimeout:0 WriteTimeout:0 AllowAllFiles:false AllowCleartextPasswords:false AllowOldPasswords:false ClientFoundRows:false ColumnsWithAlias:false InterpolateParams:false MultiStatements:false ParseTime:false Strict:false}"}, - {"unix/?arg=%2Fsome%2Fpath.ext", "&{User: Passwd: Net:unix Addr:/tmp/mysql.sock DBName: Params:map[arg:/some/path.ext] Collation:utf8_general_ci Loc:UTC TLSConfig: tls: Timeout:0 ReadTimeout:0 WriteTimeout:0 AllowAllFiles:false AllowCleartextPasswords:false AllowOldPasswords:false ClientFoundRows:false ColumnsWithAlias:false InterpolateParams:false MultiStatements:false ParseTime:false Strict:false}"}, -} - -func TestDSNParser(t *testing.T) { - var cfg *Config - var err error - var res string - - for i, tst := range testDSNs { - cfg, err = ParseDSN(tst.in) - if err != nil { - t.Error(err.Error()) - } - - // pointer not static - cfg.tls = nil - - res = fmt.Sprintf("%+v", cfg) - if res != tst.out { - t.Errorf("%d. ParseDSN(%q) => %q, want %q", i, tst.in, res, tst.out) - } - } -} - -func TestDSNParserInvalid(t *testing.T) { - var invalidDSNs = []string{ - "@net(addr/", // no closing brace - "@tcp(/", // no closing brace - "tcp(/", // no closing brace - "(/", // no closing brace - "net(addr)//", // unescaped - "User:pass@tcp(1.2.3.4:3306)", // no trailing slash - //"/dbname?arg=/some/unescaped/path", - } - - for i, tst := range invalidDSNs { - if _, err := ParseDSN(tst); err == nil { - t.Errorf("invalid DSN #%d. (%s) didn't error!", i, tst) - } - } -} - -func TestDSNReformat(t *testing.T) { - for i, tst := range testDSNs { - dsn1 := tst.in - cfg1, err := ParseDSN(dsn1) - if err != nil { - t.Error(err.Error()) - continue - } - cfg1.tls = nil // pointer not static - res1 := fmt.Sprintf("%+v", cfg1) - - dsn2 := cfg1.FormatDSN() - cfg2, err := ParseDSN(dsn2) - if err != nil { - t.Error(err.Error()) - continue - } - cfg2.tls = nil // pointer not static - res2 := fmt.Sprintf("%+v", cfg2) - - if res1 != res2 { - t.Errorf("%d. %q does not match %q", i, res2, res1) - } - } -} - -func TestDSNWithCustomTLS(t *testing.T) { - baseDSN := "User:password@tcp(localhost:5555)/dbname?tls=" - tlsCfg := tls.Config{} - - RegisterTLSConfig("utils_test", &tlsCfg) - - // Custom TLS is missing - tst := baseDSN + "invalid_tls" - cfg, err := ParseDSN(tst) - if err == nil { - t.Errorf("invalid custom TLS in DSN (%s) but did not error. Got config: %#v", tst, cfg) - } - - tst = baseDSN + "utils_test" - - // Custom TLS with a server name - name := "foohost" - tlsCfg.ServerName = name - cfg, err = ParseDSN(tst) - - if err != nil { - t.Error(err.Error()) - } else if cfg.tls.ServerName != name { - t.Errorf("did not get the correct TLS ServerName (%s) parsing DSN (%s).", name, tst) - } - - // Custom TLS without a server name - name = "localhost" - tlsCfg.ServerName = "" - cfg, err = ParseDSN(tst) - - if err != nil { - t.Error(err.Error()) - } else if cfg.tls.ServerName != name { - t.Errorf("did not get the correct ServerName (%s) parsing DSN (%s).", name, tst) - } - - DeregisterTLSConfig("utils_test") -} - -func TestDSNWithCustomTLSQueryEscape(t *testing.T) { - const configKey = "&%!:" - dsn := "User:password@tcp(localhost:5555)/dbname?tls=" + url.QueryEscape(configKey) - name := "foohost" - tlsCfg := tls.Config{ServerName: name} - - RegisterTLSConfig(configKey, &tlsCfg) - - cfg, err := ParseDSN(dsn) - - if err != nil { - t.Error(err.Error()) - } else if cfg.tls.ServerName != name { - t.Errorf("did not get the correct TLS ServerName (%s) parsing DSN (%s).", name, dsn) - } -} - -func TestDSNUnsafeCollation(t *testing.T) { - _, err := ParseDSN("/dbname?collation=gbk_chinese_ci&interpolateParams=true") - if err != errInvalidDSNUnsafeCollation { - t.Errorf("expected %v, got %v", errInvalidDSNUnsafeCollation, err) - } - - _, err = ParseDSN("/dbname?collation=gbk_chinese_ci&interpolateParams=false") - if err != nil { - t.Errorf("expected %v, got %v", nil, err) - } - - _, err = ParseDSN("/dbname?collation=gbk_chinese_ci") - if err != nil { - t.Errorf("expected %v, got %v", nil, err) - } - - _, err = ParseDSN("/dbname?collation=ascii_bin&interpolateParams=true") - if err != nil { - t.Errorf("expected %v, got %v", nil, err) - } - - _, err = ParseDSN("/dbname?collation=latin1_german1_ci&interpolateParams=true") - if err != nil { - t.Errorf("expected %v, got %v", nil, err) - } - - _, err = ParseDSN("/dbname?collation=utf8_general_ci&interpolateParams=true") - if err != nil { - t.Errorf("expected %v, got %v", nil, err) - } - - _, err = ParseDSN("/dbname?collation=utf8mb4_general_ci&interpolateParams=true") - if err != nil { - t.Errorf("expected %v, got %v", nil, err) - } -} - -func BenchmarkParseDSN(b *testing.B) { - b.ReportAllocs() - - for i := 0; i < b.N; i++ { - for _, tst := range testDSNs { - if _, err := ParseDSN(tst.in); err != nil { - b.Error(err.Error()) - } - } - } -} diff --git a/vendor/github.com/go-sql-driver/mysql/errors_test.go b/vendor/github.com/go-sql-driver/mysql/errors_test.go deleted file mode 100644 index 96f9126d679a..000000000000 --- a/vendor/github.com/go-sql-driver/mysql/errors_test.go +++ /dev/null @@ -1,42 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -import ( - "bytes" - "log" - "testing" -) - -func TestErrorsSetLogger(t *testing.T) { - previous := errLog - defer func() { - errLog = previous - }() - - // set up logger - const expected = "prefix: test\n" - buffer := bytes.NewBuffer(make([]byte, 0, 64)) - logger := log.New(buffer, "prefix: ", 0) - - // print - SetLogger(logger) - errLog.Print("test") - - // check result - if actual := buffer.String(); actual != expected { - t.Errorf("expected %q, got %q", expected, actual) - } -} - -func TestErrorsStrictIgnoreNotes(t *testing.T) { - runTests(t, dsn+"&sql_notes=false", func(dbt *DBTest) { - dbt.mustExec("DROP TABLE IF EXISTS does_not_exist") - }) -} diff --git a/vendor/github.com/go-sql-driver/mysql/utils_test.go b/vendor/github.com/go-sql-driver/mysql/utils_test.go deleted file mode 100644 index 0d6c6684f280..000000000000 --- a/vendor/github.com/go-sql-driver/mysql/utils_test.go +++ /dev/null @@ -1,197 +0,0 @@ -// Go MySQL Driver - A MySQL-Driver for Go's database/sql package -// -// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. -// -// 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/. - -package mysql - -import ( - "bytes" - "encoding/binary" - "fmt" - "testing" - "time" -) - -func TestScanNullTime(t *testing.T) { - var scanTests = []struct { - in interface{} - error bool - valid bool - time time.Time - }{ - {tDate, false, true, tDate}, - {sDate, false, true, tDate}, - {[]byte(sDate), false, true, tDate}, - {tDateTime, false, true, tDateTime}, - {sDateTime, false, true, tDateTime}, - {[]byte(sDateTime), false, true, tDateTime}, - {tDate0, false, true, tDate0}, - {sDate0, false, true, tDate0}, - {[]byte(sDate0), false, true, tDate0}, - {sDateTime0, false, true, tDate0}, - {[]byte(sDateTime0), false, true, tDate0}, - {"", true, false, tDate0}, - {"1234", true, false, tDate0}, - {0, true, false, tDate0}, - } - - var nt = NullTime{} - var err error - - for _, tst := range scanTests { - err = nt.Scan(tst.in) - if (err != nil) != tst.error { - t.Errorf("%v: expected error status %t, got %t", tst.in, tst.error, (err != nil)) - } - if nt.Valid != tst.valid { - t.Errorf("%v: expected valid status %t, got %t", tst.in, tst.valid, nt.Valid) - } - if nt.Time != tst.time { - t.Errorf("%v: expected time %v, got %v", tst.in, tst.time, nt.Time) - } - } -} - -func TestLengthEncodedInteger(t *testing.T) { - var integerTests = []struct { - num uint64 - encoded []byte - }{ - {0x0000000000000000, []byte{0x00}}, - {0x0000000000000012, []byte{0x12}}, - {0x00000000000000fa, []byte{0xfa}}, - {0x0000000000000100, []byte{0xfc, 0x00, 0x01}}, - {0x0000000000001234, []byte{0xfc, 0x34, 0x12}}, - {0x000000000000ffff, []byte{0xfc, 0xff, 0xff}}, - {0x0000000000010000, []byte{0xfd, 0x00, 0x00, 0x01}}, - {0x0000000000123456, []byte{0xfd, 0x56, 0x34, 0x12}}, - {0x0000000000ffffff, []byte{0xfd, 0xff, 0xff, 0xff}}, - {0x0000000001000000, []byte{0xfe, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00}}, - {0x123456789abcdef0, []byte{0xfe, 0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12}}, - {0xffffffffffffffff, []byte{0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, - } - - for _, tst := range integerTests { - num, isNull, numLen := readLengthEncodedInteger(tst.encoded) - if isNull { - t.Errorf("%x: expected %d, got NULL", tst.encoded, tst.num) - } - if num != tst.num { - t.Errorf("%x: expected %d, got %d", tst.encoded, tst.num, num) - } - if numLen != len(tst.encoded) { - t.Errorf("%x: expected size %d, got %d", tst.encoded, len(tst.encoded), numLen) - } - encoded := appendLengthEncodedInteger(nil, num) - if !bytes.Equal(encoded, tst.encoded) { - t.Errorf("%v: expected %x, got %x", num, tst.encoded, encoded) - } - } -} - -func TestOldPass(t *testing.T) { - scramble := []byte{9, 8, 7, 6, 5, 4, 3, 2} - vectors := []struct { - pass string - out string - }{ - {" pass", "47575c5a435b4251"}, - {"pass ", "47575c5a435b4251"}, - {"123\t456", "575c47505b5b5559"}, - {"C0mpl!ca ted#PASS123", "5d5d554849584a45"}, - } - for _, tuple := range vectors { - ours := scrambleOldPassword(scramble, []byte(tuple.pass)) - if tuple.out != fmt.Sprintf("%x", ours) { - t.Errorf("Failed old password %q", tuple.pass) - } - } -} - -func TestFormatBinaryDateTime(t *testing.T) { - rawDate := [11]byte{} - binary.LittleEndian.PutUint16(rawDate[:2], 1978) // years - rawDate[2] = 12 // months - rawDate[3] = 30 // days - rawDate[4] = 15 // hours - rawDate[5] = 46 // minutes - rawDate[6] = 23 // seconds - binary.LittleEndian.PutUint32(rawDate[7:], 987654) // microseconds - expect := func(expected string, inlen, outlen uint8) { - actual, _ := formatBinaryDateTime(rawDate[:inlen], outlen, false) - bytes, ok := actual.([]byte) - if !ok { - t.Errorf("formatBinaryDateTime must return []byte, was %T", actual) - } - if string(bytes) != expected { - t.Errorf( - "expected %q, got %q for length in %d, out %d", - bytes, actual, inlen, outlen, - ) - } - } - expect("0000-00-00", 0, 10) - expect("0000-00-00 00:00:00", 0, 19) - expect("1978-12-30", 4, 10) - expect("1978-12-30 15:46:23", 7, 19) - expect("1978-12-30 15:46:23.987654", 11, 26) -} - -func TestEscapeBackslash(t *testing.T) { - expect := func(expected, value string) { - actual := string(escapeBytesBackslash([]byte{}, []byte(value))) - if actual != expected { - t.Errorf( - "expected %s, got %s", - expected, actual, - ) - } - - actual = string(escapeStringBackslash([]byte{}, value)) - if actual != expected { - t.Errorf( - "expected %s, got %s", - expected, actual, - ) - } - } - - expect("foo\\0bar", "foo\x00bar") - expect("foo\\nbar", "foo\nbar") - expect("foo\\rbar", "foo\rbar") - expect("foo\\Zbar", "foo\x1abar") - expect("foo\\\"bar", "foo\"bar") - expect("foo\\\\bar", "foo\\bar") - expect("foo\\'bar", "foo'bar") -} - -func TestEscapeQuotes(t *testing.T) { - expect := func(expected, value string) { - actual := string(escapeBytesQuotes([]byte{}, []byte(value))) - if actual != expected { - t.Errorf( - "expected %s, got %s", - expected, actual, - ) - } - - actual = string(escapeStringQuotes([]byte{}, value)) - if actual != expected { - t.Errorf( - "expected %s, got %s", - expected, actual, - ) - } - } - - expect("foo\x00bar", "foo\x00bar") // not affected - expect("foo\nbar", "foo\nbar") // not affected - expect("foo\rbar", "foo\rbar") // not affected - expect("foo\x1abar", "foo\x1abar") // not affected - expect("foo''bar", "foo'bar") // affected - expect("foo\"bar", "foo\"bar") // not affected -} diff --git a/vendor/github.com/golang/glog/BUILD b/vendor/github.com/golang/glog/BUILD index cc600c860289..aaf7a33eb001 100644 --- a/vendor/github.com/golang/glog/BUILD +++ b/vendor/github.com/golang/glog/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -10,13 +10,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = ["glog_test.go"], - importpath = "github.com/golang/glog", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/golang/glog/glog_test.go b/vendor/github.com/golang/glog/glog_test.go deleted file mode 100644 index 0fb376e1fde8..000000000000 --- a/vendor/github.com/golang/glog/glog_test.go +++ /dev/null @@ -1,415 +0,0 @@ -// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ -// -// Copyright 2013 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package glog - -import ( - "bytes" - "fmt" - stdLog "log" - "path/filepath" - "runtime" - "strconv" - "strings" - "testing" - "time" -) - -// Test that shortHostname works as advertised. -func TestShortHostname(t *testing.T) { - for hostname, expect := range map[string]string{ - "": "", - "host": "host", - "host.google.com": "host", - } { - if got := shortHostname(hostname); expect != got { - t.Errorf("shortHostname(%q): expected %q, got %q", hostname, expect, got) - } - } -} - -// flushBuffer wraps a bytes.Buffer to satisfy flushSyncWriter. -type flushBuffer struct { - bytes.Buffer -} - -func (f *flushBuffer) Flush() error { - return nil -} - -func (f *flushBuffer) Sync() error { - return nil -} - -// swap sets the log writers and returns the old array. -func (l *loggingT) swap(writers [numSeverity]flushSyncWriter) (old [numSeverity]flushSyncWriter) { - l.mu.Lock() - defer l.mu.Unlock() - old = l.file - for i, w := range writers { - logging.file[i] = w - } - return -} - -// newBuffers sets the log writers to all new byte buffers and returns the old array. -func (l *loggingT) newBuffers() [numSeverity]flushSyncWriter { - return l.swap([numSeverity]flushSyncWriter{new(flushBuffer), new(flushBuffer), new(flushBuffer), new(flushBuffer)}) -} - -// contents returns the specified log value as a string. -func contents(s severity) string { - return logging.file[s].(*flushBuffer).String() -} - -// contains reports whether the string is contained in the log. -func contains(s severity, str string, t *testing.T) bool { - return strings.Contains(contents(s), str) -} - -// setFlags configures the logging flags how the test expects them. -func setFlags() { - logging.toStderr = false -} - -// Test that Info works as advertised. -func TestInfo(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - Info("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -func TestInfoDepth(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - - f := func() { InfoDepth(1, "depth-test1") } - - // The next three lines must stay together - _, _, wantLine, _ := runtime.Caller(0) - InfoDepth(0, "depth-test0") - f() - - msgs := strings.Split(strings.TrimSuffix(contents(infoLog), "\n"), "\n") - if len(msgs) != 2 { - t.Fatalf("Got %d lines, expected 2", len(msgs)) - } - - for i, m := range msgs { - if !strings.HasPrefix(m, "I") { - t.Errorf("InfoDepth[%d] has wrong character: %q", i, m) - } - w := fmt.Sprintf("depth-test%d", i) - if !strings.Contains(m, w) { - t.Errorf("InfoDepth[%d] missing %q: %q", i, w, m) - } - - // pull out the line number (between : and ]) - msg := m[strings.LastIndex(m, ":")+1:] - x := strings.Index(msg, "]") - if x < 0 { - t.Errorf("InfoDepth[%d]: missing ']': %q", i, m) - continue - } - line, err := strconv.Atoi(msg[:x]) - if err != nil { - t.Errorf("InfoDepth[%d]: bad line number: %q", i, m) - continue - } - wantLine++ - if wantLine != line { - t.Errorf("InfoDepth[%d]: got line %d, want %d", i, line, wantLine) - } - } -} - -func init() { - CopyStandardLogTo("INFO") -} - -// Test that CopyStandardLogTo panics on bad input. -func TestCopyStandardLogToPanic(t *testing.T) { - defer func() { - if s, ok := recover().(string); !ok || !strings.Contains(s, "LOG") { - t.Errorf(`CopyStandardLogTo("LOG") should have panicked: %v`, s) - } - }() - CopyStandardLogTo("LOG") -} - -// Test that using the standard log package logs to INFO. -func TestStandardLog(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - stdLog.Print("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -// Test that the header has the correct format. -func TestHeader(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - defer func(previous func() time.Time) { timeNow = previous }(timeNow) - timeNow = func() time.Time { - return time.Date(2006, 1, 2, 15, 4, 5, .067890e9, time.Local) - } - pid = 1234 - Info("test") - var line int - format := "I0102 15:04:05.067890 1234 glog_test.go:%d] test\n" - n, err := fmt.Sscanf(contents(infoLog), format, &line) - if n != 1 || err != nil { - t.Errorf("log format error: %d elements, error %s:\n%s", n, err, contents(infoLog)) - } - // Scanf treats multiple spaces as equivalent to a single space, - // so check for correct space-padding also. - want := fmt.Sprintf(format, line) - if contents(infoLog) != want { - t.Errorf("log format error: got:\n\t%q\nwant:\t%q", contents(infoLog), want) - } -} - -// Test that an Error log goes to Warning and Info. -// Even in the Info log, the source character will be E, so the data should -// all be identical. -func TestError(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - Error("test") - if !contains(errorLog, "E", t) { - t.Errorf("Error has wrong character: %q", contents(errorLog)) - } - if !contains(errorLog, "test", t) { - t.Error("Error failed") - } - str := contents(errorLog) - if !contains(warningLog, str, t) { - t.Error("Warning failed") - } - if !contains(infoLog, str, t) { - t.Error("Info failed") - } -} - -// Test that a Warning log goes to Info. -// Even in the Info log, the source character will be W, so the data should -// all be identical. -func TestWarning(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - Warning("test") - if !contains(warningLog, "W", t) { - t.Errorf("Warning has wrong character: %q", contents(warningLog)) - } - if !contains(warningLog, "test", t) { - t.Error("Warning failed") - } - str := contents(warningLog) - if !contains(infoLog, str, t) { - t.Error("Info failed") - } -} - -// Test that a V log goes to Info. -func TestV(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - logging.verbosity.Set("2") - defer logging.verbosity.Set("0") - V(2).Info("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -// Test that a vmodule enables a log in this file. -func TestVmoduleOn(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - logging.vmodule.Set("glog_test=2") - defer logging.vmodule.Set("") - if !V(1) { - t.Error("V not enabled for 1") - } - if !V(2) { - t.Error("V not enabled for 2") - } - if V(3) { - t.Error("V enabled for 3") - } - V(2).Info("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -// Test that a vmodule of another file does not enable a log in this file. -func TestVmoduleOff(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - logging.vmodule.Set("notthisfile=2") - defer logging.vmodule.Set("") - for i := 1; i <= 3; i++ { - if V(Level(i)) { - t.Errorf("V enabled for %d", i) - } - } - V(2).Info("test") - if contents(infoLog) != "" { - t.Error("V logged incorrectly") - } -} - -// vGlobs are patterns that match/don't match this file at V=2. -var vGlobs = map[string]bool{ - // Easy to test the numeric match here. - "glog_test=1": false, // If -vmodule sets V to 1, V(2) will fail. - "glog_test=2": true, - "glog_test=3": true, // If -vmodule sets V to 1, V(3) will succeed. - // These all use 2 and check the patterns. All are true. - "*=2": true, - "?l*=2": true, - "????_*=2": true, - "??[mno]?_*t=2": true, - // These all use 2 and check the patterns. All are false. - "*x=2": false, - "m*=2": false, - "??_*=2": false, - "?[abc]?_*t=2": false, -} - -// Test that vmodule globbing works as advertised. -func testVmoduleGlob(pat string, match bool, t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - defer logging.vmodule.Set("") - logging.vmodule.Set(pat) - if V(2) != Verbose(match) { - t.Errorf("incorrect match for %q: got %t expected %t", pat, V(2), match) - } -} - -// Test that a vmodule globbing works as advertised. -func TestVmoduleGlob(t *testing.T) { - for glob, match := range vGlobs { - testVmoduleGlob(glob, match, t) - } -} - -func TestRollover(t *testing.T) { - setFlags() - var err error - defer func(previous func(error)) { logExitFunc = previous }(logExitFunc) - logExitFunc = func(e error) { - err = e - } - defer func(previous uint64) { MaxSize = previous }(MaxSize) - MaxSize = 512 - - Info("x") // Be sure we have a file. - info, ok := logging.file[infoLog].(*syncBuffer) - if !ok { - t.Fatal("info wasn't created") - } - if err != nil { - t.Fatalf("info has initial error: %v", err) - } - fname0 := info.file.Name() - Info(strings.Repeat("x", int(MaxSize))) // force a rollover - if err != nil { - t.Fatalf("info has error after big write: %v", err) - } - - // Make sure the next log file gets a file name with a different - // time stamp. - // - // TODO: determine whether we need to support subsecond log - // rotation. C++ does not appear to handle this case (nor does it - // handle Daylight Savings Time properly). - time.Sleep(1 * time.Second) - - Info("x") // create a new file - if err != nil { - t.Fatalf("error after rotation: %v", err) - } - fname1 := info.file.Name() - if fname0 == fname1 { - t.Errorf("info.f.Name did not change: %v", fname0) - } - if info.nbytes >= MaxSize { - t.Errorf("file size was not reset: %d", info.nbytes) - } -} - -func TestLogBacktraceAt(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - // The peculiar style of this code simplifies line counting and maintenance of the - // tracing block below. - var infoLine string - setTraceLocation := func(file string, line int, ok bool, delta int) { - if !ok { - t.Fatal("could not get file:line") - } - _, file = filepath.Split(file) - infoLine = fmt.Sprintf("%s:%d", file, line+delta) - err := logging.traceLocation.Set(infoLine) - if err != nil { - t.Fatal("error setting log_backtrace_at: ", err) - } - } - { - // Start of tracing block. These lines know about each other's relative position. - _, file, line, ok := runtime.Caller(0) - setTraceLocation(file, line, ok, +2) // Two lines between Caller and Info calls. - Info("we want a stack trace here") - } - numAppearances := strings.Count(contents(infoLog), infoLine) - if numAppearances < 2 { - // Need 2 appearances, one in the log header and one in the trace: - // log_test.go:281: I0511 16:36:06.952398 02238 log_test.go:280] we want a stack trace here - // ... - // github.com/glog/glog_test.go:280 (0x41ba91) - // ... - // We could be more precise but that would require knowing the details - // of the traceback format, which may not be dependable. - t.Fatal("got no trace back; log is ", contents(infoLog)) - } -} - -func BenchmarkHeader(b *testing.B) { - for i := 0; i < b.N; i++ { - buf, _, _ := logging.header(infoLog, 0) - logging.putBuffer(buf) - } -} diff --git a/vendor/github.com/golang/lint/BUILD b/vendor/github.com/golang/lint/BUILD index 608fa33a497c..5d181f74866f 100644 --- a/vendor/github.com/golang/lint/BUILD +++ b/vendor/github.com/golang/lint/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -8,13 +8,6 @@ go_library( deps = ["//vendor/golang.org/x/tools/go/gcexportdata:go_default_library"], ) -go_test( - name = "go_default_test", - srcs = ["lint_test.go"], - importpath = "github.com/golang/lint", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/golang/lint/lint_test.go b/vendor/github.com/golang/lint/lint_test.go deleted file mode 100644 index 92db5968e4d6..000000000000 --- a/vendor/github.com/golang/lint/lint_test.go +++ /dev/null @@ -1,317 +0,0 @@ -// Copyright (c) 2013 The Go Authors. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file or at -// https://developers.google.com/open-source/licenses/bsd. - -package lint - -import ( - "bytes" - "flag" - "fmt" - "go/ast" - "go/parser" - "go/printer" - "go/token" - "go/types" - "io/ioutil" - "path" - "regexp" - "strconv" - "strings" - "testing" -) - -var lintMatch = flag.String("lint.match", "", "restrict testdata matches to this pattern") - -func TestAll(t *testing.T) { - l := new(Linter) - rx, err := regexp.Compile(*lintMatch) - if err != nil { - t.Fatalf("Bad -lint.match value %q: %v", *lintMatch, err) - } - - baseDir := "testdata" - fis, err := ioutil.ReadDir(baseDir) - if err != nil { - t.Fatalf("ioutil.ReadDir: %v", err) - } - if len(fis) == 0 { - t.Fatalf("no files in %v", baseDir) - } - for _, fi := range fis { - if !rx.MatchString(fi.Name()) { - continue - } - //t.Logf("Testing %s", fi.Name()) - src, err := ioutil.ReadFile(path.Join(baseDir, fi.Name())) - if err != nil { - t.Fatalf("Failed reading %s: %v", fi.Name(), err) - } - - ins := parseInstructions(t, fi.Name(), src) - if ins == nil { - t.Errorf("Test file %v does not have instructions", fi.Name()) - continue - } - - ps, err := l.Lint(fi.Name(), src) - if err != nil { - t.Errorf("Linting %s: %v", fi.Name(), err) - continue - } - - for _, in := range ins { - ok := false - for i, p := range ps { - if p.Position.Line != in.Line { - continue - } - if in.Match.MatchString(p.Text) { - // check replacement if we are expecting one - if in.Replacement != "" { - // ignore any inline comments, since that would be recursive - r := p.ReplacementLine - if i := strings.Index(r, " //"); i >= 0 { - r = r[:i] - } - if r != in.Replacement { - t.Errorf("Lint failed at %s:%d; got replacement %q, want %q", fi.Name(), in.Line, r, in.Replacement) - } - } - - // remove this problem from ps - copy(ps[i:], ps[i+1:]) - ps = ps[:len(ps)-1] - - //t.Logf("/%v/ matched at %s:%d", in.Match, fi.Name(), in.Line) - ok = true - break - } - } - if !ok { - t.Errorf("Lint failed at %s:%d; /%v/ did not match", fi.Name(), in.Line, in.Match) - } - } - for _, p := range ps { - t.Errorf("Unexpected problem at %s:%d: %v", fi.Name(), p.Position.Line, p.Text) - } - } -} - -type instruction struct { - Line int // the line number this applies to - Match *regexp.Regexp // what pattern to match - Replacement string // what the suggested replacement line should be -} - -// parseInstructions parses instructions from the comments in a Go source file. -// It returns nil if none were parsed. -func parseInstructions(t *testing.T, filename string, src []byte) []instruction { - fset := token.NewFileSet() - f, err := parser.ParseFile(fset, filename, src, parser.ParseComments) - if err != nil { - t.Fatalf("Test file %v does not parse: %v", filename, err) - } - var ins []instruction - for _, cg := range f.Comments { - ln := fset.Position(cg.Pos()).Line - raw := cg.Text() - for _, line := range strings.Split(raw, "\n") { - if line == "" || strings.HasPrefix(line, "#") { - continue - } - if line == "OK" && ins == nil { - // so our return value will be non-nil - ins = make([]instruction, 0) - continue - } - if strings.Contains(line, "MATCH") { - rx, err := extractPattern(line) - if err != nil { - t.Fatalf("At %v:%d: %v", filename, ln, err) - } - matchLine := ln - if i := strings.Index(line, "MATCH:"); i >= 0 { - // This is a match for a different line. - lns := strings.TrimPrefix(line[i:], "MATCH:") - lns = lns[:strings.Index(lns, " ")] - matchLine, err = strconv.Atoi(lns) - if err != nil { - t.Fatalf("Bad match line number %q at %v:%d: %v", lns, filename, ln, err) - } - } - var repl string - if r, ok := extractReplacement(line); ok { - repl = r - } - ins = append(ins, instruction{ - Line: matchLine, - Match: rx, - Replacement: repl, - }) - } - } - } - return ins -} - -func extractPattern(line string) (*regexp.Regexp, error) { - a, b := strings.Index(line, "/"), strings.LastIndex(line, "/") - if a == -1 || a == b { - return nil, fmt.Errorf("malformed match instruction %q", line) - } - pat := line[a+1 : b] - rx, err := regexp.Compile(pat) - if err != nil { - return nil, fmt.Errorf("bad match pattern %q: %v", pat, err) - } - return rx, nil -} - -func extractReplacement(line string) (string, bool) { - // Look for this: / -> ` - // (the end of a match and start of a backtick string), - // and then the closing backtick. - const start = "/ -> `" - a, b := strings.Index(line, start), strings.LastIndex(line, "`") - if a < 0 || a > b { - return "", false - } - return line[a+len(start) : b], true -} - -func render(fset *token.FileSet, x interface{}) string { - var buf bytes.Buffer - if err := printer.Fprint(&buf, fset, x); err != nil { - panic(err) - } - return buf.String() -} - -func TestLine(t *testing.T) { - tests := []struct { - src string - offset int - want string - }{ - {"single line file", 5, "single line file"}, - {"single line file with newline\n", 5, "single line file with newline\n"}, - {"first\nsecond\nthird\n", 2, "first\n"}, - {"first\nsecond\nthird\n", 9, "second\n"}, - {"first\nsecond\nthird\n", 14, "third\n"}, - {"first\nsecond\nthird with no newline", 16, "third with no newline"}, - {"first byte\n", 0, "first byte\n"}, - } - for _, test := range tests { - got := srcLine([]byte(test.src), token.Position{Offset: test.offset}) - if got != test.want { - t.Errorf("srcLine(%q, offset=%d) = %q, want %q", test.src, test.offset, got, test.want) - } - } -} - -func TestLintName(t *testing.T) { - tests := []struct { - name, want string - }{ - {"foo_bar", "fooBar"}, - {"foo_bar_baz", "fooBarBaz"}, - {"Foo_bar", "FooBar"}, - {"foo_WiFi", "fooWiFi"}, - {"id", "id"}, - {"Id", "ID"}, - {"foo_id", "fooID"}, - {"fooId", "fooID"}, - {"fooUid", "fooUID"}, - {"idFoo", "idFoo"}, - {"uidFoo", "uidFoo"}, - {"midIdDle", "midIDDle"}, - {"APIProxy", "APIProxy"}, - {"ApiProxy", "APIProxy"}, - {"apiProxy", "apiProxy"}, - {"_Leading", "_Leading"}, - {"___Leading", "_Leading"}, - {"trailing_", "trailing"}, - {"trailing___", "trailing"}, - {"a_b", "aB"}, - {"a__b", "aB"}, - {"a___b", "aB"}, - {"Rpc1150", "RPC1150"}, - {"case3_1", "case3_1"}, - {"case3__1", "case3_1"}, - {"IEEE802_16bit", "IEEE802_16bit"}, - {"IEEE802_16Bit", "IEEE802_16Bit"}, - } - for _, test := range tests { - got := lintName(test.name) - if got != test.want { - t.Errorf("lintName(%q) = %q, want %q", test.name, got, test.want) - } - } -} - -func TestExportedType(t *testing.T) { - tests := []struct { - typString string - exp bool - }{ - {"int", true}, - {"string", false}, // references the shadowed builtin "string" - {"T", true}, - {"t", false}, - {"*T", true}, - {"*t", false}, - {"map[int]complex128", true}, - } - for _, test := range tests { - src := `package foo; type T int; type t int; type string struct{}` - fset := token.NewFileSet() - file, err := parser.ParseFile(fset, "foo.go", src, 0) - if err != nil { - t.Fatalf("Parsing %q: %v", src, err) - } - // use the package name as package path - config := &types.Config{} - pkg, err := config.Check(file.Name.Name, fset, []*ast.File{file}, nil) - if err != nil { - t.Fatalf("Type checking %q: %v", src, err) - } - tv, err := types.Eval(fset, pkg, token.NoPos, test.typString) - if err != nil { - t.Errorf("types.Eval(%q): %v", test.typString, err) - continue - } - if got := exportedType(tv.Type); got != test.exp { - t.Errorf("exportedType(%v) = %t, want %t", tv.Type, got, test.exp) - } - } -} - -func TestIsGenerated(t *testing.T) { - tests := []struct { - source string - generated bool - }{ - {"// Code Generated by some tool. DO NOT EDIT.", false}, - {"// Code generated by some tool. DO NOT EDIT.", true}, - {"// Code generated by some tool. DO NOT EDIT", false}, - {"// Code generated DO NOT EDIT.", true}, - {"// Code generated DO NOT EDIT.", false}, - {"\t\t// Code generated by some tool. DO NOT EDIT.\npackage foo\n", false}, - {"// Code generated by some tool. DO NOT EDIT.\npackage foo\n", true}, - {"package foo\n// Code generated by some tool. DO NOT EDIT.\ntype foo int\n", true}, - {"package foo\n // Code generated by some tool. DO NOT EDIT.\ntype foo int\n", false}, - {"package foo\n// Code generated by some tool. DO NOT EDIT. \ntype foo int\n", false}, - {"package foo\ntype foo int\n// Code generated by some tool. DO NOT EDIT.\n", true}, - {"package foo\ntype foo int\n// Code generated by some tool. DO NOT EDIT.", true}, - } - - for i, test := range tests { - got := isGenerated([]byte(test.source)) - if got != test.generated { - t.Errorf("test %d, isGenerated() = %v, want %v", i, got, test.generated) - } - } -} diff --git a/vendor/github.com/golang/mock/gomock/BUILD b/vendor/github.com/golang/mock/gomock/BUILD index cd0d4db0f8c5..4c934050230d 100644 --- a/vendor/github.com/golang/mock/gomock/BUILD +++ b/vendor/github.com/golang/mock/gomock/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -12,19 +12,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_xtest", - srcs = [ - "controller_test.go", - "matchers_test.go", - ], - importpath = "github.com/golang/mock/gomock_test", - deps = [ - ":go_default_library", - "//vendor/github.com/golang/mock/gomock/mock_matcher:go_default_library", - ], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/golang/mock/gomock/controller_test.go b/vendor/github.com/golang/mock/gomock/controller_test.go deleted file mode 100644 index ac5204f807d2..000000000000 --- a/vendor/github.com/golang/mock/gomock/controller_test.go +++ /dev/null @@ -1,475 +0,0 @@ -// Copyright 2011 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package gomock_test - -import ( - "fmt" - "reflect" - "testing" - - "github.com/golang/mock/gomock" -) - -type ErrorReporter struct { - t *testing.T - log []string - failed bool - fatalToken struct{} -} - -func NewErrorReporter(t *testing.T) *ErrorReporter { - return &ErrorReporter{t: t} -} - -func (e *ErrorReporter) reportLog() { - for _, entry := range e.log { - e.t.Log(entry) - } -} - -func (e *ErrorReporter) assertPass(msg string) { - if e.failed { - e.t.Errorf("Expected pass, but got failure(s): %s", msg) - e.reportLog() - } -} - -func (e *ErrorReporter) assertFail(msg string) { - if !e.failed { - e.t.Error("Expected failure, but got pass: %s", msg) - } -} - -// Use to check that code triggers a fatal test failure. -func (e *ErrorReporter) assertFatal(fn func()) { - defer func() { - err := recover() - if err == nil { - var actual string - if e.failed { - actual = "non-fatal failure" - } else { - actual = "pass" - } - e.t.Error("Expected fatal failure, but got a", actual) - } else if token, ok := err.(*struct{}); ok && token == &e.fatalToken { - // This is okay - the panic is from Fatalf(). - return - } else { - // Some other panic. - panic(err) - } - }() - - fn() -} - -// recoverUnexpectedFatal can be used as a deferred call in test cases to -// recover from and display a call to ErrorReporter.Fatalf(). -func (e *ErrorReporter) recoverUnexpectedFatal() { - err := recover() - if err == nil { - // No panic. - } else if token, ok := err.(*struct{}); ok && token == &e.fatalToken { - // Unexpected fatal error happened. - e.t.Error("Got unexpected fatal error(s). All errors up to this point:") - e.reportLog() - return - } else { - // Some other panic. - panic(err) - } -} - -func (e *ErrorReporter) Logf(format string, args ...interface{}) { - e.log = append(e.log, fmt.Sprintf(format, args...)) -} - -func (e *ErrorReporter) Errorf(format string, args ...interface{}) { - e.Logf(format, args...) - e.failed = true -} - -func (e *ErrorReporter) Fatalf(format string, args ...interface{}) { - e.Logf(format, args...) - e.failed = true - panic(&e.fatalToken) -} - -// A type purely for use as a receiver in testing the Controller. -type Subject struct{} - -func (s *Subject) FooMethod(arg string) int { - return 0 -} - -func (s *Subject) BarMethod(arg string) int { - return 0 -} - -func assertEqual(t *testing.T, expected interface{}, actual interface{}) { - if !reflect.DeepEqual(expected, actual) { - t.Error("Expected %+v, but got %+v", expected, actual) - } -} - -func createFixtures(t *testing.T) (reporter *ErrorReporter, ctrl *gomock.Controller) { - // reporter acts as a testing.T-like object that we pass to the - // Controller. We use it to test that the mock considered tests - // successful or failed. - reporter = NewErrorReporter(t) - ctrl = gomock.NewController(reporter) - return -} - -func TestNoCalls(t *testing.T) { - reporter, ctrl := createFixtures(t) - ctrl.Finish() - reporter.assertPass("No calls expected or made.") -} - -func TestExpectedMethodCall(t *testing.T) { - reporter, ctrl := createFixtures(t) - subject := new(Subject) - - ctrl.RecordCall(subject, "FooMethod", "argument") - ctrl.Call(subject, "FooMethod", "argument") - ctrl.Finish() - - reporter.assertPass("Expected method call made.") -} - -func TestUnexpectedMethodCall(t *testing.T) { - reporter, ctrl := createFixtures(t) - subject := new(Subject) - - reporter.assertFatal(func() { - ctrl.Call(subject, "FooMethod", "argument") - }) - - ctrl.Finish() -} - -func TestRepeatedCall(t *testing.T) { - reporter, ctrl := createFixtures(t) - subject := new(Subject) - - ctrl.RecordCall(subject, "FooMethod", "argument").Times(3) - ctrl.Call(subject, "FooMethod", "argument") - ctrl.Call(subject, "FooMethod", "argument") - ctrl.Call(subject, "FooMethod", "argument") - reporter.assertPass("After expected repeated method calls.") - reporter.assertFatal(func() { - ctrl.Call(subject, "FooMethod", "argument") - }) - ctrl.Finish() - reporter.assertFail("After calling one too many times.") -} - -func TestUnexpectedArgCount(t *testing.T) { - reporter, ctrl := createFixtures(t) - defer reporter.recoverUnexpectedFatal() - subject := new(Subject) - - ctrl.RecordCall(subject, "FooMethod", "argument") - reporter.assertFatal(func() { - // This call is made with the wrong number of arguments... - ctrl.Call(subject, "FooMethod", "argument", "extra_argument") - }) - reporter.assertFatal(func() { - // ... so is this. - ctrl.Call(subject, "FooMethod") - }) - reporter.assertFatal(func() { - // The expected call wasn't made. - ctrl.Finish() - }) -} - -func TestAnyTimes(t *testing.T) { - reporter, ctrl := createFixtures(t) - subject := new(Subject) - - ctrl.RecordCall(subject, "FooMethod", "argument").AnyTimes() - for i := 0; i < 100; i++ { - ctrl.Call(subject, "FooMethod", "argument") - } - reporter.assertPass("After 100 method calls.") - ctrl.Finish() -} - -func TestMinTimes1(t *testing.T) { - // It fails if there are no calls - reporter, ctrl := createFixtures(t) - subject := new(Subject) - ctrl.RecordCall(subject, "FooMethod", "argument").MinTimes(1) - reporter.assertFatal(func() { - ctrl.Finish() - }) - - // It succeeds if there is one call - reporter, ctrl = createFixtures(t) - subject = new(Subject) - ctrl.RecordCall(subject, "FooMethod", "argument").MinTimes(1) - ctrl.Call(subject, "FooMethod", "argument") - ctrl.Finish() - - // It succeeds if there are many calls - reporter, ctrl = createFixtures(t) - subject = new(Subject) - ctrl.RecordCall(subject, "FooMethod", "argument").MinTimes(1) - for i := 0; i < 100; i++ { - ctrl.Call(subject, "FooMethod", "argument") - } - ctrl.Finish() -} - -func TestMaxTimes1(t *testing.T) { - // It succeeds if there are no calls - _, ctrl := createFixtures(t) - subject := new(Subject) - ctrl.RecordCall(subject, "FooMethod", "argument").MaxTimes(1) - ctrl.Finish() - - // It succeeds if there is one call - _, ctrl = createFixtures(t) - subject = new(Subject) - ctrl.RecordCall(subject, "FooMethod", "argument").MaxTimes(1) - ctrl.Call(subject, "FooMethod", "argument") - ctrl.Finish() - - //It fails if there are more - reporter, ctrl := createFixtures(t) - subject = new(Subject) - ctrl.RecordCall(subject, "FooMethod", "argument").MaxTimes(1) - ctrl.Call(subject, "FooMethod", "argument") - reporter.assertFatal(func() { - ctrl.Call(subject, "FooMethod", "argument") - }) - ctrl.Finish() -} - -func TestMinMaxTimes(t *testing.T) { - // It fails if there are less calls than specified - reporter, ctrl := createFixtures(t) - subject := new(Subject) - ctrl.RecordCall(subject, "FooMethod", "argument").MinTimes(2).MaxTimes(2) - ctrl.Call(subject, "FooMethod", "argument") - reporter.assertFatal(func() { - ctrl.Finish() - }) - - // It fails if there are more calls than specified - reporter, ctrl = createFixtures(t) - subject = new(Subject) - ctrl.RecordCall(subject, "FooMethod", "argument").MinTimes(2).MaxTimes(2) - ctrl.Call(subject, "FooMethod", "argument") - ctrl.Call(subject, "FooMethod", "argument") - reporter.assertFatal(func() { - ctrl.Call(subject, "FooMethod", "argument") - }) - - // It succeeds if there is just the right number of calls - reporter, ctrl = createFixtures(t) - subject = new(Subject) - ctrl.RecordCall(subject, "FooMethod", "argument").MaxTimes(2).MinTimes(2) - ctrl.Call(subject, "FooMethod", "argument") - ctrl.Call(subject, "FooMethod", "argument") - ctrl.Finish() -} - -func TestDo(t *testing.T) { - _, ctrl := createFixtures(t) - subject := new(Subject) - - doCalled := false - var argument string - ctrl.RecordCall(subject, "FooMethod", "argument").Do( - func(arg string) { - doCalled = true - argument = arg - }) - if doCalled { - t.Error("Do() callback called too early.") - } - - ctrl.Call(subject, "FooMethod", "argument") - - if !doCalled { - t.Error("Do() callback not called.") - } - if "argument" != argument { - t.Error("Do callback received wrong argument.") - } - - ctrl.Finish() -} - -func TestReturn(t *testing.T) { - _, ctrl := createFixtures(t) - subject := new(Subject) - - // Unspecified return should produce "zero" result. - ctrl.RecordCall(subject, "FooMethod", "zero") - ctrl.RecordCall(subject, "FooMethod", "five").Return(5) - - assertEqual( - t, - []interface{}{0}, - ctrl.Call(subject, "FooMethod", "zero")) - - assertEqual( - t, - []interface{}{5}, - ctrl.Call(subject, "FooMethod", "five")) - ctrl.Finish() -} - -func TestUnorderedCalls(t *testing.T) { - reporter, ctrl := createFixtures(t) - defer reporter.recoverUnexpectedFatal() - subjectTwo := new(Subject) - subjectOne := new(Subject) - - ctrl.RecordCall(subjectOne, "FooMethod", "1") - ctrl.RecordCall(subjectOne, "BarMethod", "2") - ctrl.RecordCall(subjectTwo, "FooMethod", "3") - ctrl.RecordCall(subjectTwo, "BarMethod", "4") - - // Make the calls in a different order, which should be fine. - ctrl.Call(subjectOne, "BarMethod", "2") - ctrl.Call(subjectTwo, "FooMethod", "3") - ctrl.Call(subjectTwo, "BarMethod", "4") - ctrl.Call(subjectOne, "FooMethod", "1") - - reporter.assertPass("After making all calls in different order") - - ctrl.Finish() - - reporter.assertPass("After finish") -} - -func commonTestOrderedCalls(t *testing.T) (reporter *ErrorReporter, ctrl *gomock.Controller, subjectOne, subjectTwo *Subject) { - reporter, ctrl = createFixtures(t) - - subjectOne = new(Subject) - subjectTwo = new(Subject) - - gomock.InOrder( - ctrl.RecordCall(subjectOne, "FooMethod", "1").AnyTimes(), - ctrl.RecordCall(subjectTwo, "FooMethod", "2"), - ctrl.RecordCall(subjectTwo, "BarMethod", "3"), - ) - - return -} - -func TestOrderedCallsCorrect(t *testing.T) { - reporter, ctrl, subjectOne, subjectTwo := commonTestOrderedCalls(t) - - ctrl.Call(subjectOne, "FooMethod", "1") - ctrl.Call(subjectTwo, "FooMethod", "2") - ctrl.Call(subjectTwo, "BarMethod", "3") - - ctrl.Finish() - - reporter.assertPass("After finish") -} - -func TestOrderedCallsInCorrect(t *testing.T) { - reporter, ctrl, subjectOne, subjectTwo := commonTestOrderedCalls(t) - - ctrl.Call(subjectOne, "FooMethod", "1") - reporter.assertFatal(func() { - ctrl.Call(subjectTwo, "BarMethod", "3") - }) -} - -// Test that calls that are prerequites to other calls but have maxCalls > -// minCalls are removed from the expected call set. -func TestOrderedCallsWithPreReqMaxUnbounded(t *testing.T) { - reporter, ctrl, subjectOne, subjectTwo := commonTestOrderedCalls(t) - - // Initially we should be able to call FooMethod("1") as many times as we - // want. - ctrl.Call(subjectOne, "FooMethod", "1") - ctrl.Call(subjectOne, "FooMethod", "1") - - // But calling something that has it as a prerequite should remove it from - // the expected call set. This allows tests to ensure that FooMethod("1") is - // *not* called after FooMethod("2"). - ctrl.Call(subjectTwo, "FooMethod", "2") - - // Therefore this call should fail: - reporter.assertFatal(func() { - ctrl.Call(subjectOne, "FooMethod", "1") - }) -} - -func TestCallAfterLoopPanic(t *testing.T) { - _, ctrl := createFixtures(t) - - subject := new(Subject) - - firstCall := ctrl.RecordCall(subject, "Foo", "1") - secondCall := ctrl.RecordCall(subject, "Foo", "2") - thirdCall := ctrl.RecordCall(subject, "Foo", "3") - - gomock.InOrder(firstCall, secondCall, thirdCall) - - defer func() { - err := recover() - if err == nil { - t.Error("Call.After creation of dependency loop did not panic.") - } - }() - - // This should panic due to dependency loop. - firstCall.After(thirdCall) -} - -func TestPanicOverridesExpectationChecks(t *testing.T) { - ctrl := gomock.NewController(t) - reporter := NewErrorReporter(t) - - reporter.assertFatal(func() { - ctrl.RecordCall(new(Subject), "FooMethod", "1") - defer ctrl.Finish() - reporter.Fatalf("Intentional panic") - }) -} - -func TestSetArgWithBadType(t *testing.T) { - rep, ctrl := createFixtures(t) - defer ctrl.Finish() - - s := new(Subject) - // This should catch a type error: - rep.assertFatal(func() { - ctrl.RecordCall(s, "FooMethod", "1").SetArg(0, "blah") - }) - ctrl.Call(s, "FooMethod", "1") -} - -func TestTimes0(t *testing.T) { - rep, ctrl := createFixtures(t) - defer ctrl.Finish() - - s := new(Subject) - ctrl.RecordCall(s, "FooMethod", "arg").Times(0) - rep.assertFatal(func() { - ctrl.Call(s, "FooMethod", "arg") - }) -} diff --git a/vendor/github.com/golang/mock/gomock/matchers_test.go b/vendor/github.com/golang/mock/gomock/matchers_test.go deleted file mode 100644 index 29b97fb9c8e3..000000000000 --- a/vendor/github.com/golang/mock/gomock/matchers_test.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2010 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package gomock_test - -import ( - "errors" - "testing" - - "github.com/golang/mock/gomock" - mock_matcher "github.com/golang/mock/gomock/mock_matcher" -) - -func TestMatchers(t *testing.T) { - type e interface{} - type testCase struct { - matcher gomock.Matcher - yes, no []e - } - tests := []testCase{ - testCase{gomock.Any(), []e{3, nil, "foo"}, nil}, - testCase{gomock.Eq(4), []e{4}, []e{3, "blah", nil, int64(4)}}, - testCase{gomock.Nil(), - []e{nil, (error)(nil), (chan bool)(nil), (*int)(nil)}, - []e{"", 0, make(chan bool), errors.New("err"), new(int)}}, - testCase{gomock.Not(gomock.Eq(4)), []e{3, "blah", nil, int64(4)}, []e{4}}, - } - for i, test := range tests { - for _, x := range test.yes { - if !test.matcher.Matches(x) { - t.Errorf(`test %d: "%v %s" should be true.`, i, x, test.matcher) - } - } - for _, x := range test.no { - if test.matcher.Matches(x) { - t.Errorf(`test %d: "%v %s" should be false.`, i, x, test.matcher) - } - } - } -} - -// A more thorough test of notMatcher -func TestNotMatcher(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - mockMatcher := mock_matcher.NewMockMatcher(ctrl) - notMatcher := gomock.Not(mockMatcher) - - mockMatcher.EXPECT().Matches(4).Return(true) - if match := notMatcher.Matches(4); match { - t.Errorf("notMatcher should not match 4") - } - - mockMatcher.EXPECT().Matches(5).Return(false) - if match := notMatcher.Matches(5); !match { - t.Errorf("notMatcher should match 5") - } -} diff --git a/vendor/github.com/golang/protobuf/proto/BUILD b/vendor/github.com/golang/protobuf/proto/BUILD index fd6d235d5a81..2ef1ce536553 100644 --- a/vendor/github.com/golang/protobuf/proto/BUILD +++ b/vendor/github.com/golang/protobuf/proto/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -19,43 +19,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = [ - "message_set_test.go", - "size2_test.go", - ], - importpath = "github.com/golang/protobuf/proto", - library = ":go_default_library", -) - -go_test( - name = "go_default_xtest", - srcs = [ - "all_test.go", - "any_test.go", - "clone_test.go", - "decode_test.go", - "encode_test.go", - "equal_test.go", - "extensions_test.go", - "map_test.go", - "proto3_test.go", - "size_test.go", - "text_parser_test.go", - "text_test.go", - ], - importpath = "github.com/golang/protobuf/proto_test", - deps = [ - ":go_default_library", - "//vendor/github.com/golang/protobuf/proto/proto3_proto:go_default_library", - "//vendor/github.com/golang/protobuf/proto/testdata:go_default_library", - "//vendor/github.com/golang/protobuf/ptypes:go_default_library", - "//vendor/github.com/golang/protobuf/ptypes/any:go_default_library", - "//vendor/golang.org/x/sync/errgroup:go_default_library", - ], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/golang/protobuf/proto/all_test.go b/vendor/github.com/golang/protobuf/proto/all_test.go deleted file mode 100644 index 41451a40734a..000000000000 --- a/vendor/github.com/golang/protobuf/proto/all_test.go +++ /dev/null @@ -1,2278 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "math" - "math/rand" - "reflect" - "runtime/debug" - "strings" - "testing" - "time" - - . "github.com/golang/protobuf/proto" - . "github.com/golang/protobuf/proto/testdata" -) - -var globalO *Buffer - -func old() *Buffer { - if globalO == nil { - globalO = NewBuffer(nil) - } - globalO.Reset() - return globalO -} - -func equalbytes(b1, b2 []byte, t *testing.T) { - if len(b1) != len(b2) { - t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2)) - return - } - for i := 0; i < len(b1); i++ { - if b1[i] != b2[i] { - t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2) - } - } -} - -func initGoTestField() *GoTestField { - f := new(GoTestField) - f.Label = String("label") - f.Type = String("type") - return f -} - -// These are all structurally equivalent but the tag numbers differ. -// (It's remarkable that required, optional, and repeated all have -// 8 letters.) -func initGoTest_RequiredGroup() *GoTest_RequiredGroup { - return &GoTest_RequiredGroup{ - RequiredField: String("required"), - } -} - -func initGoTest_OptionalGroup() *GoTest_OptionalGroup { - return &GoTest_OptionalGroup{ - RequiredField: String("optional"), - } -} - -func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { - return &GoTest_RepeatedGroup{ - RequiredField: String("repeated"), - } -} - -func initGoTest(setdefaults bool) *GoTest { - pb := new(GoTest) - if setdefaults { - pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) - pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) - pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) - pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) - pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) - pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) - pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) - pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) - pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) - pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) - pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted - pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) - pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) - } - - pb.Kind = GoTest_TIME.Enum() - pb.RequiredField = initGoTestField() - pb.F_BoolRequired = Bool(true) - pb.F_Int32Required = Int32(3) - pb.F_Int64Required = Int64(6) - pb.F_Fixed32Required = Uint32(32) - pb.F_Fixed64Required = Uint64(64) - pb.F_Uint32Required = Uint32(3232) - pb.F_Uint64Required = Uint64(6464) - pb.F_FloatRequired = Float32(3232) - pb.F_DoubleRequired = Float64(6464) - pb.F_StringRequired = String("string") - pb.F_BytesRequired = []byte("bytes") - pb.F_Sint32Required = Int32(-32) - pb.F_Sint64Required = Int64(-64) - pb.Requiredgroup = initGoTest_RequiredGroup() - - return pb -} - -func fail(msg string, b *bytes.Buffer, s string, t *testing.T) { - data := b.Bytes() - ld := len(data) - ls := len(s) / 2 - - fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls) - - // find the interesting spot - n - n := ls - if ld < ls { - n = ld - } - j := 0 - for i := 0; i < n; i++ { - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - if data[i] == bs { - continue - } - n = i - break - } - l := n - 10 - if l < 0 { - l = 0 - } - h := n + 10 - - // find the interesting spot - n - fmt.Printf("is[%d]:", l) - for i := l; i < h; i++ { - if i >= ld { - fmt.Printf(" --") - continue - } - fmt.Printf(" %.2x", data[i]) - } - fmt.Printf("\n") - - fmt.Printf("sb[%d]:", l) - for i := l; i < h; i++ { - if i >= ls { - fmt.Printf(" --") - continue - } - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - fmt.Printf(" %.2x", bs) - } - fmt.Printf("\n") - - t.Fail() - - // t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes()) - // Print the output in a partially-decoded format; can - // be helpful when updating the test. It produces the output - // that is pasted, with minor edits, into the argument to verify(). - // data := b.Bytes() - // nesting := 0 - // for b.Len() > 0 { - // start := len(data) - b.Len() - // var u uint64 - // u, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // wire := u & 0x7 - // tag := u >> 3 - // switch wire { - // case WireVarint: - // v, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed32: - // v, err := DecodeFixed32(b) - // if err != nil { - // fmt.Printf("decode error on fixed32:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed64: - // v, err := DecodeFixed64(b) - // if err != nil { - // fmt.Printf("decode error on fixed64:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireBytes: - // nb, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // after_tag := len(data) - b.Len() - // str := make([]byte, nb) - // _, err = b.Read(str) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n", - // data[start:after_tag], str, tag, wire) - // case WireStartGroup: - // nesting++ - // fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // case WireEndGroup: - // fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // nesting-- - // default: - // fmt.Printf("unrecognized wire type %d\n", wire) - // return - // } - // } -} - -func hex(c uint8) uint8 { - if '0' <= c && c <= '9' { - return c - '0' - } - if 'a' <= c && c <= 'f' { - return 10 + c - 'a' - } - if 'A' <= c && c <= 'F' { - return 10 + c - 'A' - } - return 0 -} - -func equal(b []byte, s string, t *testing.T) bool { - if 2*len(b) != len(s) { - // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t) - fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s)) - return false - } - for i, j := 0, 0; i < len(b); i, j = i+1, j+2 { - x := hex(s[j])*16 + hex(s[j+1]) - if b[i] != x { - // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t) - fmt.Printf("bad byte[%d]:%x %x", i, b[i], x) - return false - } - } - return true -} - -func overify(t *testing.T, pb *GoTest, expected string) { - o := old() - err := o.Marshal(pb) - if err != nil { - fmt.Printf("overify marshal-1 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 1", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = o.Unmarshal(pbd) - if err != nil { - t.Fatalf("overify unmarshal err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - o.Reset() - err = o.Marshal(pbd) - if err != nil { - t.Errorf("overify marshal-2 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 2", o.Bytes()) - t.Fatalf("string = %s", expected) - } -} - -// Simple tests for numeric encode/decode primitives (varint, etc.) -func TestNumericPrimitives(t *testing.T) { - for i := uint64(0); i < 1e6; i += 111 { - o := old() - if o.EncodeVarint(i) != nil { - t.Error("EncodeVarint") - break - } - x, e := o.DecodeVarint() - if e != nil { - t.Fatal("DecodeVarint") - } - if x != i { - t.Fatal("varint decode fail:", i, x) - } - - o = old() - if o.EncodeFixed32(i) != nil { - t.Fatal("encFixed32") - } - x, e = o.DecodeFixed32() - if e != nil { - t.Fatal("decFixed32") - } - if x != i { - t.Fatal("fixed32 decode fail:", i, x) - } - - o = old() - if o.EncodeFixed64(i*1234567) != nil { - t.Error("encFixed64") - break - } - x, e = o.DecodeFixed64() - if e != nil { - t.Error("decFixed64") - break - } - if x != i*1234567 { - t.Error("fixed64 decode fail:", i*1234567, x) - break - } - - o = old() - i32 := int32(i - 12345) - if o.EncodeZigzag32(uint64(i32)) != nil { - t.Fatal("EncodeZigzag32") - } - x, e = o.DecodeZigzag32() - if e != nil { - t.Fatal("DecodeZigzag32") - } - if x != uint64(uint32(i32)) { - t.Fatal("zigzag32 decode fail:", i32, x) - } - - o = old() - i64 := int64(i - 12345) - if o.EncodeZigzag64(uint64(i64)) != nil { - t.Fatal("EncodeZigzag64") - } - x, e = o.DecodeZigzag64() - if e != nil { - t.Fatal("DecodeZigzag64") - } - if x != uint64(i64) { - t.Fatal("zigzag64 decode fail:", i64, x) - } - } -} - -// fakeMarshaler is a simple struct implementing Marshaler and Message interfaces. -type fakeMarshaler struct { - b []byte - err error -} - -func (f *fakeMarshaler) Marshal() ([]byte, error) { return f.b, f.err } -func (f *fakeMarshaler) String() string { return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) } -func (f *fakeMarshaler) ProtoMessage() {} -func (f *fakeMarshaler) Reset() {} - -type msgWithFakeMarshaler struct { - M *fakeMarshaler `protobuf:"bytes,1,opt,name=fake"` -} - -func (m *msgWithFakeMarshaler) String() string { return CompactTextString(m) } -func (m *msgWithFakeMarshaler) ProtoMessage() {} -func (m *msgWithFakeMarshaler) Reset() {} - -// Simple tests for proto messages that implement the Marshaler interface. -func TestMarshalerEncoding(t *testing.T) { - tests := []struct { - name string - m Message - want []byte - errType reflect.Type - }{ - { - name: "Marshaler that fails", - m: &fakeMarshaler{ - err: errors.New("some marshal err"), - b: []byte{5, 6, 7}, - }, - // Since the Marshal method returned bytes, they should be written to the - // buffer. (For efficiency, we assume that Marshal implementations are - // always correct w.r.t. RequiredNotSetError and output.) - want: []byte{5, 6, 7}, - errType: reflect.TypeOf(errors.New("some marshal err")), - }, - { - name: "Marshaler that fails with RequiredNotSetError", - m: &msgWithFakeMarshaler{ - M: &fakeMarshaler{ - err: &RequiredNotSetError{}, - b: []byte{5, 6, 7}, - }, - }, - // Since there's an error that can be continued after, - // the buffer should be written. - want: []byte{ - 10, 3, // for &msgWithFakeMarshaler - 5, 6, 7, // for &fakeMarshaler - }, - errType: reflect.TypeOf(&RequiredNotSetError{}), - }, - { - name: "Marshaler that succeeds", - m: &fakeMarshaler{ - b: []byte{0, 1, 2, 3, 4, 127, 255}, - }, - want: []byte{0, 1, 2, 3, 4, 127, 255}, - }, - } - for _, test := range tests { - b := NewBuffer(nil) - err := b.Marshal(test.m) - if reflect.TypeOf(err) != test.errType { - t.Errorf("%s: got err %T(%v) wanted %T", test.name, err, err, test.errType) - } - if !reflect.DeepEqual(test.want, b.Bytes()) { - t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want) - } - if size := Size(test.m); size != len(b.Bytes()) { - t.Errorf("%s: Size(_) = %v, but marshaled to %v bytes", test.name, size, len(b.Bytes())) - } - - m, mErr := Marshal(test.m) - if !bytes.Equal(b.Bytes(), m) { - t.Errorf("%s: Marshal returned %v, but (*Buffer).Marshal wrote %v", test.name, m, b.Bytes()) - } - if !reflect.DeepEqual(err, mErr) { - t.Errorf("%s: Marshal err = %q, but (*Buffer).Marshal returned %q", - test.name, fmt.Sprint(mErr), fmt.Sprint(err)) - } - } -} - -// Simple tests for bytes -func TestBytesPrimitives(t *testing.T) { - o := old() - bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'} - if o.EncodeRawBytes(bytes) != nil { - t.Error("EncodeRawBytes") - } - decb, e := o.DecodeRawBytes(false) - if e != nil { - t.Error("DecodeRawBytes") - } - equalbytes(bytes, decb, t) -} - -// Simple tests for strings -func TestStringPrimitives(t *testing.T) { - o := old() - s := "now is the time" - if o.EncodeStringBytes(s) != nil { - t.Error("enc_string") - } - decs, e := o.DecodeStringBytes() - if e != nil { - t.Error("dec_string") - } - if s != decs { - t.Error("string encode/decode fail:", s, decs) - } -} - -// Do we catch the "required bit not set" case? -func TestRequiredBit(t *testing.T) { - o := old() - pb := new(GoTest) - err := o.Marshal(pb) - if err == nil { - t.Error("did not catch missing required fields") - } else if strings.Index(err.Error(), "Kind") < 0 { - t.Error("wrong error type:", err) - } -} - -// Check that all fields are nil. -// Clearly silly, and a residue from a more interesting test with an earlier, -// different initialization property, but it once caught a compiler bug so -// it lives. -func checkInitialized(pb *GoTest, t *testing.T) { - if pb.F_BoolDefaulted != nil { - t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted) - } - if pb.F_Int32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted) - } - if pb.F_Int64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted) - } - if pb.F_Fixed32Defaulted != nil { - t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted) - } - if pb.F_Fixed64Defaulted != nil { - t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted) - } - if pb.F_Uint32Defaulted != nil { - t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted) - } - if pb.F_Uint64Defaulted != nil { - t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted) - } - if pb.F_FloatDefaulted != nil { - t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted) - } - if pb.F_DoubleDefaulted != nil { - t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted) - } - if pb.F_StringDefaulted != nil { - t.Error("New or Reset did not set string:", *pb.F_StringDefaulted) - } - if pb.F_BytesDefaulted != nil { - t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted)) - } - if pb.F_Sint32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted) - } - if pb.F_Sint64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted) - } -} - -// Does Reset() reset? -func TestReset(t *testing.T) { - pb := initGoTest(true) - // muck with some values - pb.F_BoolDefaulted = Bool(false) - pb.F_Int32Defaulted = Int32(237) - pb.F_Int64Defaulted = Int64(12346) - pb.F_Fixed32Defaulted = Uint32(32000) - pb.F_Fixed64Defaulted = Uint64(666) - pb.F_Uint32Defaulted = Uint32(323232) - pb.F_Uint64Defaulted = nil - pb.F_FloatDefaulted = nil - pb.F_DoubleDefaulted = Float64(0) - pb.F_StringDefaulted = String("gotcha") - pb.F_BytesDefaulted = []byte("asdfasdf") - pb.F_Sint32Defaulted = Int32(123) - pb.F_Sint64Defaulted = Int64(789) - pb.Reset() - checkInitialized(pb, t) -} - -// All required fields set, no defaults provided. -func TestEncodeDecode1(t *testing.T) { - pb := initGoTest(false) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 0x20 - "714000000000000000"+ // field 14, encoding 1, value 0x40 - "78a019"+ // field 15, encoding 0, value 0xca0 = 3232 - "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string" - "b304"+ // field 70, encoding 3, start group - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // field 70, encoding 4, end group - "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f") // field 103, encoding 0, 0x7f zigzag64 -} - -// All required fields set, defaults provided. -func TestEncodeDecode2(t *testing.T) { - pb := initGoTest(true) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All default fields set to their default value by hand -func TestEncodeDecode3(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolDefaulted = Bool(true) - pb.F_Int32Defaulted = Int32(32) - pb.F_Int64Defaulted = Int64(64) - pb.F_Fixed32Defaulted = Uint32(320) - pb.F_Fixed64Defaulted = Uint64(640) - pb.F_Uint32Defaulted = Uint32(3200) - pb.F_Uint64Defaulted = Uint64(6400) - pb.F_FloatDefaulted = Float32(314159) - pb.F_DoubleDefaulted = Float64(271828) - pb.F_StringDefaulted = String("hello, \"world!\"\n") - pb.F_BytesDefaulted = []byte("Bignose") - pb.F_Sint32Defaulted = Int32(-32) - pb.F_Sint64Defaulted = Int64(-64) - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all non-defaulted optional fields have values. -func TestEncodeDecode4(t *testing.T) { - pb := initGoTest(true) - pb.Table = String("hello") - pb.Param = Int32(7) - pb.OptionalField = initGoTestField() - pb.F_BoolOptional = Bool(true) - pb.F_Int32Optional = Int32(32) - pb.F_Int64Optional = Int64(64) - pb.F_Fixed32Optional = Uint32(3232) - pb.F_Fixed64Optional = Uint64(6464) - pb.F_Uint32Optional = Uint32(323232) - pb.F_Uint64Optional = Uint64(646464) - pb.F_FloatOptional = Float32(32.) - pb.F_DoubleOptional = Float64(64.) - pb.F_StringOptional = String("hello") - pb.F_BytesOptional = []byte("Bignose") - pb.F_Sint32Optional = Int32(-32) - pb.F_Sint64Optional = Int64(-64) - pb.Optionalgroup = initGoTest_OptionalGroup() - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello" - "1807"+ // field 3, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "f00101"+ // field 30, encoding 0, value 1 - "f80120"+ // field 31, encoding 0, value 32 - "800240"+ // field 32, encoding 0, value 64 - "8d02a00c0000"+ // field 33, encoding 5, value 3232 - "91024019000000000000"+ // field 34, encoding 1, value 6464 - "9802a0dd13"+ // field 35, encoding 0, value 323232 - "a002c0ba27"+ // field 36, encoding 0, value 646464 - "ad0200000042"+ // field 37, encoding 5, value 32.0 - "b1020000000000005040"+ // field 38, encoding 1, value 64.0 - "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "d305"+ // start group field 90 level 1 - "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional" - "d405"+ // end group field 90 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose" - "f0123f"+ // field 302, encoding 0, value 63 - "f8127f"+ // field 303, encoding 0, value 127 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestEncodeDecode5(t *testing.T) { - pb := initGoTest(true) - pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()} - pb.F_BoolRepeated = []bool{false, true} - pb.F_Int32Repeated = []int32{32, 33} - pb.F_Int64Repeated = []int64{64, 65} - pb.F_Fixed32Repeated = []uint32{3232, 3333} - pb.F_Fixed64Repeated = []uint64{6464, 6565} - pb.F_Uint32Repeated = []uint32{323232, 333333} - pb.F_Uint64Repeated = []uint64{646464, 656565} - pb.F_FloatRepeated = []float32{32., 33.} - pb.F_DoubleRepeated = []float64{64., 65.} - pb.F_StringRepeated = []string{"hello", "sailor"} - pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")} - pb.F_Sint32Repeated = []int32{32, -32} - pb.F_Sint64Repeated = []int64{64, -64} - pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "a00100"+ // field 20, encoding 0, value 0 - "a00101"+ // field 20, encoding 0, value 1 - "a80120"+ // field 21, encoding 0, value 32 - "a80121"+ // field 21, encoding 0, value 33 - "b00140"+ // field 22, encoding 0, value 64 - "b00141"+ // field 22, encoding 0, value 65 - "bd01a00c0000"+ // field 23, encoding 5, value 3232 - "bd01050d0000"+ // field 23, encoding 5, value 3333 - "c1014019000000000000"+ // field 24, encoding 1, value 6464 - "c101a519000000000000"+ // field 24, encoding 1, value 6565 - "c801a0dd13"+ // field 25, encoding 0, value 323232 - "c80195ac14"+ // field 25, encoding 0, value 333333 - "d001c0ba27"+ // field 26, encoding 0, value 646464 - "d001b58928"+ // field 26, encoding 0, value 656565 - "dd0100000042"+ // field 27, encoding 5, value 32.0 - "dd0100000442"+ // field 27, encoding 5, value 33.0 - "e1010000000000005040"+ // field 28, encoding 1, value 64.0 - "e1010000000000405040"+ // field 28, encoding 1, value 65.0 - "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello" - "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ca0c03"+"626967"+ // field 201, encoding 2, string "big" - "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose" - "d00c40"+ // field 202, encoding 0, value 32 - "d00c3f"+ // field 202, encoding 0, value -32 - "d80c8001"+ // field 203, encoding 0, value 64 - "d80c7f"+ // field 203, encoding 0, value -64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, all packed repeated fields given two values. -func TestEncodeDecode6(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolRepeatedPacked = []bool{false, true} - pb.F_Int32RepeatedPacked = []int32{32, 33} - pb.F_Int64RepeatedPacked = []int64{64, 65} - pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333} - pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565} - pb.F_Uint32RepeatedPacked = []uint32{323232, 333333} - pb.F_Uint64RepeatedPacked = []uint64{646464, 656565} - pb.F_FloatRepeatedPacked = []float32{32., 33.} - pb.F_DoubleRepeatedPacked = []float64{64., 65.} - pb.F_Sint32RepeatedPacked = []int32{32, -32} - pb.F_Sint64RepeatedPacked = []int64{64, -64} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1 - "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33 - "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65 - "aa0308"+ // field 53, encoding 2, 8 bytes - "a00c0000050d0000"+ // value 3232, value 3333 - "b20310"+ // field 54, encoding 2, 16 bytes - "4019000000000000a519000000000000"+ // value 6464, value 6565 - "ba0306"+ // field 55, encoding 2, 6 bytes - "a0dd1395ac14"+ // value 323232, value 333333 - "c20306"+ // field 56, encoding 2, 6 bytes - "c0ba27b58928"+ // value 646464, value 656565 - "ca0308"+ // field 57, encoding 2, 8 bytes - "0000004200000442"+ // value 32.0, value 33.0 - "d20310"+ // field 58, encoding 2, 16 bytes - "00000000000050400000000000405040"+ // value 64.0, value 65.0 - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "b21f02"+ // field 502, encoding 2, 2 bytes - "403f"+ // value 32, value -32 - "ba1f03"+ // field 503, encoding 2, 3 bytes - "80017f") // value 64, value -64 -} - -// Test that we can encode empty bytes fields. -func TestEncodeDecodeBytes1(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRequired = []byte{} - pb.F_BytesRepeated = [][]byte{{}} - pb.F_BytesOptional = []byte{} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 { - t.Error("required empty bytes field is incorrect") - } - if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil { - t.Error("repeated empty bytes field is incorrect") - } - if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 { - t.Error("optional empty bytes field is incorrect") - } -} - -// Test that we encode nil-valued fields of a repeated bytes field correctly. -// Since entries in a repeated field cannot be nil, nil must mean empty value. -func TestEncodeDecodeBytes2(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRepeated = [][]byte{nil} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil { - t.Error("Unexpected value for repeated bytes field") - } -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestSkippingUnrecognizedFields(t *testing.T) { - o := old() - pb := initGoTestField() - - // Marshal it normally. - o.Marshal(pb) - - // Now new a GoSkipTest record. - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - // Marshal it into same buffer. - o.Marshal(skip) - - pbd := new(GoTestField) - o.Unmarshal(pbd) - - // The __unrecognized field should be a marshaling of GoSkipTest - skipd := new(GoSkipTest) - - o.SetBuf(pbd.XXX_unrecognized) - o.Unmarshal(skipd) - - if *skipd.SkipInt32 != *skip.SkipInt32 { - t.Error("skip int32", skipd.SkipInt32) - } - if *skipd.SkipFixed32 != *skip.SkipFixed32 { - t.Error("skip fixed32", skipd.SkipFixed32) - } - if *skipd.SkipFixed64 != *skip.SkipFixed64 { - t.Error("skip fixed64", skipd.SkipFixed64) - } - if *skipd.SkipString != *skip.SkipString { - t.Error("skip string", *skipd.SkipString) - } - if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 { - t.Error("skip group int32", skipd.Skipgroup.GroupInt32) - } - if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString { - t.Error("skip group string", *skipd.Skipgroup.GroupString) - } -} - -// Check that unrecognized fields of a submessage are preserved. -func TestSubmessageUnrecognizedFields(t *testing.T) { - nm := &NewMessage{ - Nested: &NewMessage_Nested{ - Name: String("Nigel"), - FoodGroup: String("carbs"), - }, - } - b, err := Marshal(nm) - if err != nil { - t.Fatalf("Marshal of NewMessage: %v", err) - } - - // Unmarshal into an OldMessage. - om := new(OldMessage) - if err := Unmarshal(b, om); err != nil { - t.Fatalf("Unmarshal to OldMessage: %v", err) - } - exp := &OldMessage{ - Nested: &OldMessage_Nested{ - Name: String("Nigel"), - // normal protocol buffer users should not do this - XXX_unrecognized: []byte("\x12\x05carbs"), - }, - } - if !Equal(om, exp) { - t.Errorf("om = %v, want %v", om, exp) - } - - // Clone the OldMessage. - om = Clone(om).(*OldMessage) - if !Equal(om, exp) { - t.Errorf("Clone(om) = %v, want %v", om, exp) - } - - // Marshal the OldMessage, then unmarshal it into an empty NewMessage. - if b, err = Marshal(om); err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - t.Logf("Marshal(%v) -> %q", om, b) - nm2 := new(NewMessage) - if err := Unmarshal(b, nm2); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - if !Equal(nm, nm2) { - t.Errorf("NewMessage round-trip: %v => %v", nm, nm2) - } -} - -// Check that an int32 field can be upgraded to an int64 field. -func TestNegativeInt32(t *testing.T) { - om := &OldMessage{ - Num: Int32(-1), - } - b, err := Marshal(om) - if err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - - // Check the size. It should be 11 bytes; - // 1 for the field/wire type, and 10 for the negative number. - if len(b) != 11 { - t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b) - } - - // Unmarshal into a NewMessage. - nm := new(NewMessage) - if err := Unmarshal(b, nm); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - want := &NewMessage{ - Num: Int64(-1), - } - if !Equal(nm, want) { - t.Errorf("nm = %v, want %v", nm, want) - } -} - -// Check that we can grow an array (repeated field) to have many elements. -// This test doesn't depend only on our encoding; for variety, it makes sure -// we create, encode, and decode the correct contents explicitly. It's therefore -// a bit messier. -// This test also uses (and hence tests) the Marshal/Unmarshal functions -// instead of the methods. -func TestBigRepeated(t *testing.T) { - pb := initGoTest(true) - - // Create the arrays - const N = 50 // Internally the library starts much smaller. - pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N) - pb.F_Sint64Repeated = make([]int64, N) - pb.F_Sint32Repeated = make([]int32, N) - pb.F_BytesRepeated = make([][]byte, N) - pb.F_StringRepeated = make([]string, N) - pb.F_DoubleRepeated = make([]float64, N) - pb.F_FloatRepeated = make([]float32, N) - pb.F_Uint64Repeated = make([]uint64, N) - pb.F_Uint32Repeated = make([]uint32, N) - pb.F_Fixed64Repeated = make([]uint64, N) - pb.F_Fixed32Repeated = make([]uint32, N) - pb.F_Int64Repeated = make([]int64, N) - pb.F_Int32Repeated = make([]int32, N) - pb.F_BoolRepeated = make([]bool, N) - pb.RepeatedField = make([]*GoTestField, N) - - // Fill in the arrays with checkable values. - igtf := initGoTestField() - igtrg := initGoTest_RepeatedGroup() - for i := 0; i < N; i++ { - pb.Repeatedgroup[i] = igtrg - pb.F_Sint64Repeated[i] = int64(i) - pb.F_Sint32Repeated[i] = int32(i) - s := fmt.Sprint(i) - pb.F_BytesRepeated[i] = []byte(s) - pb.F_StringRepeated[i] = s - pb.F_DoubleRepeated[i] = float64(i) - pb.F_FloatRepeated[i] = float32(i) - pb.F_Uint64Repeated[i] = uint64(i) - pb.F_Uint32Repeated[i] = uint32(i) - pb.F_Fixed64Repeated[i] = uint64(i) - pb.F_Fixed32Repeated[i] = uint32(i) - pb.F_Int64Repeated[i] = int64(i) - pb.F_Int32Repeated[i] = int32(i) - pb.F_BoolRepeated[i] = i%2 == 0 - pb.RepeatedField[i] = igtf - } - - // Marshal. - buf, _ := Marshal(pb) - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - Unmarshal(buf, pbd) - - // Check the checkable values - for i := uint64(0); i < N; i++ { - if pbd.Repeatedgroup[i] == nil { // TODO: more checking? - t.Error("pbd.Repeatedgroup bad") - } - var x uint64 - x = uint64(pbd.F_Sint64Repeated[i]) - if x != i { - t.Error("pbd.F_Sint64Repeated bad", x, i) - } - x = uint64(pbd.F_Sint32Repeated[i]) - if x != i { - t.Error("pbd.F_Sint32Repeated bad", x, i) - } - s := fmt.Sprint(i) - equalbytes(pbd.F_BytesRepeated[i], []byte(s), t) - if pbd.F_StringRepeated[i] != s { - t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i) - } - x = uint64(pbd.F_DoubleRepeated[i]) - if x != i { - t.Error("pbd.F_DoubleRepeated bad", x, i) - } - x = uint64(pbd.F_FloatRepeated[i]) - if x != i { - t.Error("pbd.F_FloatRepeated bad", x, i) - } - x = pbd.F_Uint64Repeated[i] - if x != i { - t.Error("pbd.F_Uint64Repeated bad", x, i) - } - x = uint64(pbd.F_Uint32Repeated[i]) - if x != i { - t.Error("pbd.F_Uint32Repeated bad", x, i) - } - x = pbd.F_Fixed64Repeated[i] - if x != i { - t.Error("pbd.F_Fixed64Repeated bad", x, i) - } - x = uint64(pbd.F_Fixed32Repeated[i]) - if x != i { - t.Error("pbd.F_Fixed32Repeated bad", x, i) - } - x = uint64(pbd.F_Int64Repeated[i]) - if x != i { - t.Error("pbd.F_Int64Repeated bad", x, i) - } - x = uint64(pbd.F_Int32Repeated[i]) - if x != i { - t.Error("pbd.F_Int32Repeated bad", x, i) - } - if pbd.F_BoolRepeated[i] != (i%2 == 0) { - t.Error("pbd.F_BoolRepeated bad", x, i) - } - if pbd.RepeatedField[i] == nil { // TODO: more checking? - t.Error("pbd.RepeatedField bad") - } - } -} - -// Verify we give a useful message when decoding to the wrong structure type. -func TestTypeMismatch(t *testing.T) { - pb1 := initGoTest(true) - - // Marshal - o := old() - o.Marshal(pb1) - - // Now Unmarshal it to the wrong type. - pb2 := initGoTestField() - err := o.Unmarshal(pb2) - if err == nil { - t.Error("expected error, got no error") - } else if !strings.Contains(err.Error(), "bad wiretype") { - t.Error("expected bad wiretype error, got", err) - } -} - -func encodeDecode(t *testing.T, in, out Message, msg string) { - buf, err := Marshal(in) - if err != nil { - t.Fatalf("failed marshaling %v: %v", msg, err) - } - if err := Unmarshal(buf, out); err != nil { - t.Fatalf("failed unmarshaling %v: %v", msg, err) - } -} - -func TestPackedNonPackedDecoderSwitching(t *testing.T) { - np, p := new(NonPackedTest), new(PackedTest) - - // non-packed -> packed - np.A = []int32{0, 1, 1, 2, 3, 5} - encodeDecode(t, np, p, "non-packed -> packed") - if !reflect.DeepEqual(np.A, p.B) { - t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B) - } - - // packed -> non-packed - np.Reset() - p.B = []int32{3, 1, 4, 1, 5, 9} - encodeDecode(t, p, np, "packed -> non-packed") - if !reflect.DeepEqual(p.B, np.A) { - t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A) - } -} - -func TestProto1RepeatedGroup(t *testing.T) { - pb := &MessageList{ - Message: []*MessageList_Message{ - { - Name: String("blah"), - Count: Int32(7), - }, - // NOTE: pb.Message[1] is a nil - nil, - }, - } - - o := old() - err := o.Marshal(pb) - if err == nil || !strings.Contains(err.Error(), "repeated field Message has nil") { - t.Fatalf("unexpected or no error when marshaling: %v", err) - } -} - -// Test that enums work. Checks for a bug introduced by making enums -// named types instead of int32: newInt32FromUint64 would crash with -// a type mismatch in reflect.PointTo. -func TestEnum(t *testing.T) { - pb := new(GoEnum) - pb.Foo = FOO_FOO1.Enum() - o := old() - if err := o.Marshal(pb); err != nil { - t.Fatal("error encoding enum:", err) - } - pb1 := new(GoEnum) - if err := o.Unmarshal(pb1); err != nil { - t.Fatal("error decoding enum:", err) - } - if *pb1.Foo != FOO_FOO1 { - t.Error("expected 7 but got ", *pb1.Foo) - } -} - -// Enum types have String methods. Check that enum fields can be printed. -// We don't care what the value actually is, just as long as it doesn't crash. -func TestPrintingNilEnumFields(t *testing.T) { - pb := new(GoEnum) - _ = fmt.Sprintf("%+v", pb) -} - -// Verify that absent required fields cause Marshal/Unmarshal to return errors. -func TestRequiredFieldEnforcement(t *testing.T) { - pb := new(GoTestField) - _, err := Marshal(pb) - if err == nil { - t.Error("marshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Label") { - t.Errorf("marshal: bad error type: %v", err) - } - - // A slightly sneaky, yet valid, proto. It encodes the same required field twice, - // so simply counting the required fields is insufficient. - // field 1, encoding 2, value "hi" - buf := []byte("\x0A\x02hi\x0A\x02hi") - err = Unmarshal(buf, pb) - if err == nil { - t.Error("unmarshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "{Unknown}") { - t.Errorf("unmarshal: bad error type: %v", err) - } -} - -// Verify that absent required fields in groups cause Marshal/Unmarshal to return errors. -func TestRequiredFieldEnforcementGroups(t *testing.T) { - pb := &GoTestRequiredGroupField{Group: &GoTestRequiredGroupField_Group{}} - if _, err := Marshal(pb); err == nil { - t.Error("marshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.Field") { - t.Errorf("marshal: bad error type: %v", err) - } - - buf := []byte{11, 12} - if err := Unmarshal(buf, pb); err == nil { - t.Error("unmarshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.{Unknown}") { - t.Errorf("unmarshal: bad error type: %v", err) - } -} - -func TestTypedNilMarshal(t *testing.T) { - // A typed nil should return ErrNil and not crash. - { - var m *GoEnum - if _, err := Marshal(m); err != ErrNil { - t.Errorf("Marshal(%#v): got %v, want ErrNil", m, err) - } - } - - { - m := &Communique{Union: &Communique_Msg{nil}} - if _, err := Marshal(m); err == nil || err == ErrNil { - t.Errorf("Marshal(%#v): got %v, want errOneofHasNil", m, err) - } - } -} - -// A type that implements the Marshaler interface, but is not nillable. -type nonNillableInt uint64 - -func (nni nonNillableInt) Marshal() ([]byte, error) { - return EncodeVarint(uint64(nni)), nil -} - -type NNIMessage struct { - nni nonNillableInt -} - -func (*NNIMessage) Reset() {} -func (*NNIMessage) String() string { return "" } -func (*NNIMessage) ProtoMessage() {} - -// A type that implements the Marshaler interface and is nillable. -type nillableMessage struct { - x uint64 -} - -func (nm *nillableMessage) Marshal() ([]byte, error) { - return EncodeVarint(nm.x), nil -} - -type NMMessage struct { - nm *nillableMessage -} - -func (*NMMessage) Reset() {} -func (*NMMessage) String() string { return "" } -func (*NMMessage) ProtoMessage() {} - -// Verify a type that uses the Marshaler interface, but has a nil pointer. -func TestNilMarshaler(t *testing.T) { - // Try a struct with a Marshaler field that is nil. - // It should be directly marshable. - nmm := new(NMMessage) - if _, err := Marshal(nmm); err != nil { - t.Error("unexpected error marshaling nmm: ", err) - } - - // Try a struct with a Marshaler field that is not nillable. - nnim := new(NNIMessage) - nnim.nni = 7 - var _ Marshaler = nnim.nni // verify it is truly a Marshaler - if _, err := Marshal(nnim); err != nil { - t.Error("unexpected error marshaling nnim: ", err) - } -} - -func TestAllSetDefaults(t *testing.T) { - // Exercise SetDefaults with all scalar field types. - m := &Defaults{ - // NaN != NaN, so override that here. - F_Nan: Float32(1.7), - } - expected := &Defaults{ - F_Bool: Bool(true), - F_Int32: Int32(32), - F_Int64: Int64(64), - F_Fixed32: Uint32(320), - F_Fixed64: Uint64(640), - F_Uint32: Uint32(3200), - F_Uint64: Uint64(6400), - F_Float: Float32(314159), - F_Double: Float64(271828), - F_String: String(`hello, "world!"` + "\n"), - F_Bytes: []byte("Bignose"), - F_Sint32: Int32(-32), - F_Sint64: Int64(-64), - F_Enum: Defaults_GREEN.Enum(), - F_Pinf: Float32(float32(math.Inf(1))), - F_Ninf: Float32(float32(math.Inf(-1))), - F_Nan: Float32(1.7), - StrZero: String(""), - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithSetField(t *testing.T) { - // Check that a set value is not overridden. - m := &Defaults{ - F_Int32: Int32(12), - } - SetDefaults(m) - if v := m.GetF_Int32(); v != 12 { - t.Errorf("m.FInt32 = %v, want 12", v) - } -} - -func TestSetDefaultsWithSubMessage(t *testing.T) { - m := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - }, - } - expected := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - Port: Int32(4000), - }, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) { - m := &MyMessage{ - RepInner: []*InnerMessage{{}}, - } - expected := &MyMessage{ - RepInner: []*InnerMessage{{ - Port: Int32(4000), - }}, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultWithRepeatedNonMessage(t *testing.T) { - m := &MyMessage{ - Pet: []string{"turtle", "wombat"}, - } - expected := Clone(m) - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestMaximumTagNumber(t *testing.T) { - m := &MaxTag{ - LastField: String("natural goat essence"), - } - buf, err := Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal failed: %v", err) - } - m2 := new(MaxTag) - if err := Unmarshal(buf, m2); err != nil { - t.Fatalf("proto.Unmarshal failed: %v", err) - } - if got, want := m2.GetLastField(), *m.LastField; got != want { - t.Errorf("got %q, want %q", got, want) - } -} - -func TestJSON(t *testing.T) { - m := &MyMessage{ - Count: Int32(4), - Pet: []string{"bunny", "kitty"}, - Inner: &InnerMessage{ - Host: String("cauchy"), - }, - Bikeshed: MyMessage_GREEN.Enum(), - } - const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}` - - b, err := json.Marshal(m) - if err != nil { - t.Fatalf("json.Marshal failed: %v", err) - } - s := string(b) - if s != expected { - t.Errorf("got %s\nwant %s", s, expected) - } - - received := new(MyMessage) - if err := json.Unmarshal(b, received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } - - // Test unmarshalling of JSON with symbolic enum name. - const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}` - received.Reset() - if err := json.Unmarshal([]byte(old), received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } -} - -func TestBadWireType(t *testing.T) { - b := []byte{7<<3 | 6} // field 7, wire type 6 - pb := new(OtherMessage) - if err := Unmarshal(b, pb); err == nil { - t.Errorf("Unmarshal did not fail") - } else if !strings.Contains(err.Error(), "unknown wire type") { - t.Errorf("wrong error: %v", err) - } -} - -func TestBytesWithInvalidLength(t *testing.T) { - // If a byte sequence has an invalid (negative) length, Unmarshal should not panic. - b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0} - Unmarshal(b, new(MyMessage)) -} - -func TestLengthOverflow(t *testing.T) { - // Overflowing a length should not panic. - b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01} - Unmarshal(b, new(MyMessage)) -} - -func TestVarintOverflow(t *testing.T) { - // Overflowing a 64-bit length should not be allowed. - b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01} - if err := Unmarshal(b, new(MyMessage)); err == nil { - t.Fatalf("Overflowed uint64 length without error") - } -} - -func TestUnmarshalFuzz(t *testing.T) { - const N = 1000 - seed := time.Now().UnixNano() - t.Logf("RNG seed is %d", seed) - rng := rand.New(rand.NewSource(seed)) - buf := make([]byte, 20) - for i := 0; i < N; i++ { - for j := range buf { - buf[j] = byte(rng.Intn(256)) - } - fuzzUnmarshal(t, buf) - } -} - -func TestMergeMessages(t *testing.T) { - pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}} - data, err := Marshal(pb) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - pb1 := new(MessageList) - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("first Unmarshal: %v", err) - } - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("second Unmarshal: %v", err) - } - if len(pb1.Message) != 1 { - t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message)) - } - - pb2 := new(MessageList) - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("first UnmarshalMerge: %v", err) - } - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("second UnmarshalMerge: %v", err) - } - if len(pb2.Message) != 2 { - t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message)) - } -} - -func TestExtensionMarshalOrder(t *testing.T) { - m := &MyMessage{Count: Int(123)} - if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil { - t.Fatalf("SetExtension: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - var orig []byte - for i := 0; i < 100; i++ { - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if i == 0 { - orig = b - continue - } - if !bytes.Equal(b, orig) { - t.Errorf("Bytes differ on attempt #%d", i) - } - } -} - -// Many extensions, because small maps might not iterate differently on each iteration. -var exts = []*ExtensionDesc{ - E_X201, - E_X202, - E_X203, - E_X204, - E_X205, - E_X206, - E_X207, - E_X208, - E_X209, - E_X210, - E_X211, - E_X212, - E_X213, - E_X214, - E_X215, - E_X216, - E_X217, - E_X218, - E_X219, - E_X220, - E_X221, - E_X222, - E_X223, - E_X224, - E_X225, - E_X226, - E_X227, - E_X228, - E_X229, - E_X230, - E_X231, - E_X232, - E_X233, - E_X234, - E_X235, - E_X236, - E_X237, - E_X238, - E_X239, - E_X240, - E_X241, - E_X242, - E_X243, - E_X244, - E_X245, - E_X246, - E_X247, - E_X248, - E_X249, - E_X250, -} - -func TestMessageSetMarshalOrder(t *testing.T) { - m := &MyMessageSet{} - for _, x := range exts { - if err := SetExtension(m, x, &Empty{}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - } - - buf, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - for i := 0; i < 10; i++ { - b1, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if !bytes.Equal(b1, buf) { - t.Errorf("Bytes differ on re-Marshal #%d", i) - } - - m2 := &MyMessageSet{} - if err := Unmarshal(buf, m2); err != nil { - t.Errorf("Unmarshal: %v", err) - } - b2, err := Marshal(m2) - if err != nil { - t.Errorf("re-Marshal: %v", err) - } - if !bytes.Equal(b2, buf) { - t.Errorf("Bytes differ on round-trip #%d", i) - } - } -} - -func TestUnmarshalMergesMessages(t *testing.T) { - // If a nested message occurs twice in the input, - // the fields should be merged when decoding. - a := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("polhode"), - Port: Int32(1234), - }, - } - aData, err := Marshal(a) - if err != nil { - t.Fatalf("Marshal(a): %v", err) - } - b := &OtherMessage{ - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Connected: Bool(true), - }, - } - bData, err := Marshal(b) - if err != nil { - t.Fatalf("Marshal(b): %v", err) - } - want := &OtherMessage{ - Key: Int64(123), - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Port: Int32(1234), - Connected: Bool(true), - }, - } - got := new(OtherMessage) - if err := Unmarshal(append(aData, bData...), got); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !Equal(got, want) { - t.Errorf("\n got %v\nwant %v", got, want) - } -} - -func TestEncodingSizes(t *testing.T) { - tests := []struct { - m Message - n int - }{ - {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6}, - {&Defaults{F_Int32: Int32(math.MinInt32)}, 11}, - {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6}, - {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6}, - } - for _, test := range tests { - b, err := Marshal(test.m) - if err != nil { - t.Errorf("Marshal(%v): %v", test.m, err) - continue - } - if len(b) != test.n { - t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n) - } - } -} - -func TestRequiredNotSetError(t *testing.T) { - pb := initGoTest(false) - pb.RequiredField.Label = nil - pb.F_Int32Required = nil - pb.F_Int64Required = nil - - expected := "0807" + // field 1, encoding 0, value 7 - "2206" + "120474797065" + // field 4, encoding 2 (GoTestField) - "5001" + // field 10, encoding 0, value 1 - "6d20000000" + // field 13, encoding 5, value 0x20 - "714000000000000000" + // field 14, encoding 1, value 0x40 - "78a019" + // field 15, encoding 0, value 0xca0 = 3232 - "8001c032" + // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45" + // field 17, encoding 5, value 3232.0 - "9101000000000040b940" + // field 18, encoding 1, value 6464.0 - "9a0106" + "737472696e67" + // field 19, encoding 2, string "string" - "b304" + // field 70, encoding 3, start group - "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required" - "b404" + // field 70, encoding 4, end group - "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes" - "b0063f" + // field 102, encoding 0, 0x3f zigzag32 - "b8067f" // field 103, encoding 0, 0x7f zigzag64 - - o := old() - bytes, err := Marshal(pb) - if _, ok := err.(*RequiredNotSetError); !ok { - fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("expected = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-1 wrong err msg: %v", err) - } - if !equal(bytes, expected, t) { - o.DebugPrint("neq 1", bytes) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = Unmarshal(bytes, pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.{Unknown}") < 0 { - t.Errorf("unmarshal wrong err msg: %v", err) - } - bytes, err = Marshal(pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-2 wrong err msg: %v", err) - } - if !equal(bytes, expected, t) { - o.DebugPrint("neq 2", bytes) - t.Fatalf("string = %s", expected) - } -} - -func fuzzUnmarshal(t *testing.T, data []byte) { - defer func() { - if e := recover(); e != nil { - t.Errorf("These bytes caused a panic: %+v", data) - t.Logf("Stack:\n%s", debug.Stack()) - t.FailNow() - } - }() - - pb := new(MyMessage) - Unmarshal(data, pb) -} - -func TestMapFieldMarshal(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // b should be the concatenation of these three byte sequences in some order. - parts := []string{ - "\n\a\b\x01\x12\x03Rob", - "\n\a\b\x04\x12\x03Ian", - "\n\b\b\x08\x12\x04Dave", - } - ok := false - for i := range parts { - for j := range parts { - if j == i { - continue - } - for k := range parts { - if k == i || k == j { - continue - } - try := parts[i] + parts[j] + parts[k] - if bytes.Equal(b, []byte(try)) { - ok = true - break - } - } - } - } - if !ok { - t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2]) - } - t.Logf("FYI b: %q", b) - - (new(Buffer)).DebugPrint("Dump of b", b) -} - -func TestMapFieldRoundTrips(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - MsgMapping: map[int64]*FloatingPoint{ - 0x7001: &FloatingPoint{F: Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{ - false: []byte("that's not right!"), - true: []byte("aye, 'tis true!"), - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("FYI b: %q", b) - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - for _, pair := range [][2]interface{}{ - {m.NameMapping, m2.NameMapping}, - {m.MsgMapping, m2.MsgMapping}, - {m.ByteMapping, m2.ByteMapping}, - } { - if !reflect.DeepEqual(pair[0], pair[1]) { - t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", pair[0], pair[1]) - } - } -} - -func TestMapFieldWithNil(t *testing.T) { - m1 := &MessageWithMap{ - MsgMapping: map[int64]*FloatingPoint{ - 1: nil, - }, - } - b, err := Marshal(m1) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b) - } - if v, ok := m2.MsgMapping[1]; !ok { - t.Error("msg_mapping[1] not present") - } else if v != nil { - t.Errorf("msg_mapping[1] not nil: %v", v) - } -} - -func TestMapFieldWithNilBytes(t *testing.T) { - m1 := &MessageWithMap{ - ByteMapping: map[bool][]byte{ - false: []byte{}, - true: nil, - }, - } - n := Size(m1) - b, err := Marshal(m1) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if n != len(b) { - t.Errorf("Size(m1) = %d; want len(Marshal(m1)) = %d", n, len(b)) - } - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b) - } - if v, ok := m2.ByteMapping[false]; !ok { - t.Error("byte_mapping[false] not present") - } else if len(v) != 0 { - t.Errorf("byte_mapping[false] not empty: %#v", v) - } - if v, ok := m2.ByteMapping[true]; !ok { - t.Error("byte_mapping[true] not present") - } else if len(v) != 0 { - t.Errorf("byte_mapping[true] not empty: %#v", v) - } -} - -func TestDecodeMapFieldMissingKey(t *testing.T) { - b := []byte{ - 0x0A, 0x03, // message, tag 1 (name_mapping), of length 3 bytes - // no key - 0x12, 0x01, 0x6D, // string value of length 1 byte, value "m" - } - got := &MessageWithMap{} - err := Unmarshal(b, got) - if err != nil { - t.Fatalf("failed to marshal map with missing key: %v", err) - } - want := &MessageWithMap{NameMapping: map[int32]string{0: "m"}} - if !Equal(got, want) { - t.Errorf("Unmarshaled map with no key was not as expected. got: %v, want %v", got, want) - } -} - -func TestDecodeMapFieldMissingValue(t *testing.T) { - b := []byte{ - 0x0A, 0x02, // message, tag 1 (name_mapping), of length 2 bytes - 0x08, 0x01, // varint key, value 1 - // no value - } - got := &MessageWithMap{} - err := Unmarshal(b, got) - if err != nil { - t.Fatalf("failed to marshal map with missing value: %v", err) - } - want := &MessageWithMap{NameMapping: map[int32]string{1: ""}} - if !Equal(got, want) { - t.Errorf("Unmarshaled map with no value was not as expected. got: %v, want %v", got, want) - } -} - -func TestOneof(t *testing.T) { - m := &Communique{} - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal of empty message with oneof: %v", err) - } - if len(b) != 0 { - t.Errorf("Marshal of empty message yielded too many bytes: %v", b) - } - - m = &Communique{ - Union: &Communique_Name{"Barry"}, - } - - // Round-trip. - b, err = Marshal(m) - if err != nil { - t.Fatalf("Marshal of message with oneof: %v", err) - } - if len(b) != 7 { // name tag/wire (1) + name len (1) + name (5) - t.Errorf("Incorrect marshal of message with oneof: %v", b) - } - m.Reset() - if err := Unmarshal(b, m); err != nil { - t.Fatalf("Unmarshal of message with oneof: %v", err) - } - if x, ok := m.Union.(*Communique_Name); !ok || x.Name != "Barry" { - t.Errorf("After round trip, Union = %+v", m.Union) - } - if name := m.GetName(); name != "Barry" { - t.Errorf("After round trip, GetName = %q, want %q", name, "Barry") - } - - // Let's try with a message in the oneof. - m.Union = &Communique_Msg{&Strings{StringField: String("deep deep string")}} - b, err = Marshal(m) - if err != nil { - t.Fatalf("Marshal of message with oneof set to message: %v", err) - } - if len(b) != 20 { // msg tag/wire (1) + msg len (1) + msg (1 + 1 + 16) - t.Errorf("Incorrect marshal of message with oneof set to message: %v", b) - } - m.Reset() - if err := Unmarshal(b, m); err != nil { - t.Fatalf("Unmarshal of message with oneof set to message: %v", err) - } - ss, ok := m.Union.(*Communique_Msg) - if !ok || ss.Msg.GetStringField() != "deep deep string" { - t.Errorf("After round trip with oneof set to message, Union = %+v", m.Union) - } -} - -func TestInefficientPackedBool(t *testing.T) { - // https://github.com/golang/protobuf/issues/76 - inp := []byte{ - 0x12, 0x02, // 0x12 = 2<<3|2; 2 bytes - // Usually a bool should take a single byte, - // but it is permitted to be any varint. - 0xb9, 0x30, - } - if err := Unmarshal(inp, new(MoreRepeated)); err != nil { - t.Error(err) - } -} - -// Benchmarks - -func testMsg() *GoTest { - pb := initGoTest(true) - const N = 1000 // Internally the library starts much smaller. - pb.F_Int32Repeated = make([]int32, N) - pb.F_DoubleRepeated = make([]float64, N) - for i := 0; i < N; i++ { - pb.F_Int32Repeated[i] = int32(i) - pb.F_DoubleRepeated[i] = float64(i) - } - return pb -} - -func bytesMsg() *GoTest { - pb := initGoTest(true) - buf := make([]byte, 4000) - for i := range buf { - buf[i] = byte(i) - } - pb.F_BytesDefaulted = buf - return pb -} - -func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) { - d, _ := marshal(pb) - b.SetBytes(int64(len(d))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - marshal(pb) - } -} - -func benchmarkBufferMarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - p.Reset() - err := p.Marshal(pb0) - return p.Bytes(), err - }) -} - -func benchmarkSize(b *testing.B, pb Message) { - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - Size(pb) - return nil, nil - }) -} - -func newOf(pb Message) Message { - in := reflect.ValueOf(pb) - if in.IsNil() { - return pb - } - return reflect.New(in.Type().Elem()).Interface().(Message) -} - -func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) { - d, _ := Marshal(pb) - b.SetBytes(int64(len(d))) - pbd := newOf(pb) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - unmarshal(d, pbd) - } -} - -func benchmarkBufferUnmarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error { - p.SetBuf(d) - return p.Unmarshal(pb0) - }) -} - -// Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes} - -func BenchmarkMarshal(b *testing.B) { - benchmarkMarshal(b, testMsg(), Marshal) -} - -func BenchmarkBufferMarshal(b *testing.B) { - benchmarkBufferMarshal(b, testMsg()) -} - -func BenchmarkSize(b *testing.B) { - benchmarkSize(b, testMsg()) -} - -func BenchmarkUnmarshal(b *testing.B) { - benchmarkUnmarshal(b, testMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshal(b *testing.B) { - benchmarkBufferUnmarshal(b, testMsg()) -} - -func BenchmarkMarshalBytes(b *testing.B) { - benchmarkMarshal(b, bytesMsg(), Marshal) -} - -func BenchmarkBufferMarshalBytes(b *testing.B) { - benchmarkBufferMarshal(b, bytesMsg()) -} - -func BenchmarkSizeBytes(b *testing.B) { - benchmarkSize(b, bytesMsg()) -} - -func BenchmarkUnmarshalBytes(b *testing.B) { - benchmarkUnmarshal(b, bytesMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshalBytes(b *testing.B) { - benchmarkBufferUnmarshal(b, bytesMsg()) -} - -func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) { - b.StopTimer() - pb := initGoTestField() - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - pbd := new(GoTestField) - p := NewBuffer(nil) - p.Marshal(pb) - p.Marshal(skip) - p2 := NewBuffer(nil) - - b.StartTimer() - for i := 0; i < b.N; i++ { - p2.SetBuf(p.Bytes()) - p2.Unmarshal(pbd) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/any_test.go b/vendor/github.com/golang/protobuf/proto/any_test.go deleted file mode 100644 index 1a3c22ed4160..000000000000 --- a/vendor/github.com/golang/protobuf/proto/any_test.go +++ /dev/null @@ -1,300 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "strings" - "testing" - - "github.com/golang/protobuf/proto" - - pb "github.com/golang/protobuf/proto/proto3_proto" - testpb "github.com/golang/protobuf/proto/testdata" - anypb "github.com/golang/protobuf/ptypes/any" -) - -var ( - expandedMarshaler = proto.TextMarshaler{ExpandAny: true} - expandedCompactMarshaler = proto.TextMarshaler{Compact: true, ExpandAny: true} -) - -// anyEqual reports whether two messages which may be google.protobuf.Any or may -// contain google.protobuf.Any fields are equal. We can't use proto.Equal for -// comparison, because semantically equivalent messages may be marshaled to -// binary in different tag order. Instead, trust that TextMarshaler with -// ExpandAny option works and compare the text marshaling results. -func anyEqual(got, want proto.Message) bool { - // if messages are proto.Equal, no need to marshal. - if proto.Equal(got, want) { - return true - } - g := expandedMarshaler.Text(got) - w := expandedMarshaler.Text(want) - return g == w -} - -type golden struct { - m proto.Message - t, c string -} - -var goldenMessages = makeGolden() - -func makeGolden() []golden { - nested := &pb.Nested{Bunny: "Monty"} - nb, err := proto.Marshal(nested) - if err != nil { - panic(err) - } - m1 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb}, - } - m2 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "http://[::1]/type.googleapis.com/" + proto.MessageName(nested), Value: nb}, - } - m3 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: `type.googleapis.com/"/` + proto.MessageName(nested), Value: nb}, - } - m4 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "type.googleapis.com/a/path/" + proto.MessageName(nested), Value: nb}, - } - m5 := &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb} - - any1 := &testpb.MyMessage{Count: proto.Int32(47), Name: proto.String("David")} - proto.SetExtension(any1, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("foo")}) - proto.SetExtension(any1, testpb.E_Ext_Text, proto.String("bar")) - any1b, err := proto.Marshal(any1) - if err != nil { - panic(err) - } - any2 := &testpb.MyMessage{Count: proto.Int32(42), Bikeshed: testpb.MyMessage_GREEN.Enum(), RepBytes: [][]byte{[]byte("roboto")}} - proto.SetExtension(any2, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("baz")}) - any2b, err := proto.Marshal(any2) - if err != nil { - panic(err) - } - m6 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b}, - ManyThings: []*anypb.Any{ - &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any2), Value: any2b}, - &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b}, - }, - } - - const ( - m1Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/proto3_proto.Nested]: < - bunny: "Monty" - > -> -` - m2Golden = ` -name: "David" -result_count: 47 -anything: < - ["http://[::1]/type.googleapis.com/proto3_proto.Nested"]: < - bunny: "Monty" - > -> -` - m3Golden = ` -name: "David" -result_count: 47 -anything: < - ["type.googleapis.com/\"/proto3_proto.Nested"]: < - bunny: "Monty" - > -> -` - m4Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Monty" - > -> -` - m5Golden = ` -[type.googleapis.com/proto3_proto.Nested]: < - bunny: "Monty" -> -` - m6Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/testdata.MyMessage]: < - count: 47 - name: "David" - [testdata.Ext.more]: < - data: "foo" - > - [testdata.Ext.text]: "bar" - > -> -many_things: < - [type.googleapis.com/testdata.MyMessage]: < - count: 42 - bikeshed: GREEN - rep_bytes: "roboto" - [testdata.Ext.more]: < - data: "baz" - > - > -> -many_things: < - [type.googleapis.com/testdata.MyMessage]: < - count: 47 - name: "David" - [testdata.Ext.more]: < - data: "foo" - > - [testdata.Ext.text]: "bar" - > -> -` - ) - return []golden{ - {m1, strings.TrimSpace(m1Golden) + "\n", strings.TrimSpace(compact(m1Golden)) + " "}, - {m2, strings.TrimSpace(m2Golden) + "\n", strings.TrimSpace(compact(m2Golden)) + " "}, - {m3, strings.TrimSpace(m3Golden) + "\n", strings.TrimSpace(compact(m3Golden)) + " "}, - {m4, strings.TrimSpace(m4Golden) + "\n", strings.TrimSpace(compact(m4Golden)) + " "}, - {m5, strings.TrimSpace(m5Golden) + "\n", strings.TrimSpace(compact(m5Golden)) + " "}, - {m6, strings.TrimSpace(m6Golden) + "\n", strings.TrimSpace(compact(m6Golden)) + " "}, - } -} - -func TestMarshalGolden(t *testing.T) { - for _, tt := range goldenMessages { - if got, want := expandedMarshaler.Text(tt.m), tt.t; got != want { - t.Errorf("message %v: got:\n%s\nwant:\n%s", tt.m, got, want) - } - if got, want := expandedCompactMarshaler.Text(tt.m), tt.c; got != want { - t.Errorf("message %v: got:\n`%s`\nwant:\n`%s`", tt.m, got, want) - } - } -} - -func TestUnmarshalGolden(t *testing.T) { - for _, tt := range goldenMessages { - want := tt.m - got := proto.Clone(tt.m) - got.Reset() - if err := proto.UnmarshalText(tt.t, got); err != nil { - t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.t, err) - } - if !anyEqual(got, want) { - t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.t, got, want) - } - got.Reset() - if err := proto.UnmarshalText(tt.c, got); err != nil { - t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.c, err) - } - if !anyEqual(got, want) { - t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.c, got, want) - } - } -} - -func TestMarshalUnknownAny(t *testing.T) { - m := &pb.Message{ - Anything: &anypb.Any{ - TypeUrl: "foo", - Value: []byte("bar"), - }, - } - want := `anything: < - type_url: "foo" - value: "bar" -> -` - got := expandedMarshaler.Text(m) - if got != want { - t.Errorf("got\n`%s`\nwant\n`%s`", got, want) - } -} - -func TestAmbiguousAny(t *testing.T) { - pb := &anypb.Any{} - err := proto.UnmarshalText(` - type_url: "ttt/proto3_proto.Nested" - value: "\n\x05Monty" - `, pb) - t.Logf("result: %v (error: %v)", expandedMarshaler.Text(pb), err) - if err != nil { - t.Errorf("failed to parse ambiguous Any message: %v", err) - } -} - -func TestUnmarshalOverwriteAny(t *testing.T) { - pb := &anypb.Any{} - err := proto.UnmarshalText(` - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Monty" - > - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Rabbit of Caerbannog" - > - `, pb) - want := `line 7: Any message unpacked multiple times, or "type_url" already set` - if err.Error() != want { - t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want) - } -} - -func TestUnmarshalAnyMixAndMatch(t *testing.T) { - pb := &anypb.Any{} - err := proto.UnmarshalText(` - value: "\n\x05Monty" - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Rabbit of Caerbannog" - > - `, pb) - want := `line 5: Any message unpacked multiple times, or "value" already set` - if err.Error() != want { - t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/clone_test.go b/vendor/github.com/golang/protobuf/proto/clone_test.go deleted file mode 100644 index f607ff49eba0..000000000000 --- a/vendor/github.com/golang/protobuf/proto/clone_test.go +++ /dev/null @@ -1,300 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "testing" - - "github.com/golang/protobuf/proto" - - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - pb "github.com/golang/protobuf/proto/testdata" -) - -var cloneTestMessage = &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, -} - -func init() { - ext := &pb.Ext{ - Data: proto.String("extension"), - } - if err := proto.SetExtension(cloneTestMessage, pb.E_Ext_More, ext); err != nil { - panic("SetExtension: " + err.Error()) - } -} - -func TestClone(t *testing.T) { - m := proto.Clone(cloneTestMessage).(*pb.MyMessage) - if !proto.Equal(m, cloneTestMessage) { - t.Errorf("Clone(%v) = %v", cloneTestMessage, m) - } - - // Verify it was a deep copy. - *m.Inner.Port++ - if proto.Equal(m, cloneTestMessage) { - t.Error("Mutating clone changed the original") - } - // Byte fields and repeated fields should be copied. - if &m.Pet[0] == &cloneTestMessage.Pet[0] { - t.Error("Pet: repeated field not copied") - } - if &m.Others[0] == &cloneTestMessage.Others[0] { - t.Error("Others: repeated field not copied") - } - if &m.Others[0].Value[0] == &cloneTestMessage.Others[0].Value[0] { - t.Error("Others[0].Value: bytes field not copied") - } - if &m.RepBytes[0] == &cloneTestMessage.RepBytes[0] { - t.Error("RepBytes: repeated field not copied") - } - if &m.RepBytes[0][0] == &cloneTestMessage.RepBytes[0][0] { - t.Error("RepBytes[0]: bytes field not copied") - } -} - -func TestCloneNil(t *testing.T) { - var m *pb.MyMessage - if c := proto.Clone(m); !proto.Equal(m, c) { - t.Errorf("Clone(%v) = %v", m, c) - } -} - -var mergeTests = []struct { - src, dst, want proto.Message -}{ - { - src: &pb.MyMessage{ - Count: proto.Int32(42), - }, - dst: &pb.MyMessage{ - Name: proto.String("Dave"), - }, - want: &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - }, - }, - { - src: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - }, - Pet: []string{"horsey"}, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - }, - dst: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - { - // Explicitly test a src=nil field - Inner: nil, - }, - }, - }, - want: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty", "horsey"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - {}, - { - Value: []byte("some bytes"), - }, - }, - }, - }, - { - src: &pb.MyMessage{ - RepBytes: [][]byte{[]byte("wow")}, - }, - dst: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham")}, - }, - want: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, - }, - }, - // Check that a scalar bytes field replaces rather than appends. - { - src: &pb.OtherMessage{Value: []byte("foo")}, - dst: &pb.OtherMessage{Value: []byte("bar")}, - want: &pb.OtherMessage{Value: []byte("foo")}, - }, - { - src: &pb.MessageWithMap{ - NameMapping: map[int32]string{6: "Nigel"}, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, - 0x4002: &pb.FloatingPoint{ - F: proto.Float64(2.0), - }, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - dst: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Bruce", // should be overwritten - 7: "Andrew", - }, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4002: &pb.FloatingPoint{ - F: proto.Float64(3.0), - Exact: proto.Bool(true), - }, // the entire message should be overwritten - }, - }, - want: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Nigel", - 7: "Andrew", - }, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, - 0x4002: &pb.FloatingPoint{ - F: proto.Float64(2.0), - }, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - }, - // proto3 shouldn't merge zero values, - // in the same way that proto2 shouldn't merge nils. - { - src: &proto3pb.Message{ - Name: "Aaron", - Data: []byte(""), // zero value, but not nil - }, - dst: &proto3pb.Message{ - HeightInCm: 176, - Data: []byte("texas!"), - }, - want: &proto3pb.Message{ - Name: "Aaron", - HeightInCm: 176, - Data: []byte("texas!"), - }, - }, - // Oneof fields should merge by assignment. - { - src: &pb.Communique{ - Union: &pb.Communique_Number{41}, - }, - dst: &pb.Communique{ - Union: &pb.Communique_Name{"Bobby Tables"}, - }, - want: &pb.Communique{ - Union: &pb.Communique_Number{41}, - }, - }, - // Oneof nil is the same as not set. - { - src: &pb.Communique{}, - dst: &pb.Communique{ - Union: &pb.Communique_Name{"Bobby Tables"}, - }, - want: &pb.Communique{ - Union: &pb.Communique_Name{"Bobby Tables"}, - }, - }, - { - src: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": &proto3pb.Nested{Cute: true}, // replace - "kay_b": &proto3pb.Nested{Bunny: "rabbit"}, // insert - }, - }, - dst: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": &proto3pb.Nested{Bunny: "lost"}, // replaced - "kay_c": &proto3pb.Nested{Bunny: "bunny"}, // keep - }, - }, - want: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": &proto3pb.Nested{Cute: true}, - "kay_b": &proto3pb.Nested{Bunny: "rabbit"}, - "kay_c": &proto3pb.Nested{Bunny: "bunny"}, - }, - }, - }, -} - -func TestMerge(t *testing.T) { - for _, m := range mergeTests { - got := proto.Clone(m.dst) - proto.Merge(got, m.src) - if !proto.Equal(got, m.want) { - t.Errorf("Merge(%v, %v)\n got %v\nwant %v\n", m.dst, m.src, got, m.want) - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/decode_test.go b/vendor/github.com/golang/protobuf/proto/decode_test.go deleted file mode 100644 index b1f1304493e8..000000000000 --- a/vendor/github.com/golang/protobuf/proto/decode_test.go +++ /dev/null @@ -1,256 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "fmt" - "testing" - - "github.com/golang/protobuf/proto" - tpb "github.com/golang/protobuf/proto/proto3_proto" -) - -var ( - bytesBlackhole []byte - msgBlackhole = new(tpb.Message) -) - -// BenchmarkVarint32ArraySmall shows the performance on an array of small int32 fields (1 and -// 2 bytes long). -func BenchmarkVarint32ArraySmall(b *testing.B) { - for i := uint(1); i <= 10; i++ { - dist := genInt32Dist([7]int{0, 3, 1}, 1<unmarshal. -} - -func TestMarshalUnmarshalRepeatedExtension(t *testing.T) { - // Add a repeated extension to the result. - tests := []struct { - name string - ext []*pb.ComplexExtension - }{ - { - "two fields", - []*pb.ComplexExtension{ - {First: proto.Int32(7)}, - {Second: proto.Int32(11)}, - }, - }, - { - "repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {Third: []int32{2000}}, - }, - }, - { - "two fields and repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {First: proto.Int32(9)}, - {Second: proto.Int32(21)}, - {Third: []int32{2000}}, - }, - }, - } - for _, test := range tests { - // Marshal message with a repeated extension. - msg1 := new(pb.OtherMessage) - err := proto.SetExtension(msg1, pb.E_RComplex, test.ext) - if err != nil { - t.Fatalf("[%s] Error setting extension: %v", test.name, err) - } - b, err := proto.Marshal(msg1) - if err != nil { - t.Fatalf("[%s] Error marshaling message: %v", test.name, err) - } - - // Unmarshal and read the merged proto. - msg2 := new(pb.OtherMessage) - err = proto.Unmarshal(b, msg2) - if err != nil { - t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) - } - e, err := proto.GetExtension(msg2, pb.E_RComplex) - if err != nil { - t.Fatalf("[%s] Error getting extension: %v", test.name, err) - } - ext := e.([]*pb.ComplexExtension) - if ext == nil { - t.Fatalf("[%s] Invalid extension", test.name) - } - if !reflect.DeepEqual(ext, test.ext) { - t.Errorf("[%s] Wrong value for ComplexExtension: got: %v want: %v\n", test.name, ext, test.ext) - } - } -} - -func TestUnmarshalRepeatingNonRepeatedExtension(t *testing.T) { - // We may see multiple instances of the same extension in the wire - // format. For example, the proto compiler may encode custom options in - // this way. Here, we verify that we merge the extensions together. - tests := []struct { - name string - ext []*pb.ComplexExtension - }{ - { - "two fields", - []*pb.ComplexExtension{ - {First: proto.Int32(7)}, - {Second: proto.Int32(11)}, - }, - }, - { - "repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {Third: []int32{2000}}, - }, - }, - { - "two fields and repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {First: proto.Int32(9)}, - {Second: proto.Int32(21)}, - {Third: []int32{2000}}, - }, - }, - } - for _, test := range tests { - var buf bytes.Buffer - var want pb.ComplexExtension - - // Generate a serialized representation of a repeated extension - // by catenating bytes together. - for i, e := range test.ext { - // Merge to create the wanted proto. - proto.Merge(&want, e) - - // serialize the message - msg := new(pb.OtherMessage) - err := proto.SetExtension(msg, pb.E_Complex, e) - if err != nil { - t.Fatalf("[%s] Error setting extension %d: %v", test.name, i, err) - } - b, err := proto.Marshal(msg) - if err != nil { - t.Fatalf("[%s] Error marshaling message %d: %v", test.name, i, err) - } - buf.Write(b) - } - - // Unmarshal and read the merged proto. - msg2 := new(pb.OtherMessage) - err := proto.Unmarshal(buf.Bytes(), msg2) - if err != nil { - t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) - } - e, err := proto.GetExtension(msg2, pb.E_Complex) - if err != nil { - t.Fatalf("[%s] Error getting extension: %v", test.name, err) - } - ext := e.(*pb.ComplexExtension) - if ext == nil { - t.Fatalf("[%s] Invalid extension", test.name) - } - if !reflect.DeepEqual(*ext, want) { - t.Errorf("[%s] Wrong value for ComplexExtension: got: %s want: %s\n", test.name, ext, want) - } - } -} - -func TestClearAllExtensions(t *testing.T) { - // unregistered extension - desc := &proto.ExtensionDesc{ - ExtendedType: (*pb.MyMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 101010100, - Name: "emptyextension", - Tag: "varint,0,opt", - } - m := &pb.MyMessage{} - if proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m)) - } - if err := proto.SetExtension(m, desc, proto.Bool(true)); err != nil { - t.Errorf("proto.SetExtension(m, desc, true): got error %q, want nil", err) - } - if !proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got false, want true", proto.MarshalTextString(m)) - } - proto.ClearAllExtensions(m) - if proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m)) - } -} - -func TestMarshalRace(t *testing.T) { - // unregistered extension - desc := &proto.ExtensionDesc{ - ExtendedType: (*pb.MyMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 101010100, - Name: "emptyextension", - Tag: "varint,0,opt", - } - - m := &pb.MyMessage{Count: proto.Int32(4)} - if err := proto.SetExtension(m, desc, proto.Bool(true)); err != nil { - t.Errorf("proto.SetExtension(m, desc, true): got error %q, want nil", err) - } - - var g errgroup.Group - for n := 3; n > 0; n-- { - g.Go(func() error { - _, err := proto.Marshal(m) - return err - }) - } - if err := g.Wait(); err != nil { - t.Fatal(err) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/map_test.go b/vendor/github.com/golang/protobuf/proto/map_test.go deleted file mode 100644 index 313e8792452f..000000000000 --- a/vendor/github.com/golang/protobuf/proto/map_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package proto_test - -import ( - "fmt" - "testing" - - "github.com/golang/protobuf/proto" - ppb "github.com/golang/protobuf/proto/proto3_proto" -) - -func marshalled() []byte { - m := &ppb.IntMaps{} - for i := 0; i < 1000; i++ { - m.Maps = append(m.Maps, &ppb.IntMap{ - Rtt: map[int32]int32{1: 2}, - }) - } - b, err := proto.Marshal(m) - if err != nil { - panic(fmt.Sprintf("Can't marshal %+v: %v", m, err)) - } - return b -} - -func BenchmarkConcurrentMapUnmarshal(b *testing.B) { - in := marshalled() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - var out ppb.IntMaps - if err := proto.Unmarshal(in, &out); err != nil { - b.Errorf("Can't unmarshal ppb.IntMaps: %v", err) - } - } - }) -} - -func BenchmarkSequentialMapUnmarshal(b *testing.B) { - in := marshalled() - b.ResetTimer() - for i := 0; i < b.N; i++ { - var out ppb.IntMaps - if err := proto.Unmarshal(in, &out); err != nil { - b.Errorf("Can't unmarshal ppb.IntMaps: %v", err) - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/message_set_test.go b/vendor/github.com/golang/protobuf/proto/message_set_test.go deleted file mode 100644 index 353a3ea7694b..000000000000 --- a/vendor/github.com/golang/protobuf/proto/message_set_test.go +++ /dev/null @@ -1,66 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "bytes" - "testing" -) - -func TestUnmarshalMessageSetWithDuplicate(t *testing.T) { - // Check that a repeated message set entry will be concatenated. - in := &messageSet{ - Item: []*_MessageSet_Item{ - {TypeId: Int32(12345), Message: []byte("hoo")}, - {TypeId: Int32(12345), Message: []byte("hah")}, - }, - } - b, err := Marshal(in) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("Marshaled bytes: %q", b) - - var extensions XXX_InternalExtensions - if err := UnmarshalMessageSet(b, &extensions); err != nil { - t.Fatalf("UnmarshalMessageSet: %v", err) - } - ext, ok := extensions.p.extensionMap[12345] - if !ok { - t.Fatalf("Didn't retrieve extension 12345; map is %v", extensions.p.extensionMap) - } - // Skip wire type/field number and length varints. - got := skipVarint(skipVarint(ext.enc)) - if want := []byte("hoohah"); !bytes.Equal(got, want) { - t.Errorf("Combined extension is %q, want %q", got, want) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/proto3_test.go b/vendor/github.com/golang/protobuf/proto/proto3_test.go deleted file mode 100644 index 735837f2de0e..000000000000 --- a/vendor/github.com/golang/protobuf/proto/proto3_test.go +++ /dev/null @@ -1,135 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "testing" - - "github.com/golang/protobuf/proto" - pb "github.com/golang/protobuf/proto/proto3_proto" - tpb "github.com/golang/protobuf/proto/testdata" -) - -func TestProto3ZeroValues(t *testing.T) { - tests := []struct { - desc string - m proto.Message - }{ - {"zero message", &pb.Message{}}, - {"empty bytes field", &pb.Message{Data: []byte{}}}, - } - for _, test := range tests { - b, err := proto.Marshal(test.m) - if err != nil { - t.Errorf("%s: proto.Marshal: %v", test.desc, err) - continue - } - if len(b) > 0 { - t.Errorf("%s: Encoding is non-empty: %q", test.desc, b) - } - } -} - -func TestRoundTripProto3(t *testing.T) { - m := &pb.Message{ - Name: "David", // (2 | 1<<3): 0x0a 0x05 "David" - Hilarity: pb.Message_PUNS, // (0 | 2<<3): 0x10 0x01 - HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01 - Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto" - ResultCount: 47, // (0 | 7<<3): 0x38 0x2f - TrueScotsman: true, // (0 | 8<<3): 0x40 0x01 - Score: 8.1, // (5 | 9<<3): 0x4d <8.1> - - Key: []uint64{1, 0xdeadbeef}, - Nested: &pb.Nested{ - Bunny: "Monty", - }, - } - t.Logf(" m: %v", m) - - b, err := proto.Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal: %v", err) - } - t.Logf(" b: %q", b) - - m2 := new(pb.Message) - if err := proto.Unmarshal(b, m2); err != nil { - t.Fatalf("proto.Unmarshal: %v", err) - } - t.Logf("m2: %v", m2) - - if !proto.Equal(m, m2) { - t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2) - } -} - -func TestGettersForBasicTypesExist(t *testing.T) { - var m pb.Message - if got := m.GetNested().GetBunny(); got != "" { - t.Errorf("m.GetNested().GetBunny() = %q, want empty string", got) - } - if got := m.GetNested().GetCute(); got { - t.Errorf("m.GetNested().GetCute() = %t, want false", got) - } -} - -func TestProto3SetDefaults(t *testing.T) { - in := &pb.Message{ - Terrain: map[string]*pb.Nested{ - "meadow": new(pb.Nested), - }, - Proto2Field: new(tpb.SubDefaults), - Proto2Value: map[string]*tpb.SubDefaults{ - "badlands": new(tpb.SubDefaults), - }, - } - - got := proto.Clone(in).(*pb.Message) - proto.SetDefaults(got) - - // There are no defaults in proto3. Everything should be the zero value, but - // we need to remember to set defaults for nested proto2 messages. - want := &pb.Message{ - Terrain: map[string]*pb.Nested{ - "meadow": new(pb.Nested), - }, - Proto2Field: &tpb.SubDefaults{N: proto.Int64(7)}, - Proto2Value: map[string]*tpb.SubDefaults{ - "badlands": &tpb.SubDefaults{N: proto.Int64(7)}, - }, - } - - if !proto.Equal(got, want) { - t.Errorf("with in = %v\nproto.SetDefaults(in) =>\ngot %v\nwant %v", in, got, want) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/size2_test.go b/vendor/github.com/golang/protobuf/proto/size2_test.go deleted file mode 100644 index a2729c39a1b8..000000000000 --- a/vendor/github.com/golang/protobuf/proto/size2_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "testing" -) - -// This is a separate file and package from size_test.go because that one uses -// generated messages and thus may not be in package proto without having a circular -// dependency, whereas this file tests unexported details of size.go. - -func TestVarintSize(t *testing.T) { - // Check the edge cases carefully. - testCases := []struct { - n uint64 - size int - }{ - {0, 1}, - {1, 1}, - {127, 1}, - {128, 2}, - {16383, 2}, - {16384, 3}, - {1<<63 - 1, 9}, - {1 << 63, 10}, - } - for _, tc := range testCases { - size := sizeVarint(tc.n) - if size != tc.size { - t.Errorf("sizeVarint(%d) = %d, want %d", tc.n, size, tc.size) - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/size_test.go b/vendor/github.com/golang/protobuf/proto/size_test.go deleted file mode 100644 index af1034dc7b89..000000000000 --- a/vendor/github.com/golang/protobuf/proto/size_test.go +++ /dev/null @@ -1,164 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "log" - "strings" - "testing" - - . "github.com/golang/protobuf/proto" - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - pb "github.com/golang/protobuf/proto/testdata" -) - -var messageWithExtension1 = &pb.MyMessage{Count: Int32(7)} - -// messageWithExtension2 is in equal_test.go. -var messageWithExtension3 = &pb.MyMessage{Count: Int32(8)} - -func init() { - if err := SetExtension(messageWithExtension1, pb.E_Ext_More, &pb.Ext{Data: String("Abbott")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - if err := SetExtension(messageWithExtension3, pb.E_Ext_More, &pb.Ext{Data: String("Costello")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - - // Force messageWithExtension3 to have the extension encoded. - Marshal(messageWithExtension3) - -} - -var SizeTests = []struct { - desc string - pb Message -}{ - {"empty", &pb.OtherMessage{}}, - // Basic types. - {"bool", &pb.Defaults{F_Bool: Bool(true)}}, - {"int32", &pb.Defaults{F_Int32: Int32(12)}}, - {"negative int32", &pb.Defaults{F_Int32: Int32(-1)}}, - {"small int64", &pb.Defaults{F_Int64: Int64(1)}}, - {"big int64", &pb.Defaults{F_Int64: Int64(1 << 20)}}, - {"negative int64", &pb.Defaults{F_Int64: Int64(-1)}}, - {"fixed32", &pb.Defaults{F_Fixed32: Uint32(71)}}, - {"fixed64", &pb.Defaults{F_Fixed64: Uint64(72)}}, - {"uint32", &pb.Defaults{F_Uint32: Uint32(123)}}, - {"uint64", &pb.Defaults{F_Uint64: Uint64(124)}}, - {"float", &pb.Defaults{F_Float: Float32(12.6)}}, - {"double", &pb.Defaults{F_Double: Float64(13.9)}}, - {"string", &pb.Defaults{F_String: String("niles")}}, - {"bytes", &pb.Defaults{F_Bytes: []byte("wowsa")}}, - {"bytes, empty", &pb.Defaults{F_Bytes: []byte{}}}, - {"sint32", &pb.Defaults{F_Sint32: Int32(65)}}, - {"sint64", &pb.Defaults{F_Sint64: Int64(67)}}, - {"enum", &pb.Defaults{F_Enum: pb.Defaults_BLUE.Enum()}}, - // Repeated. - {"empty repeated bool", &pb.MoreRepeated{Bools: []bool{}}}, - {"repeated bool", &pb.MoreRepeated{Bools: []bool{false, true, true, false}}}, - {"packed repeated bool", &pb.MoreRepeated{BoolsPacked: []bool{false, true, true, false, true, true, true}}}, - {"repeated int32", &pb.MoreRepeated{Ints: []int32{1, 12203, 1729, -1}}}, - {"repeated int32 packed", &pb.MoreRepeated{IntsPacked: []int32{1, 12203, 1729}}}, - {"repeated int64 packed", &pb.MoreRepeated{Int64SPacked: []int64{ - // Need enough large numbers to verify that the header is counting the number of bytes - // for the field, not the number of elements. - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - }}}, - {"repeated string", &pb.MoreRepeated{Strings: []string{"r", "ken", "gri"}}}, - {"repeated fixed", &pb.MoreRepeated{Fixeds: []uint32{1, 2, 3, 4}}}, - // Nested. - {"nested", &pb.OldMessage{Nested: &pb.OldMessage_Nested{Name: String("whatever")}}}, - {"group", &pb.GroupOld{G: &pb.GroupOld_G{X: Int32(12345)}}}, - // Other things. - {"unrecognized", &pb.MoreRepeated{XXX_unrecognized: []byte{13<<3 | 0, 4}}}, - {"extension (unencoded)", messageWithExtension1}, - {"extension (encoded)", messageWithExtension3}, - // proto3 message - {"proto3 empty", &proto3pb.Message{}}, - {"proto3 bool", &proto3pb.Message{TrueScotsman: true}}, - {"proto3 int64", &proto3pb.Message{ResultCount: 1}}, - {"proto3 uint32", &proto3pb.Message{HeightInCm: 123}}, - {"proto3 float", &proto3pb.Message{Score: 12.6}}, - {"proto3 string", &proto3pb.Message{Name: "Snezana"}}, - {"proto3 bytes", &proto3pb.Message{Data: []byte("wowsa")}}, - {"proto3 bytes, empty", &proto3pb.Message{Data: []byte{}}}, - {"proto3 enum", &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, - {"proto3 map field with empty bytes", &proto3pb.MessageWithMap{ByteMapping: map[bool][]byte{false: []byte{}}}}, - - {"map field", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob", 7: "Andrew"}}}, - {"map field with message", &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{0x7001: &pb.FloatingPoint{F: Float64(2.0)}}}}, - {"map field with bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte("this time for sure")}}}, - {"map field with empty bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte{}}}}, - - {"map field with big entry", &pb.MessageWithMap{NameMapping: map[int32]string{8: strings.Repeat("x", 125)}}}, - {"map field with big key and val", &pb.MessageWithMap{StrToStr: map[string]string{strings.Repeat("x", 70): strings.Repeat("y", 70)}}}, - {"map field with big numeric key", &pb.MessageWithMap{NameMapping: map[int32]string{0xf00d: "om nom nom"}}}, - - {"oneof not set", &pb.Oneof{}}, - {"oneof bool", &pb.Oneof{Union: &pb.Oneof_F_Bool{true}}}, - {"oneof zero int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{0}}}, - {"oneof big int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{1 << 20}}}, - {"oneof int64", &pb.Oneof{Union: &pb.Oneof_F_Int64{42}}}, - {"oneof fixed32", &pb.Oneof{Union: &pb.Oneof_F_Fixed32{43}}}, - {"oneof fixed64", &pb.Oneof{Union: &pb.Oneof_F_Fixed64{44}}}, - {"oneof uint32", &pb.Oneof{Union: &pb.Oneof_F_Uint32{45}}}, - {"oneof uint64", &pb.Oneof{Union: &pb.Oneof_F_Uint64{46}}}, - {"oneof float", &pb.Oneof{Union: &pb.Oneof_F_Float{47.1}}}, - {"oneof double", &pb.Oneof{Union: &pb.Oneof_F_Double{48.9}}}, - {"oneof string", &pb.Oneof{Union: &pb.Oneof_F_String{"Rhythmic Fman"}}}, - {"oneof bytes", &pb.Oneof{Union: &pb.Oneof_F_Bytes{[]byte("let go")}}}, - {"oneof sint32", &pb.Oneof{Union: &pb.Oneof_F_Sint32{50}}}, - {"oneof sint64", &pb.Oneof{Union: &pb.Oneof_F_Sint64{51}}}, - {"oneof enum", &pb.Oneof{Union: &pb.Oneof_F_Enum{pb.MyMessage_BLUE}}}, - {"message for oneof", &pb.GoTestField{Label: String("k"), Type: String("v")}}, - {"oneof message", &pb.Oneof{Union: &pb.Oneof_F_Message{&pb.GoTestField{Label: String("k"), Type: String("v")}}}}, - {"oneof group", &pb.Oneof{Union: &pb.Oneof_FGroup{&pb.Oneof_F_Group{X: Int32(52)}}}}, - {"oneof largest tag", &pb.Oneof{Union: &pb.Oneof_F_Largest_Tag{1}}}, - {"multiple oneofs", &pb.Oneof{Union: &pb.Oneof_F_Int32{1}, Tormato: &pb.Oneof_Value{2}}}, -} - -func TestSize(t *testing.T) { - for _, tc := range SizeTests { - size := Size(tc.pb) - b, err := Marshal(tc.pb) - if err != nil { - t.Errorf("%v: Marshal failed: %v", tc.desc, err) - continue - } - if size != len(b) { - t.Errorf("%v: Size(%v) = %d, want %d", tc.desc, tc.pb, size, len(b)) - t.Logf("%v: bytes: %#v", tc.desc, b) - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/text_parser_test.go b/vendor/github.com/golang/protobuf/proto/text_parser_test.go deleted file mode 100644 index 8f7cb4d27428..000000000000 --- a/vendor/github.com/golang/protobuf/proto/text_parser_test.go +++ /dev/null @@ -1,673 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "math" - "reflect" - "testing" - - . "github.com/golang/protobuf/proto" - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - . "github.com/golang/protobuf/proto/testdata" -) - -type UnmarshalTextTest struct { - in string - err string // if "", no error expected - out *MyMessage -} - -func buildExtStructTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_More, &Ext{ - Data: String("Hello, world!"), - }) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtDataTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_Text, String("Hello, world!")) - SetExtension(msg, E_Ext_Number, Int32(1729)) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtRepStringTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - if err := SetExtension(msg, E_Greeting, []string{"bula", "hola"}); err != nil { - panic(err) - } - return UnmarshalTextTest{in: text, out: msg} -} - -var unMarshalTextTests = []UnmarshalTextTest{ - // Basic - { - in: " count:42\n name:\"Dave\" ", - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - }, - }, - - // Empty quoted string - { - in: `count:42 name:""`, - out: &MyMessage{ - Count: Int32(42), - Name: String(""), - }, - }, - - // Quoted string concatenation with double quotes - { - in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string concatenation with single quotes - { - in: "count:42 name: 'My name is '\n'elsewhere'", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string concatenations with mixed quotes - { - in: "count:42 name: 'My name is '\n\"elsewhere\"", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - { - in: "count:42 name: \"My name is \"\n'elsewhere'", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string with escaped apostrophe - { - in: `count:42 name: "HOLIDAY - New Year\'s Day"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("HOLIDAY - New Year's Day"), - }, - }, - - // Quoted string with single quote - { - in: `count:42 name: 'Roger "The Ramster" Ramjet'`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`Roger "The Ramster" Ramjet`), - }, - }, - - // Quoted string with all the accepted special characters from the C++ test - { - in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"", - out: &MyMessage{ - Count: Int32(42), - Name: String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"), - }, - }, - - // Quoted string with quoted backslash - { - in: `count:42 name: "\\'xyz"`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`\'xyz`), - }, - }, - - // Quoted string with UTF-8 bytes. - { - in: "count:42 name: '\303\277\302\201\xAB'", - out: &MyMessage{ - Count: Int32(42), - Name: String("\303\277\302\201\xAB"), - }, - }, - - // Bad quoted string - { - in: `inner: < host: "\0" >` + "\n", - err: `line 1.15: invalid quoted string "\0": \0 requires 2 following digits`, - }, - - // Number too large for int64 - { - in: "count: 1 others { key: 123456789012345678901 }", - err: "line 1.23: invalid int64: 123456789012345678901", - }, - - // Number too large for int32 - { - in: "count: 1234567890123", - err: "line 1.7: invalid int32: 1234567890123", - }, - - // Number in hexadecimal - { - in: "count: 0x2beef", - out: &MyMessage{ - Count: Int32(0x2beef), - }, - }, - - // Number in octal - { - in: "count: 024601", - out: &MyMessage{ - Count: Int32(024601), - }, - }, - - // Floating point number with "f" suffix - { - in: "count: 4 others:< weight: 17.0f >", - out: &MyMessage{ - Count: Int32(4), - Others: []*OtherMessage{ - { - Weight: Float32(17), - }, - }, - }, - }, - - // Floating point positive infinity - { - in: "count: 4 bigfloat: inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(1)), - }, - }, - - // Floating point negative infinity - { - in: "count: 4 bigfloat: -inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(-1)), - }, - }, - - // Number too large for float32 - { - in: "others:< weight: 12345678901234567890123456789012345678901234567890 >", - err: "line 1.17: invalid float32: 12345678901234567890123456789012345678901234567890", - }, - - // Number posing as a quoted string - { - in: `inner: < host: 12 >` + "\n", - err: `line 1.15: invalid string: 12`, - }, - - // Quoted string posing as int32 - { - in: `count: "12"`, - err: `line 1.7: invalid int32: "12"`, - }, - - // Quoted string posing a float32 - { - in: `others:< weight: "17.4" >`, - err: `line 1.17: invalid float32: "17.4"`, - }, - - // Enum - { - in: `count:42 bikeshed: BLUE`, - out: &MyMessage{ - Count: Int32(42), - Bikeshed: MyMessage_BLUE.Enum(), - }, - }, - - // Repeated field - { - in: `count:42 pet: "horsey" pet:"bunny"`, - out: &MyMessage{ - Count: Int32(42), - Pet: []string{"horsey", "bunny"}, - }, - }, - - // Repeated field with list notation - { - in: `count:42 pet: ["horsey", "bunny"]`, - out: &MyMessage{ - Count: Int32(42), - Pet: []string{"horsey", "bunny"}, - }, - }, - - // Repeated message with/without colon and <>/{} - { - in: `count:42 others:{} others{} others:<> others:{}`, - out: &MyMessage{ - Count: Int32(42), - Others: []*OtherMessage{ - {}, - {}, - {}, - {}, - }, - }, - }, - - // Missing colon for inner message - { - in: `count:42 inner < host: "cauchy.syd" >`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("cauchy.syd"), - }, - }, - }, - - // Missing colon for string field - { - in: `name "Dave"`, - err: `line 1.5: expected ':', found "\"Dave\""`, - }, - - // Missing colon for int32 field - { - in: `count 42`, - err: `line 1.6: expected ':', found "42"`, - }, - - // Missing required field - { - in: `name: "Pawel"`, - err: `proto: required field "testdata.MyMessage.count" not set`, - out: &MyMessage{ - Name: String("Pawel"), - }, - }, - - // Missing required field in a required submessage - { - in: `count: 42 we_must_go_deeper < leo_finally_won_an_oscar <> >`, - err: `proto: required field "testdata.InnerMessage.host" not set`, - out: &MyMessage{ - Count: Int32(42), - WeMustGoDeeper: &RequiredInnerMessage{LeoFinallyWonAnOscar: &InnerMessage{}}, - }, - }, - - // Repeated non-repeated field - { - in: `name: "Rob" name: "Russ"`, - err: `line 1.12: non-repeated field "name" was repeated`, - }, - - // Group - { - in: `count: 17 SomeGroup { group_field: 12 }`, - out: &MyMessage{ - Count: Int32(17), - Somegroup: &MyMessage_SomeGroup{ - GroupField: Int32(12), - }, - }, - }, - - // Semicolon between fields - { - in: `count:3;name:"Calvin"`, - out: &MyMessage{ - Count: Int32(3), - Name: String("Calvin"), - }, - }, - // Comma between fields - { - in: `count:4,name:"Ezekiel"`, - out: &MyMessage{ - Count: Int32(4), - Name: String("Ezekiel"), - }, - }, - - // Boolean false - { - in: `count:42 inner { host: "example.com" connected: false }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean true - { - in: `count:42 inner { host: "example.com" connected: true }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean 0 - { - in: `count:42 inner { host: "example.com" connected: 0 }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean 1 - { - in: `count:42 inner { host: "example.com" connected: 1 }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean f - { - in: `count:42 inner { host: "example.com" connected: f }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean t - { - in: `count:42 inner { host: "example.com" connected: t }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean False - { - in: `count:42 inner { host: "example.com" connected: False }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean True - { - in: `count:42 inner { host: "example.com" connected: True }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - - // Extension - buildExtStructTest(`count: 42 [testdata.Ext.more]:`), - buildExtStructTest(`count: 42 [testdata.Ext.more] {data:"Hello, world!"}`), - buildExtDataTest(`count: 42 [testdata.Ext.text]:"Hello, world!" [testdata.Ext.number]:1729`), - buildExtRepStringTest(`count: 42 [testdata.greeting]:"bula" [testdata.greeting]:"hola"`), - - // Big all-in-one - { - in: "count:42 # Meaning\n" + - `name:"Dave" ` + - `quote:"\"I didn't want to go.\"" ` + - `pet:"bunny" ` + - `pet:"kitty" ` + - `pet:"horsey" ` + - `inner:<` + - ` host:"footrest.syd" ` + - ` port:7001 ` + - ` connected:true ` + - `> ` + - `others:<` + - ` key:3735928559 ` + - ` value:"\x01A\a\f" ` + - `> ` + - `others:<` + - " weight:58.9 # Atomic weight of Co\n" + - ` inner:<` + - ` host:"lesha.mtv" ` + - ` port:8002 ` + - ` >` + - `>`, - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - Quote: String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &InnerMessage{ - Host: String("footrest.syd"), - Port: Int32(7001), - Connected: Bool(true), - }, - Others: []*OtherMessage{ - { - Key: Int64(3735928559), - Value: []byte{0x1, 'A', '\a', '\f'}, - }, - { - Weight: Float32(58.9), - Inner: &InnerMessage{ - Host: String("lesha.mtv"), - Port: Int32(8002), - }, - }, - }, - }, - }, -} - -func TestUnmarshalText(t *testing.T) { - for i, test := range unMarshalTextTests { - pb := new(MyMessage) - err := UnmarshalText(test.in, pb) - if test.err == "" { - // We don't expect failure. - if err != nil { - t.Errorf("Test %d: Unexpected error: %v", i, err) - } else if !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } else { - // We do expect failure. - if err == nil { - t.Errorf("Test %d: Didn't get expected error: %v", i, test.err) - } else if err.Error() != test.err { - t.Errorf("Test %d: Incorrect error.\nHave: %v\nWant: %v", - i, err.Error(), test.err) - } else if _, ok := err.(*RequiredNotSetError); ok && test.out != nil && !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } - } -} - -func TestUnmarshalTextCustomMessage(t *testing.T) { - msg := &textMessage{} - if err := UnmarshalText("custom", msg); err != nil { - t.Errorf("Unexpected error from custom unmarshal: %v", err) - } - if UnmarshalText("not custom", msg) == nil { - t.Errorf("Didn't get expected error from custom unmarshal") - } -} - -// Regression test; this caused a panic. -func TestRepeatedEnum(t *testing.T) { - pb := new(RepeatedEnum) - if err := UnmarshalText("color: RED", pb); err != nil { - t.Fatal(err) - } - exp := &RepeatedEnum{ - Color: []RepeatedEnum_Color{RepeatedEnum_RED}, - } - if !Equal(pb, exp) { - t.Errorf("Incorrect populated \nHave: %v\nWant: %v", pb, exp) - } -} - -func TestProto3TextParsing(t *testing.T) { - m := new(proto3pb.Message) - const in = `name: "Wallace" true_scotsman: true` - want := &proto3pb.Message{ - Name: "Wallace", - TrueScotsman: true, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -func TestMapParsing(t *testing.T) { - m := new(MessageWithMap) - const in = `name_mapping: name_mapping:` + - `msg_mapping:,>` + // separating commas are okay - `msg_mapping>` + // no colon after "value" - `msg_mapping:>` + // omitted key - `msg_mapping:` + // omitted value - `byte_mapping:` + - `byte_mapping:<>` // omitted key and value - want := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Beatles", - 1234: "Feist", - }, - MsgMapping: map[int64]*FloatingPoint{ - -4: {F: Float64(2.0)}, - -2: {F: Float64(4.0)}, - 0: {F: Float64(5.0)}, - 1: nil, - }, - ByteMapping: map[bool][]byte{ - false: nil, - true: []byte("so be it"), - }, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -func TestOneofParsing(t *testing.T) { - const in = `name:"Shrek"` - m := new(Communique) - want := &Communique{Union: &Communique_Name{"Shrek"}} - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } - - const inOverwrite = `name:"Shrek" number:42` - m = new(Communique) - testErr := "line 1.13: field 'number' would overwrite already parsed oneof 'Union'" - if err := UnmarshalText(inOverwrite, m); err == nil { - t.Errorf("TestOneofParsing: Didn't get expected error: %v", testErr) - } else if err.Error() != testErr { - t.Errorf("TestOneofParsing: Incorrect error.\nHave: %v\nWant: %v", - err.Error(), testErr) - } - -} - -var benchInput string - -func init() { - benchInput = "count: 4\n" - for i := 0; i < 1000; i++ { - benchInput += "pet: \"fido\"\n" - } - - // Check it is valid input. - pb := new(MyMessage) - err := UnmarshalText(benchInput, pb) - if err != nil { - panic("Bad benchmark input: " + err.Error()) - } -} - -func BenchmarkUnmarshalText(b *testing.B) { - pb := new(MyMessage) - for i := 0; i < b.N; i++ { - UnmarshalText(benchInput, pb) - } - b.SetBytes(int64(len(benchInput))) -} diff --git a/vendor/github.com/golang/protobuf/proto/text_test.go b/vendor/github.com/golang/protobuf/proto/text_test.go deleted file mode 100644 index 3eabacac8f99..000000000000 --- a/vendor/github.com/golang/protobuf/proto/text_test.go +++ /dev/null @@ -1,474 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "bytes" - "errors" - "io/ioutil" - "math" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - pb "github.com/golang/protobuf/proto/testdata" -) - -// textMessage implements the methods that allow it to marshal and unmarshal -// itself as text. -type textMessage struct { -} - -func (*textMessage) MarshalText() ([]byte, error) { - return []byte("custom"), nil -} - -func (*textMessage) UnmarshalText(bytes []byte) error { - if string(bytes) != "custom" { - return errors.New("expected 'custom'") - } - return nil -} - -func (*textMessage) Reset() {} -func (*textMessage) String() string { return "" } -func (*textMessage) ProtoMessage() {} - -func newTestMessage() *pb.MyMessage { - msg := &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Quote: proto.String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("footrest.syd"), - Port: proto.Int32(7001), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(0xdeadbeef), - Value: []byte{1, 65, 7, 12}, - }, - { - Weight: proto.Float32(6.022), - Inner: &pb.InnerMessage{ - Host: proto.String("lesha.mtv"), - Port: proto.Int32(8002), - }, - }, - }, - Bikeshed: pb.MyMessage_BLUE.Enum(), - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(8), - }, - // One normally wouldn't do this. - // This is an undeclared tag 13, as a varint (wire type 0) with value 4. - XXX_unrecognized: []byte{13<<3 | 0, 4}, - } - ext := &pb.Ext{ - Data: proto.String("Big gobs for big rats"), - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil { - panic(err) - } - greetings := []string{"adg", "easy", "cow"} - if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil { - panic(err) - } - - // Add an unknown extension. We marshal a pb.Ext, and fake the ID. - b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")}) - if err != nil { - panic(err) - } - b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...) - proto.SetRawExtension(msg, 201, b) - - // Extensions can be plain fields, too, so let's test that. - b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19) - proto.SetRawExtension(msg, 202, b) - - return msg -} - -const text = `count: 42 -name: "Dave" -quote: "\"I didn't want to go.\"" -pet: "bunny" -pet: "kitty" -pet: "horsey" -inner: < - host: "footrest.syd" - port: 7001 - connected: true -> -others: < - key: 3735928559 - value: "\001A\007\014" -> -others: < - weight: 6.022 - inner: < - host: "lesha.mtv" - port: 8002 - > -> -bikeshed: BLUE -SomeGroup { - group_field: 8 -} -/* 2 unknown bytes */ -13: 4 -[testdata.Ext.more]: < - data: "Big gobs for big rats" -> -[testdata.greeting]: "adg" -[testdata.greeting]: "easy" -[testdata.greeting]: "cow" -/* 13 unknown bytes */ -201: "\t3G skiing" -/* 3 unknown bytes */ -202: 19 -` - -func TestMarshalText(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, newTestMessage()); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != text { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, text) - } -} - -func TestMarshalTextCustomMessage(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, &textMessage{}); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != "custom" { - t.Errorf("Got %q, expected %q", s, "custom") - } -} -func TestMarshalTextNil(t *testing.T) { - want := "" - tests := []proto.Message{nil, (*pb.MyMessage)(nil)} - for i, test := range tests { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, test); err != nil { - t.Fatal(err) - } - if got := buf.String(); got != want { - t.Errorf("%d: got %q want %q", i, got, want) - } - } -} - -func TestMarshalTextUnknownEnum(t *testing.T) { - // The Color enum only specifies values 0-2. - m := &pb.MyMessage{Bikeshed: pb.MyMessage_Color(3).Enum()} - got := m.String() - const want = `bikeshed:3 ` - if got != want { - t.Errorf("\n got %q\nwant %q", got, want) - } -} - -func TestTextOneof(t *testing.T) { - tests := []struct { - m proto.Message - want string - }{ - // zero message - {&pb.Communique{}, ``}, - // scalar field - {&pb.Communique{Union: &pb.Communique_Number{4}}, `number:4`}, - // message field - {&pb.Communique{Union: &pb.Communique_Msg{ - &pb.Strings{StringField: proto.String("why hello!")}, - }}, `msg:`}, - // bad oneof (should not panic) - {&pb.Communique{Union: &pb.Communique_Msg{nil}}, `msg:/* nil */`}, - } - for _, test := range tests { - got := strings.TrimSpace(test.m.String()) - if got != test.want { - t.Errorf("\n got %s\nwant %s", got, test.want) - } - } -} - -func BenchmarkMarshalTextBuffered(b *testing.B) { - buf := new(bytes.Buffer) - m := newTestMessage() - for i := 0; i < b.N; i++ { - buf.Reset() - proto.MarshalText(buf, m) - } -} - -func BenchmarkMarshalTextUnbuffered(b *testing.B) { - w := ioutil.Discard - m := newTestMessage() - for i := 0; i < b.N; i++ { - proto.MarshalText(w, m) - } -} - -func compact(src string) string { - // s/[ \n]+/ /g; s/ $//; - dst := make([]byte, len(src)) - space, comment := false, false - j := 0 - for i := 0; i < len(src); i++ { - if strings.HasPrefix(src[i:], "/*") { - comment = true - i++ - continue - } - if comment && strings.HasPrefix(src[i:], "*/") { - comment = false - i++ - continue - } - if comment { - continue - } - c := src[i] - if c == ' ' || c == '\n' { - space = true - continue - } - if j > 0 && (dst[j-1] == ':' || dst[j-1] == '<' || dst[j-1] == '{') { - space = false - } - if c == '{' { - space = false - } - if space { - dst[j] = ' ' - j++ - space = false - } - dst[j] = c - j++ - } - if space { - dst[j] = ' ' - j++ - } - return string(dst[0:j]) -} - -var compactText = compact(text) - -func TestCompactText(t *testing.T) { - s := proto.CompactTextString(newTestMessage()) - if s != compactText { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v\n===\n", s, compactText) - } -} - -func TestStringEscaping(t *testing.T) { - testCases := []struct { - in *pb.Strings - out string - }{ - { - // Test data from C++ test (TextFormatTest.StringEscape). - // Single divergence: we don't escape apostrophes. - &pb.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")}, - "string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"\n", - }, - { - // Test data from the same C++ test. - &pb.Strings{StringField: proto.String("\350\260\267\346\255\214")}, - "string_field: \"\\350\\260\\267\\346\\255\\214\"\n", - }, - { - // Some UTF-8. - &pb.Strings{StringField: proto.String("\x00\x01\xff\x81")}, - `string_field: "\000\001\377\201"` + "\n", - }, - } - - for i, tc := range testCases { - var buf bytes.Buffer - if err := proto.MarshalText(&buf, tc.in); err != nil { - t.Errorf("proto.MarsalText: %v", err) - continue - } - s := buf.String() - if s != tc.out { - t.Errorf("#%d: Got:\n%s\nExpected:\n%s\n", i, s, tc.out) - continue - } - - // Check round-trip. - pb := new(pb.Strings) - if err := proto.UnmarshalText(s, pb); err != nil { - t.Errorf("#%d: UnmarshalText: %v", i, err) - continue - } - if !proto.Equal(pb, tc.in) { - t.Errorf("#%d: Round-trip failed:\nstart: %v\n end: %v", i, tc.in, pb) - } - } -} - -// A limitedWriter accepts some output before it fails. -// This is a proxy for something like a nearly-full or imminently-failing disk, -// or a network connection that is about to die. -type limitedWriter struct { - b bytes.Buffer - limit int -} - -var outOfSpace = errors.New("proto: insufficient space") - -func (w *limitedWriter) Write(p []byte) (n int, err error) { - var avail = w.limit - w.b.Len() - if avail <= 0 { - return 0, outOfSpace - } - if len(p) <= avail { - return w.b.Write(p) - } - n, _ = w.b.Write(p[:avail]) - return n, outOfSpace -} - -func TestMarshalTextFailing(t *testing.T) { - // Try lots of different sizes to exercise more error code-paths. - for lim := 0; lim < len(text); lim++ { - buf := new(limitedWriter) - buf.limit = lim - err := proto.MarshalText(buf, newTestMessage()) - // We expect a certain error, but also some partial results in the buffer. - if err != outOfSpace { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", err, outOfSpace) - } - s := buf.b.String() - x := text[:buf.limit] - if s != x { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, x) - } - } -} - -func TestFloats(t *testing.T) { - tests := []struct { - f float64 - want string - }{ - {0, "0"}, - {4.7, "4.7"}, - {math.Inf(1), "inf"}, - {math.Inf(-1), "-inf"}, - {math.NaN(), "nan"}, - } - for _, test := range tests { - msg := &pb.FloatingPoint{F: &test.f} - got := strings.TrimSpace(msg.String()) - want := `f:` + test.want - if got != want { - t.Errorf("f=%f: got %q, want %q", test.f, got, want) - } - } -} - -func TestRepeatedNilText(t *testing.T) { - m := &pb.MessageList{ - Message: []*pb.MessageList_Message{ - nil, - &pb.MessageList_Message{ - Name: proto.String("Horse"), - }, - nil, - }, - } - want := `Message -Message { - name: "Horse" -} -Message -` - if s := proto.MarshalTextString(m); s != want { - t.Errorf(" got: %s\nwant: %s", s, want) - } -} - -func TestProto3Text(t *testing.T) { - tests := []struct { - m proto.Message - want string - }{ - // zero message - {&proto3pb.Message{}, ``}, - // zero message except for an empty byte slice - {&proto3pb.Message{Data: []byte{}}, ``}, - // trivial case - {&proto3pb.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`}, - // empty map - {&pb.MessageWithMap{}, ``}, - // non-empty map; map format is the same as a repeated struct, - // and they are sorted by key (numerically for numeric keys). - { - &pb.MessageWithMap{NameMapping: map[int32]string{ - -1: "Negatory", - 7: "Lucky", - 1234: "Feist", - 6345789: "Otis", - }}, - `name_mapping: ` + - `name_mapping: ` + - `name_mapping: ` + - `name_mapping:`, - }, - // map with nil value; not well-defined, but we shouldn't crash - { - &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{7: nil}}, - `msg_mapping:`, - }, - } - for _, test := range tests { - got := strings.TrimSpace(test.m.String()) - if got != test.want { - t.Errorf("\n got %s\nwant %s", got, test.want) - } - } -} diff --git a/vendor/github.com/google/btree/BUILD b/vendor/github.com/google/btree/BUILD index 68ec558c84d9..a8a0d0d22958 100644 --- a/vendor/github.com/google/btree/BUILD +++ b/vendor/github.com/google/btree/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -7,13 +7,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = ["btree_test.go"], - importpath = "github.com/google/btree", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/google/btree/btree_test.go b/vendor/github.com/google/btree/btree_test.go deleted file mode 100644 index 43dcea63bb31..000000000000 --- a/vendor/github.com/google/btree/btree_test.go +++ /dev/null @@ -1,293 +0,0 @@ -// Copyright 2014 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package btree - -import ( - "flag" - "fmt" - "math/rand" - "reflect" - "testing" - "time" -) - -func init() { - seed := time.Now().Unix() - fmt.Println(seed) - rand.Seed(seed) -} - -// perm returns a random permutation of n Int items in the range [0, n). -func perm(n int) (out []Item) { - for _, v := range rand.Perm(n) { - out = append(out, Int(v)) - } - return -} - -// rang returns an ordered list of Int items in the range [0, n). -func rang(n int) (out []Item) { - for i := 0; i < n; i++ { - out = append(out, Int(i)) - } - return -} - -// all extracts all items from a tree in order as a slice. -func all(t *BTree) (out []Item) { - t.Ascend(func(a Item) bool { - out = append(out, a) - return true - }) - return -} - -var btreeDegree = flag.Int("degree", 32, "B-Tree degree") - -func TestBTree(t *testing.T) { - tr := New(*btreeDegree) - const treeSize = 10000 - for i := 0; i < 10; i++ { - for _, item := range perm(treeSize) { - if x := tr.ReplaceOrInsert(item); x != nil { - t.Fatal("insert found item", item) - } - } - for _, item := range perm(treeSize) { - if x := tr.ReplaceOrInsert(item); x == nil { - t.Fatal("insert didn't find item", item) - } - } - got := all(tr) - want := rang(treeSize) - if !reflect.DeepEqual(got, want) { - t.Fatalf("mismatch:\n got: %v\nwant: %v", got, want) - } - for _, item := range perm(treeSize) { - if x := tr.Delete(item); x == nil { - t.Fatalf("didn't find %v", item) - } - } - if got = all(tr); len(got) > 0 { - t.Fatalf("some left!: %v", got) - } - } -} - -func ExampleBTree() { - tr := New(*btreeDegree) - for i := Int(0); i < 10; i++ { - tr.ReplaceOrInsert(i) - } - fmt.Println("len: ", tr.Len()) - fmt.Println("get3: ", tr.Get(Int(3))) - fmt.Println("get100: ", tr.Get(Int(100))) - fmt.Println("del4: ", tr.Delete(Int(4))) - fmt.Println("del100: ", tr.Delete(Int(100))) - fmt.Println("replace5: ", tr.ReplaceOrInsert(Int(5))) - fmt.Println("replace100:", tr.ReplaceOrInsert(Int(100))) - fmt.Println("delmin: ", tr.DeleteMin()) - fmt.Println("delmax: ", tr.DeleteMax()) - fmt.Println("len: ", tr.Len()) - // Output: - // len: 10 - // get3: 3 - // get100: - // del4: 4 - // del100: - // replace5: 5 - // replace100: - // delmin: 0 - // delmax: 100 - // len: 8 -} - -func TestDeleteMin(t *testing.T) { - tr := New(3) - for _, v := range perm(100) { - tr.ReplaceOrInsert(v) - } - var got []Item - for v := tr.DeleteMin(); v != nil; v = tr.DeleteMin() { - got = append(got, v) - } - if want := rang(100); !reflect.DeepEqual(got, want) { - t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want) - } -} - -func TestDeleteMax(t *testing.T) { - tr := New(3) - for _, v := range perm(100) { - tr.ReplaceOrInsert(v) - } - var got []Item - for v := tr.DeleteMax(); v != nil; v = tr.DeleteMax() { - got = append(got, v) - } - // Reverse our list. - for i := 0; i < len(got)/2; i++ { - got[i], got[len(got)-i-1] = got[len(got)-i-1], got[i] - } - if want := rang(100); !reflect.DeepEqual(got, want) { - t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want) - } -} - -func TestAscendRange(t *testing.T) { - tr := New(2) - for _, v := range perm(100) { - tr.ReplaceOrInsert(v) - } - var got []Item - tr.AscendRange(Int(40), Int(60), func(a Item) bool { - got = append(got, a) - return true - }) - if want := rang(100)[40:60]; !reflect.DeepEqual(got, want) { - t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want) - } - got = got[:0] - tr.AscendRange(Int(40), Int(60), func(a Item) bool { - if a.(Int) > 50 { - return false - } - got = append(got, a) - return true - }) - if want := rang(100)[40:51]; !reflect.DeepEqual(got, want) { - t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want) - } -} - -func TestAscendLessThan(t *testing.T) { - tr := New(*btreeDegree) - for _, v := range perm(100) { - tr.ReplaceOrInsert(v) - } - var got []Item - tr.AscendLessThan(Int(60), func(a Item) bool { - got = append(got, a) - return true - }) - if want := rang(100)[:60]; !reflect.DeepEqual(got, want) { - t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want) - } - got = got[:0] - tr.AscendLessThan(Int(60), func(a Item) bool { - if a.(Int) > 50 { - return false - } - got = append(got, a) - return true - }) - if want := rang(100)[:51]; !reflect.DeepEqual(got, want) { - t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want) - } -} - -func TestAscendGreaterOrEqual(t *testing.T) { - tr := New(*btreeDegree) - for _, v := range perm(100) { - tr.ReplaceOrInsert(v) - } - var got []Item - tr.AscendGreaterOrEqual(Int(40), func(a Item) bool { - got = append(got, a) - return true - }) - if want := rang(100)[40:]; !reflect.DeepEqual(got, want) { - t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want) - } - got = got[:0] - tr.AscendGreaterOrEqual(Int(40), func(a Item) bool { - if a.(Int) > 50 { - return false - } - got = append(got, a) - return true - }) - if want := rang(100)[40:51]; !reflect.DeepEqual(got, want) { - t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want) - } -} - -const benchmarkTreeSize = 10000 - -func BenchmarkInsert(b *testing.B) { - b.StopTimer() - insertP := perm(benchmarkTreeSize) - b.StartTimer() - i := 0 - for i < b.N { - tr := New(*btreeDegree) - for _, item := range insertP { - tr.ReplaceOrInsert(item) - i++ - if i >= b.N { - return - } - } - } -} - -func BenchmarkDelete(b *testing.B) { - b.StopTimer() - insertP := perm(benchmarkTreeSize) - removeP := perm(benchmarkTreeSize) - b.StartTimer() - i := 0 - for i < b.N { - b.StopTimer() - tr := New(*btreeDegree) - for _, v := range insertP { - tr.ReplaceOrInsert(v) - } - b.StartTimer() - for _, item := range removeP { - tr.Delete(item) - i++ - if i >= b.N { - return - } - } - if tr.Len() > 0 { - panic(tr.Len()) - } - } -} - -func BenchmarkGet(b *testing.B) { - b.StopTimer() - insertP := perm(benchmarkTreeSize) - removeP := perm(benchmarkTreeSize) - b.StartTimer() - i := 0 - for i < b.N { - b.StopTimer() - tr := New(*btreeDegree) - for _, v := range insertP { - tr.ReplaceOrInsert(v) - } - b.StartTimer() - for _, item := range removeP { - tr.Get(item) - i++ - if i >= b.N { - return - } - } - } -} diff --git a/vendor/github.com/google/go-github/github/BUILD b/vendor/github.com/google/go-github/github/BUILD index 846cce923f57..41608f4e9462 100644 --- a/vendor/github.com/google/go-github/github/BUILD +++ b/vendor/github.com/google/go-github/github/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -85,92 +85,6 @@ go_library( deps = ["//vendor/github.com/google/go-querystring/query:go_default_library"], ) -go_test( - name = "go_default_test", - srcs = [ - "activity_events_test.go", - "activity_notifications_test.go", - "activity_star_test.go", - "activity_test.go", - "activity_watching_test.go", - "admin_test.go", - "apps_installation_test.go", - "apps_test.go", - "authorizations_test.go", - "gists_comments_test.go", - "gists_test.go", - "git_blobs_test.go", - "git_commits_test.go", - "git_refs_test.go", - "git_tags_test.go", - "git_trees_test.go", - "github_test.go", - "gitignore_test.go", - "issues_assignees_test.go", - "issues_comments_test.go", - "issues_events_test.go", - "issues_labels_test.go", - "issues_milestones_test.go", - "issues_test.go", - "issues_timeline_test.go", - "licenses_test.go", - "messages_test.go", - "migrations_source_import_test.go", - "migrations_test.go", - "misc_test.go", - "orgs_hooks_test.go", - "orgs_members_test.go", - "orgs_outside_collaborators_test.go", - "orgs_projects_test.go", - "orgs_teams_test.go", - "orgs_test.go", - "orgs_users_blocking_test.go", - "projects_test.go", - "pulls_comments_test.go", - "pulls_reviewers_test.go", - "pulls_reviews_test.go", - "pulls_test.go", - "reactions_test.go", - "repos_collaborators_test.go", - "repos_comments_test.go", - "repos_commits_test.go", - "repos_community_health_test.go", - "repos_contents_test.go", - "repos_deployments_test.go", - "repos_forks_test.go", - "repos_hooks_test.go", - "repos_invitations_test.go", - "repos_keys_test.go", - "repos_merging_test.go", - "repos_pages_test.go", - "repos_projects_test.go", - "repos_releases_test.go", - "repos_stats_test.go", - "repos_statuses_test.go", - "repos_test.go", - "repos_traffic_test.go", - "search_test.go", - "strings_test.go", - "timestamp_test.go", - "users_administration_test.go", - "users_blocking_test.go", - "users_emails_test.go", - "users_followers_test.go", - "users_gpg_keys_test.go", - "users_keys_test.go", - "users_test.go", - ], - importpath = "github.com/google/go-github/github", - library = ":go_default_library", -) - -go_test( - name = "go_default_xtest", - srcs = ["examples_test.go"], - importpath = "github.com/google/go-github/github_test", - deps = [":go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/google/go-github/github/activity_events_test.go b/vendor/github.com/google/go-github/github/activity_events_test.go deleted file mode 100644 index 2b59d11be8e0..000000000000 --- a/vendor/github.com/google/go-github/github/activity_events_test.go +++ /dev/null @@ -1,331 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestActivityService_ListEvents(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/events", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`) - }) - - opt := &ListOptions{Page: 2} - events, _, err := client.Activity.ListEvents(context.Background(), opt) - if err != nil { - t.Errorf("Activities.ListEvents returned error: %v", err) - } - - want := []*Event{{ID: String("1")}, {ID: String("2")}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Activities.ListEvents returned %+v, want %+v", events, want) - } -} - -func TestActivityService_ListRepositoryEvents(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/events", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`) - }) - - opt := &ListOptions{Page: 2} - events, _, err := client.Activity.ListRepositoryEvents(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Activities.ListRepositoryEvents returned error: %v", err) - } - - want := []*Event{{ID: String("1")}, {ID: String("2")}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Activities.ListRepositoryEvents returned %+v, want %+v", events, want) - } -} - -func TestActivityService_ListRepositoryEvents_invalidOwner(t *testing.T) { - _, _, err := client.Activity.ListRepositoryEvents(context.Background(), "%", "%", nil) - testURLParseError(t, err) -} - -func TestActivityService_ListIssueEventsForRepository(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/events", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id":1},{"id":2}]`) - }) - - opt := &ListOptions{Page: 2} - events, _, err := client.Activity.ListIssueEventsForRepository(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Activities.ListIssueEventsForRepository returned error: %v", err) - } - - want := []*IssueEvent{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Activities.ListIssueEventsForRepository returned %+v, want %+v", events, want) - } -} - -func TestActivityService_ListIssueEventsForRepository_invalidOwner(t *testing.T) { - _, _, err := client.Activity.ListIssueEventsForRepository(context.Background(), "%", "%", nil) - testURLParseError(t, err) -} - -func TestActivityService_ListEventsForRepoNetwork(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/networks/o/r/events", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`) - }) - - opt := &ListOptions{Page: 2} - events, _, err := client.Activity.ListEventsForRepoNetwork(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Activities.ListEventsForRepoNetwork returned error: %v", err) - } - - want := []*Event{{ID: String("1")}, {ID: String("2")}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Activities.ListEventsForRepoNetwork returned %+v, want %+v", events, want) - } -} - -func TestActivityService_ListEventsForRepoNetwork_invalidOwner(t *testing.T) { - _, _, err := client.Activity.ListEventsForRepoNetwork(context.Background(), "%", "%", nil) - testURLParseError(t, err) -} - -func TestActivityService_ListEventsForOrganization(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/events", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`) - }) - - opt := &ListOptions{Page: 2} - events, _, err := client.Activity.ListEventsForOrganization(context.Background(), "o", opt) - if err != nil { - t.Errorf("Activities.ListEventsForOrganization returned error: %v", err) - } - - want := []*Event{{ID: String("1")}, {ID: String("2")}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Activities.ListEventsForOrganization returned %+v, want %+v", events, want) - } -} - -func TestActivityService_ListEventsForOrganization_invalidOrg(t *testing.T) { - _, _, err := client.Activity.ListEventsForOrganization(context.Background(), "%", nil) - testURLParseError(t, err) -} - -func TestActivityService_ListEventsPerformedByUser_all(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/events", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`) - }) - - opt := &ListOptions{Page: 2} - events, _, err := client.Activity.ListEventsPerformedByUser(context.Background(), "u", false, opt) - if err != nil { - t.Errorf("Events.ListPerformedByUser returned error: %v", err) - } - - want := []*Event{{ID: String("1")}, {ID: String("2")}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Events.ListPerformedByUser returned %+v, want %+v", events, want) - } -} - -func TestActivityService_ListEventsPerformedByUser_publicOnly(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/events/public", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`) - }) - - events, _, err := client.Activity.ListEventsPerformedByUser(context.Background(), "u", true, nil) - if err != nil { - t.Errorf("Events.ListPerformedByUser returned error: %v", err) - } - - want := []*Event{{ID: String("1")}, {ID: String("2")}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Events.ListPerformedByUser returned %+v, want %+v", events, want) - } -} - -func TestActivityService_ListEventsPerformedByUser_invalidUser(t *testing.T) { - _, _, err := client.Activity.ListEventsPerformedByUser(context.Background(), "%", false, nil) - testURLParseError(t, err) -} - -func TestActivityService_ListEventsReceivedByUser_all(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/received_events", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`) - }) - - opt := &ListOptions{Page: 2} - events, _, err := client.Activity.ListEventsReceivedByUser(context.Background(), "u", false, opt) - if err != nil { - t.Errorf("Events.ListReceivedByUser returned error: %v", err) - } - - want := []*Event{{ID: String("1")}, {ID: String("2")}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Events.ListReceivedUser returned %+v, want %+v", events, want) - } -} - -func TestActivityService_ListEventsReceivedByUser_publicOnly(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/received_events/public", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`) - }) - - events, _, err := client.Activity.ListEventsReceivedByUser(context.Background(), "u", true, nil) - if err != nil { - t.Errorf("Events.ListReceivedByUser returned error: %v", err) - } - - want := []*Event{{ID: String("1")}, {ID: String("2")}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Events.ListReceivedByUser returned %+v, want %+v", events, want) - } -} - -func TestActivityService_ListEventsReceivedByUser_invalidUser(t *testing.T) { - _, _, err := client.Activity.ListEventsReceivedByUser(context.Background(), "%", false, nil) - testURLParseError(t, err) -} - -func TestActivityService_ListUserEventsForOrganization(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/events/orgs/o", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id":"1"},{"id":"2"}]`) - }) - - opt := &ListOptions{Page: 2} - events, _, err := client.Activity.ListUserEventsForOrganization(context.Background(), "o", "u", opt) - if err != nil { - t.Errorf("Activities.ListUserEventsForOrganization returned error: %v", err) - } - - want := []*Event{{ID: String("1")}, {ID: String("2")}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Activities.ListUserEventsForOrganization returned %+v, want %+v", events, want) - } -} - -func TestActivityService_EventParsePayload_typed(t *testing.T) { - raw := []byte(`{"type": "PushEvent","payload":{"push_id": 1}}`) - var event *Event - if err := json.Unmarshal(raw, &event); err != nil { - t.Fatalf("Unmarshal Event returned error: %v", err) - } - - want := &PushEvent{PushID: Int(1)} - got, err := event.ParsePayload() - if err != nil { - t.Fatalf("ParsePayload returned unexpected error: %v", err) - } - if !reflect.DeepEqual(got, want) { - t.Errorf("Event.ParsePayload returned %+v, want %+v", got, want) - } -} - -// TestEvent_Payload_untyped checks that unrecognized events are parsed to an -// interface{} value (instead of being discarded or throwing an error), for -// forward compatibility with new event types. -func TestActivityService_EventParsePayload_untyped(t *testing.T) { - raw := []byte(`{"type": "UnrecognizedEvent","payload":{"field": "val"}}`) - var event *Event - if err := json.Unmarshal(raw, &event); err != nil { - t.Fatalf("Unmarshal Event returned error: %v", err) - } - - want := map[string]interface{}{"field": "val"} - got, err := event.ParsePayload() - if err != nil { - t.Fatalf("ParsePayload returned unexpected error: %v", err) - } - if !reflect.DeepEqual(got, want) { - t.Errorf("Event.ParsePayload returned %+v, want %+v", got, want) - } -} - -func TestActivityService_EventParsePayload_installation(t *testing.T) { - raw := []byte(`{"type": "PullRequestEvent","payload":{"installation":{"id":1}}}`) - var event *Event - if err := json.Unmarshal(raw, &event); err != nil { - t.Fatalf("Unmarshal Event returned error: %v", err) - } - - want := &PullRequestEvent{Installation: &Installation{ID: Int(1)}} - got, err := event.ParsePayload() - if err != nil { - t.Fatalf("ParsePayload returned unexpected error: %v", err) - } - if !reflect.DeepEqual(got, want) { - t.Errorf("Event.ParsePayload returned %+v, want %+v", got, want) - } -} diff --git a/vendor/github.com/google/go-github/github/activity_notifications_test.go b/vendor/github.com/google/go-github/github/activity_notifications_test.go deleted file mode 100644 index cab8f94da8df..000000000000 --- a/vendor/github.com/google/go-github/github/activity_notifications_test.go +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestActivityService_ListNotification(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/notifications", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "all": "true", - "participating": "true", - "since": "2006-01-02T15:04:05Z", - "before": "2007-03-04T15:04:05Z", - }) - - fmt.Fprint(w, `[{"id":"1", "subject":{"title":"t"}}]`) - }) - - opt := &NotificationListOptions{ - All: true, - Participating: true, - Since: time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC), - Before: time.Date(2007, 03, 04, 15, 04, 05, 0, time.UTC), - } - notifications, _, err := client.Activity.ListNotifications(context.Background(), opt) - if err != nil { - t.Errorf("Activity.ListNotifications returned error: %v", err) - } - - want := []*Notification{{ID: String("1"), Subject: &NotificationSubject{Title: String("t")}}} - if !reflect.DeepEqual(notifications, want) { - t.Errorf("Activity.ListNotifications returned %+v, want %+v", notifications, want) - } -} - -func TestActivityService_ListRepositoryNotification(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/notifications", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":"1"}]`) - }) - - notifications, _, err := client.Activity.ListRepositoryNotifications(context.Background(), "o", "r", nil) - if err != nil { - t.Errorf("Activity.ListRepositoryNotifications returned error: %v", err) - } - - want := []*Notification{{ID: String("1")}} - if !reflect.DeepEqual(notifications, want) { - t.Errorf("Activity.ListRepositoryNotifications returned %+v, want %+v", notifications, want) - } -} - -func TestActivityService_MarkNotificationsRead(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/notifications", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"last_read_at":"2006-01-02T15:04:05Z"}`+"\n") - - w.WriteHeader(http.StatusResetContent) - }) - - _, err := client.Activity.MarkNotificationsRead(context.Background(), time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC)) - if err != nil { - t.Errorf("Activity.MarkNotificationsRead returned error: %v", err) - } -} - -func TestActivityService_MarkRepositoryNotificationsRead(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/notifications", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - testHeader(t, r, "Content-Type", "application/json") - testBody(t, r, `{"last_read_at":"2006-01-02T15:04:05Z"}`+"\n") - - w.WriteHeader(http.StatusResetContent) - }) - - _, err := client.Activity.MarkRepositoryNotificationsRead(context.Background(), "o", "r", time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC)) - if err != nil { - t.Errorf("Activity.MarkRepositoryNotificationsRead returned error: %v", err) - } -} - -func TestActivityService_GetThread(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/notifications/threads/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":"1"}`) - }) - - notification, _, err := client.Activity.GetThread(context.Background(), "1") - if err != nil { - t.Errorf("Activity.GetThread returned error: %v", err) - } - - want := &Notification{ID: String("1")} - if !reflect.DeepEqual(notification, want) { - t.Errorf("Activity.GetThread returned %+v, want %+v", notification, want) - } -} - -func TestActivityService_MarkThreadRead(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/notifications/threads/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PATCH") - w.WriteHeader(http.StatusResetContent) - }) - - _, err := client.Activity.MarkThreadRead(context.Background(), "1") - if err != nil { - t.Errorf("Activity.MarkThreadRead returned error: %v", err) - } -} - -func TestActivityService_GetThreadSubscription(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/notifications/threads/1/subscription", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"subscribed":true}`) - }) - - sub, _, err := client.Activity.GetThreadSubscription(context.Background(), "1") - if err != nil { - t.Errorf("Activity.GetThreadSubscription returned error: %v", err) - } - - want := &Subscription{Subscribed: Bool(true)} - if !reflect.DeepEqual(sub, want) { - t.Errorf("Activity.GetThreadSubscription returned %+v, want %+v", sub, want) - } -} - -func TestActivityService_SetThreadSubscription(t *testing.T) { - setup() - defer teardown() - - input := &Subscription{Subscribed: Bool(true)} - - mux.HandleFunc("/notifications/threads/1/subscription", func(w http.ResponseWriter, r *http.Request) { - v := new(Subscription) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PUT") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"ignored":true}`) - }) - - sub, _, err := client.Activity.SetThreadSubscription(context.Background(), "1", input) - if err != nil { - t.Errorf("Activity.SetThreadSubscription returned error: %v", err) - } - - want := &Subscription{Ignored: Bool(true)} - if !reflect.DeepEqual(sub, want) { - t.Errorf("Activity.SetThreadSubscription returned %+v, want %+v", sub, want) - } -} - -func TestActivityService_DeleteThreadSubscription(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/notifications/threads/1/subscription", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Activity.DeleteThreadSubscription(context.Background(), "1") - if err != nil { - t.Errorf("Activity.DeleteThreadSubscription returned error: %v", err) - } -} diff --git a/vendor/github.com/google/go-github/github/activity_star_test.go b/vendor/github.com/google/go-github/github/activity_star_test.go deleted file mode 100644 index 542bfc66b4b7..000000000000 --- a/vendor/github.com/google/go-github/github/activity_star_test.go +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestActivityService_ListStargazers(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/stargazers", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeStarringPreview) - testFormValues(t, r, values{ - "page": "2", - }) - - fmt.Fprint(w, `[{"starred_at":"2002-02-10T15:30:00Z","user":{"id":1}}]`) - }) - - stargazers, _, err := client.Activity.ListStargazers(context.Background(), "o", "r", &ListOptions{Page: 2}) - if err != nil { - t.Errorf("Activity.ListStargazers returned error: %v", err) - } - - want := []*Stargazer{{StarredAt: &Timestamp{time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC)}, User: &User{ID: Int(1)}}} - if !reflect.DeepEqual(stargazers, want) { - t.Errorf("Activity.ListStargazers returned %+v, want %+v", stargazers, want) - } -} - -func TestActivityService_ListStarred_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/starred", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeStarringPreview) - fmt.Fprint(w, `[{"starred_at":"2002-02-10T15:30:00Z","repo":{"id":1}}]`) - }) - - repos, _, err := client.Activity.ListStarred(context.Background(), "", nil) - if err != nil { - t.Errorf("Activity.ListStarred returned error: %v", err) - } - - want := []*StarredRepository{{StarredAt: &Timestamp{time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC)}, Repository: &Repository{ID: Int(1)}}} - if !reflect.DeepEqual(repos, want) { - t.Errorf("Activity.ListStarred returned %+v, want %+v", repos, want) - } -} - -func TestActivityService_ListStarred_specifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/starred", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeStarringPreview) - testFormValues(t, r, values{ - "sort": "created", - "direction": "asc", - "page": "2", - }) - fmt.Fprint(w, `[{"starred_at":"2002-02-10T15:30:00Z","repo":{"id":2}}]`) - }) - - opt := &ActivityListStarredOptions{"created", "asc", ListOptions{Page: 2}} - repos, _, err := client.Activity.ListStarred(context.Background(), "u", opt) - if err != nil { - t.Errorf("Activity.ListStarred returned error: %v", err) - } - - want := []*StarredRepository{{StarredAt: &Timestamp{time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC)}, Repository: &Repository{ID: Int(2)}}} - if !reflect.DeepEqual(repos, want) { - t.Errorf("Activity.ListStarred returned %+v, want %+v", repos, want) - } -} - -func TestActivityService_ListStarred_invalidUser(t *testing.T) { - _, _, err := client.Activity.ListStarred(context.Background(), "%", nil) - testURLParseError(t, err) -} - -func TestActivityService_IsStarred_hasStar(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/starred/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNoContent) - }) - - star, _, err := client.Activity.IsStarred(context.Background(), "o", "r") - if err != nil { - t.Errorf("Activity.IsStarred returned error: %v", err) - } - if want := true; star != want { - t.Errorf("Activity.IsStarred returned %+v, want %+v", star, want) - } -} - -func TestActivityService_IsStarred_noStar(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/starred/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - star, _, err := client.Activity.IsStarred(context.Background(), "o", "r") - if err != nil { - t.Errorf("Activity.IsStarred returned error: %v", err) - } - if want := false; star != want { - t.Errorf("Activity.IsStarred returned %+v, want %+v", star, want) - } -} - -func TestActivityService_IsStarred_invalidID(t *testing.T) { - _, _, err := client.Activity.IsStarred(context.Background(), "%", "%") - testURLParseError(t, err) -} - -func TestActivityService_Star(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/starred/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - }) - - _, err := client.Activity.Star(context.Background(), "o", "r") - if err != nil { - t.Errorf("Activity.Star returned error: %v", err) - } -} - -func TestActivityService_Star_invalidID(t *testing.T) { - _, err := client.Activity.Star(context.Background(), "%", "%") - testURLParseError(t, err) -} - -func TestActivityService_Unstar(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/starred/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Activity.Unstar(context.Background(), "o", "r") - if err != nil { - t.Errorf("Activity.Unstar returned error: %v", err) - } -} - -func TestActivityService_Unstar_invalidID(t *testing.T) { - _, err := client.Activity.Unstar(context.Background(), "%", "%") - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/activity_test.go b/vendor/github.com/google/go-github/github/activity_test.go deleted file mode 100644 index 98567a254b6b..000000000000 --- a/vendor/github.com/google/go-github/github/activity_test.go +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "net/http" - "reflect" - "testing" -) - -func TestActivityService_List(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/feeds", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - - w.WriteHeader(http.StatusOK) - w.Write(feedsJSON) - }) - - got, _, err := client.Activity.ListFeeds(context.Background()) - if err != nil { - t.Errorf("Activity.ListFeeds returned error: %v", err) - } - if want := wantFeeds; !reflect.DeepEqual(got, want) { - t.Errorf("Activity.ListFeeds = %+v, want %+v", got, want) - } -} - -var feedsJSON = []byte(`{ - "timeline_url": "https://github.com/timeline", - "user_url": "https://github.com/{user}", - "current_user_public_url": "https://github.com/defunkt", - "current_user_url": "https://github.com/defunkt.private?token=abc123", - "current_user_actor_url": "https://github.com/defunkt.private.actor?token=abc123", - "current_user_organization_url": "", - "current_user_organization_urls": [ - "https://github.com/organizations/github/defunkt.private.atom?token=abc123" - ], - "_links": { - "timeline": { - "href": "https://github.com/timeline", - "type": "application/atom+xml" - }, - "user": { - "href": "https://github.com/{user}", - "type": "application/atom+xml" - }, - "current_user_public": { - "href": "https://github.com/defunkt", - "type": "application/atom+xml" - }, - "current_user": { - "href": "https://github.com/defunkt.private?token=abc123", - "type": "application/atom+xml" - }, - "current_user_actor": { - "href": "https://github.com/defunkt.private.actor?token=abc123", - "type": "application/atom+xml" - }, - "current_user_organization": { - "href": "", - "type": "" - }, - "current_user_organizations": [ - { - "href": "https://github.com/organizations/github/defunkt.private.atom?token=abc123", - "type": "application/atom+xml" - } - ] - } -}`) - -var wantFeeds = &Feeds{ - TimelineURL: String("https://github.com/timeline"), - UserURL: String("https://github.com/{user}"), - CurrentUserPublicURL: String("https://github.com/defunkt"), - CurrentUserURL: String("https://github.com/defunkt.private?token=abc123"), - CurrentUserActorURL: String("https://github.com/defunkt.private.actor?token=abc123"), - CurrentUserOrganizationURL: String(""), - CurrentUserOrganizationURLs: []string{ - "https://github.com/organizations/github/defunkt.private.atom?token=abc123", - }, - Links: &struct { - Timeline *FeedLink `json:"timeline,omitempty"` - User *FeedLink `json:"user,omitempty"` - CurrentUserPublic *FeedLink `json:"current_user_public,omitempty"` - CurrentUser *FeedLink `json:"current_user,omitempty"` - CurrentUserActor *FeedLink `json:"current_user_actor,omitempty"` - CurrentUserOrganization *FeedLink `json:"current_user_organization,omitempty"` - CurrentUserOrganizations []FeedLink `json:"current_user_organizations,omitempty"` - }{ - Timeline: &FeedLink{ - HRef: String("https://github.com/timeline"), - Type: String("application/atom+xml"), - }, - User: &FeedLink{ - HRef: String("https://github.com/{user}"), - Type: String("application/atom+xml"), - }, - CurrentUserPublic: &FeedLink{ - HRef: String("https://github.com/defunkt"), - Type: String("application/atom+xml"), - }, - CurrentUser: &FeedLink{ - HRef: String("https://github.com/defunkt.private?token=abc123"), - Type: String("application/atom+xml"), - }, - CurrentUserActor: &FeedLink{ - HRef: String("https://github.com/defunkt.private.actor?token=abc123"), - Type: String("application/atom+xml"), - }, - CurrentUserOrganization: &FeedLink{ - HRef: String(""), - Type: String(""), - }, - CurrentUserOrganizations: []FeedLink{ - { - HRef: String("https://github.com/organizations/github/defunkt.private.atom?token=abc123"), - Type: String("application/atom+xml"), - }, - }, - }, -} diff --git a/vendor/github.com/google/go-github/github/activity_watching_test.go b/vendor/github.com/google/go-github/github/activity_watching_test.go deleted file mode 100644 index d765f67e9e08..000000000000 --- a/vendor/github.com/google/go-github/github/activity_watching_test.go +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestActivityService_ListWatchers(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/subscribers", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - - fmt.Fprint(w, `[{"id":1}]`) - }) - - watchers, _, err := client.Activity.ListWatchers(context.Background(), "o", "r", &ListOptions{Page: 2}) - if err != nil { - t.Errorf("Activity.ListWatchers returned error: %v", err) - } - - want := []*User{{ID: Int(1)}} - if !reflect.DeepEqual(watchers, want) { - t.Errorf("Activity.ListWatchers returned %+v, want %+v", watchers, want) - } -} - -func TestActivityService_ListWatched_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/subscriptions", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - watched, _, err := client.Activity.ListWatched(context.Background(), "", &ListOptions{Page: 2}) - if err != nil { - t.Errorf("Activity.ListWatched returned error: %v", err) - } - - want := []*Repository{{ID: Int(1)}} - if !reflect.DeepEqual(watched, want) { - t.Errorf("Activity.ListWatched returned %+v, want %+v", watched, want) - } -} - -func TestActivityService_ListWatched_specifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/subscriptions", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - watched, _, err := client.Activity.ListWatched(context.Background(), "u", &ListOptions{Page: 2}) - if err != nil { - t.Errorf("Activity.ListWatched returned error: %v", err) - } - - want := []*Repository{{ID: Int(1)}} - if !reflect.DeepEqual(watched, want) { - t.Errorf("Activity.ListWatched returned %+v, want %+v", watched, want) - } -} - -func TestActivityService_GetRepositorySubscription_true(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/subscription", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"subscribed":true}`) - }) - - sub, _, err := client.Activity.GetRepositorySubscription(context.Background(), "o", "r") - if err != nil { - t.Errorf("Activity.GetRepositorySubscription returned error: %v", err) - } - - want := &Subscription{Subscribed: Bool(true)} - if !reflect.DeepEqual(sub, want) { - t.Errorf("Activity.GetRepositorySubscription returned %+v, want %+v", sub, want) - } -} - -func TestActivityService_GetRepositorySubscription_false(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/subscription", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - sub, _, err := client.Activity.GetRepositorySubscription(context.Background(), "o", "r") - if err != nil { - t.Errorf("Activity.GetRepositorySubscription returned error: %v", err) - } - - var want *Subscription - if !reflect.DeepEqual(sub, want) { - t.Errorf("Activity.GetRepositorySubscription returned %+v, want %+v", sub, want) - } -} - -func TestActivityService_GetRepositorySubscription_error(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/subscription", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusBadRequest) - }) - - _, _, err := client.Activity.GetRepositorySubscription(context.Background(), "o", "r") - if err == nil { - t.Errorf("Expected HTTP 400 response") - } -} - -func TestActivityService_SetRepositorySubscription(t *testing.T) { - setup() - defer teardown() - - input := &Subscription{Subscribed: Bool(true)} - - mux.HandleFunc("/repos/o/r/subscription", func(w http.ResponseWriter, r *http.Request) { - v := new(Subscription) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PUT") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"ignored":true}`) - }) - - sub, _, err := client.Activity.SetRepositorySubscription(context.Background(), "o", "r", input) - if err != nil { - t.Errorf("Activity.SetRepositorySubscription returned error: %v", err) - } - - want := &Subscription{Ignored: Bool(true)} - if !reflect.DeepEqual(sub, want) { - t.Errorf("Activity.SetRepositorySubscription returned %+v, want %+v", sub, want) - } -} - -func TestActivityService_DeleteRepositorySubscription(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/subscription", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Activity.DeleteRepositorySubscription(context.Background(), "o", "r") - if err != nil { - t.Errorf("Activity.DeleteRepositorySubscription returned error: %v", err) - } -} diff --git a/vendor/github.com/google/go-github/github/admin_test.go b/vendor/github.com/google/go-github/github/admin_test.go deleted file mode 100644 index 32a870eb4070..000000000000 --- a/vendor/github.com/google/go-github/github/admin_test.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestAdminService_UpdateUserLDAPMapping(t *testing.T) { - setup() - defer teardown() - - input := &UserLDAPMapping{ - LDAPDN: String("uid=asdf,ou=users,dc=github,dc=com"), - } - - mux.HandleFunc("/admin/ldap/users/u/mapping", func(w http.ResponseWriter, r *http.Request) { - v := new(UserLDAPMapping) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - fmt.Fprint(w, `{"id":1,"ldap_dn":"uid=asdf,ou=users,dc=github,dc=com"}`) - }) - - mapping, _, err := client.Admin.UpdateUserLDAPMapping(context.Background(), "u", input) - if err != nil { - t.Errorf("Admin.UpdateUserLDAPMapping returned error: %v", err) - } - - want := &UserLDAPMapping{ - ID: Int(1), - LDAPDN: String("uid=asdf,ou=users,dc=github,dc=com"), - } - if !reflect.DeepEqual(mapping, want) { - t.Errorf("Admin.UpdateUserLDAPMapping returned %+v, want %+v", mapping, want) - } -} - -func TestAdminService_UpdateTeamLDAPMapping(t *testing.T) { - setup() - defer teardown() - - input := &TeamLDAPMapping{ - LDAPDN: String("cn=Enterprise Ops,ou=teams,dc=github,dc=com"), - } - - mux.HandleFunc("/admin/ldap/teams/1/mapping", func(w http.ResponseWriter, r *http.Request) { - v := new(TeamLDAPMapping) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - fmt.Fprint(w, `{"id":1,"ldap_dn":"cn=Enterprise Ops,ou=teams,dc=github,dc=com"}`) - }) - - mapping, _, err := client.Admin.UpdateTeamLDAPMapping(context.Background(), 1, input) - if err != nil { - t.Errorf("Admin.UpdateTeamLDAPMapping returned error: %v", err) - } - - want := &TeamLDAPMapping{ - ID: Int(1), - LDAPDN: String("cn=Enterprise Ops,ou=teams,dc=github,dc=com"), - } - if !reflect.DeepEqual(mapping, want) { - t.Errorf("Admin.UpdateTeamLDAPMapping returned %+v, want %+v", mapping, want) - } -} diff --git a/vendor/github.com/google/go-github/github/apps_installation_test.go b/vendor/github.com/google/go-github/github/apps_installation_test.go deleted file mode 100644 index 462d15a3f29d..000000000000 --- a/vendor/github.com/google/go-github/github/apps_installation_test.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestAppsService_ListRepos(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/installation/repositories", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeIntegrationPreview) - testFormValues(t, r, values{ - "page": "1", - "per_page": "2", - }) - fmt.Fprint(w, `{"repositories": [{"id":1}]}`) - }) - - opt := &ListOptions{Page: 1, PerPage: 2} - repositories, _, err := client.Apps.ListRepos(context.Background(), opt) - if err != nil { - t.Errorf("Apps.ListRepos returned error: %v", err) - } - - want := []*Repository{{ID: Int(1)}} - if !reflect.DeepEqual(repositories, want) { - t.Errorf("Apps.ListRepos returned %+v, want %+v", repositories, want) - } -} diff --git a/vendor/github.com/google/go-github/github/apps_test.go b/vendor/github.com/google/go-github/github/apps_test.go deleted file mode 100644 index f847b84271c1..000000000000 --- a/vendor/github.com/google/go-github/github/apps_test.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestAppsService_ListInstallations(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/app/installations", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeIntegrationPreview) - testFormValues(t, r, values{ - "page": "1", - "per_page": "2", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 1, PerPage: 2} - installations, _, err := client.Apps.ListInstallations(context.Background(), opt) - if err != nil { - t.Errorf("Apps.ListInstallations returned error: %v", err) - } - - want := []*Installation{{ID: Int(1)}} - if !reflect.DeepEqual(installations, want) { - t.Errorf("Apps.ListInstallations returned %+v, want %+v", installations, want) - } -} diff --git a/vendor/github.com/google/go-github/github/authorizations_test.go b/vendor/github.com/google/go-github/github/authorizations_test.go deleted file mode 100644 index 61bf21252a44..000000000000 --- a/vendor/github.com/google/go-github/github/authorizations_test.go +++ /dev/null @@ -1,359 +0,0 @@ -// Copyright 2015 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestAuthorizationsService_List(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/authorizations", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "1", "per_page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 1, PerPage: 2} - got, _, err := client.Authorizations.List(context.Background(), opt) - if err != nil { - t.Errorf("Authorizations.List returned error: %v", err) - } - - want := []*Authorization{{ID: Int(1)}} - if !reflect.DeepEqual(got, want) { - t.Errorf("Authorizations.List returned %+v, want %+v", *got[0].ID, *want[0].ID) - } -} - -func TestAuthorizationsService_Get(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/authorizations/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - got, _, err := client.Authorizations.Get(context.Background(), 1) - if err != nil { - t.Errorf("Authorizations.Get returned error: %v", err) - } - - want := &Authorization{ID: Int(1)} - if !reflect.DeepEqual(got, want) { - t.Errorf("Authorizations.Get returned auth %+v, want %+v", got, want) - } -} - -func TestAuthorizationsService_Create(t *testing.T) { - setup() - defer teardown() - - input := &AuthorizationRequest{ - Note: String("test"), - } - - mux.HandleFunc("/authorizations", func(w http.ResponseWriter, r *http.Request) { - v := new(AuthorizationRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"ID":1}`) - }) - - got, _, err := client.Authorizations.Create(context.Background(), input) - if err != nil { - t.Errorf("Authorizations.Create returned error: %v", err) - } - - want := &Authorization{ID: Int(1)} - if !reflect.DeepEqual(got, want) { - t.Errorf("Authorization.Create returned %+v, want %+v", got, want) - } -} - -func TestAuthorizationsService_GetOrCreateForApp(t *testing.T) { - setup() - defer teardown() - - input := &AuthorizationRequest{ - Note: String("test"), - } - - mux.HandleFunc("/authorizations/clients/id", func(w http.ResponseWriter, r *http.Request) { - v := new(AuthorizationRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PUT") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"ID":1}`) - }) - - got, _, err := client.Authorizations.GetOrCreateForApp(context.Background(), "id", input) - if err != nil { - t.Errorf("Authorizations.GetOrCreateForApp returned error: %v", err) - } - - want := &Authorization{ID: Int(1)} - if !reflect.DeepEqual(got, want) { - t.Errorf("Authorization.GetOrCreateForApp returned %+v, want %+v", got, want) - } -} - -func TestAuthorizationsService_GetOrCreateForApp_Fingerprint(t *testing.T) { - setup() - defer teardown() - - input := &AuthorizationRequest{ - Note: String("test"), - Fingerprint: String("fp"), - } - - mux.HandleFunc("/authorizations/clients/id/fp", func(w http.ResponseWriter, r *http.Request) { - v := new(AuthorizationRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PUT") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"ID":1}`) - }) - - got, _, err := client.Authorizations.GetOrCreateForApp(context.Background(), "id", input) - if err != nil { - t.Errorf("Authorizations.GetOrCreateForApp returned error: %v", err) - } - - want := &Authorization{ID: Int(1)} - if !reflect.DeepEqual(got, want) { - t.Errorf("Authorization.GetOrCreateForApp returned %+v, want %+v", got, want) - } -} - -func TestAuthorizationsService_Edit(t *testing.T) { - setup() - defer teardown() - - input := &AuthorizationUpdateRequest{ - Note: String("test"), - } - - mux.HandleFunc("/authorizations/1", func(w http.ResponseWriter, r *http.Request) { - v := new(AuthorizationUpdateRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"ID":1}`) - }) - - got, _, err := client.Authorizations.Edit(context.Background(), 1, input) - if err != nil { - t.Errorf("Authorizations.Edit returned error: %v", err) - } - - want := &Authorization{ID: Int(1)} - if !reflect.DeepEqual(got, want) { - t.Errorf("Authorization.Update returned %+v, want %+v", got, want) - } -} - -func TestAuthorizationsService_Delete(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/authorizations/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Authorizations.Delete(context.Background(), 1) - if err != nil { - t.Errorf("Authorizations.Delete returned error: %v", err) - } -} - -func TestAuthorizationsService_Check(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/applications/id/tokens/t", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - got, _, err := client.Authorizations.Check(context.Background(), "id", "t") - if err != nil { - t.Errorf("Authorizations.Check returned error: %v", err) - } - - want := &Authorization{ID: Int(1)} - if !reflect.DeepEqual(got, want) { - t.Errorf("Authorizations.Check returned auth %+v, want %+v", got, want) - } -} - -func TestAuthorizationsService_Reset(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/applications/id/tokens/t", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - fmt.Fprint(w, `{"ID":1}`) - }) - - got, _, err := client.Authorizations.Reset(context.Background(), "id", "t") - if err != nil { - t.Errorf("Authorizations.Reset returned error: %v", err) - } - - want := &Authorization{ID: Int(1)} - if !reflect.DeepEqual(got, want) { - t.Errorf("Authorizations.Reset returned auth %+v, want %+v", got, want) - } -} - -func TestAuthorizationsService_Revoke(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/applications/id/tokens/t", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Authorizations.Revoke(context.Background(), "id", "t") - if err != nil { - t.Errorf("Authorizations.Revoke returned error: %v", err) - } -} - -func TestListGrants(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/applications/grants", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id": 1}]`) - }) - - got, _, err := client.Authorizations.ListGrants(context.Background(), nil) - if err != nil { - t.Errorf("OAuthAuthorizations.ListGrants returned error: %v", err) - } - - want := []*Grant{{ID: Int(1)}} - if !reflect.DeepEqual(got, want) { - t.Errorf("OAuthAuthorizations.ListGrants = %+v, want %+v", got, want) - } -} - -func TestListGrants_withOptions(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/applications/grants", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id": 1}]`) - }) - - _, _, err := client.Authorizations.ListGrants(context.Background(), &ListOptions{Page: 2}) - if err != nil { - t.Errorf("OAuthAuthorizations.ListGrants returned error: %v", err) - } -} - -func TestGetGrant(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/applications/grants/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id": 1}`) - }) - - got, _, err := client.Authorizations.GetGrant(context.Background(), 1) - if err != nil { - t.Errorf("OAuthAuthorizations.GetGrant returned error: %v", err) - } - - want := &Grant{ID: Int(1)} - if !reflect.DeepEqual(got, want) { - t.Errorf("OAuthAuthorizations.GetGrant = %+v, want %+v", got, want) - } -} - -func TestDeleteGrant(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/applications/grants/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Authorizations.DeleteGrant(context.Background(), 1) - if err != nil { - t.Errorf("OAuthAuthorizations.DeleteGrant returned error: %v", err) - } -} - -func TestAuthorizationsService_CreateImpersonation(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/admin/users/u/authorizations", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - fmt.Fprint(w, `{"id":1}`) - }) - - req := &AuthorizationRequest{Scopes: []Scope{ScopePublicRepo}} - got, _, err := client.Authorizations.CreateImpersonation(context.Background(), "u", req) - if err != nil { - t.Errorf("Authorizations.CreateImpersonation returned error: %+v", err) - } - - want := &Authorization{ID: Int(1)} - if !reflect.DeepEqual(got, want) { - t.Errorf("Authorizations.CreateImpersonation returned %+v, want %+v", *got.ID, *want.ID) - } -} - -func TestAuthorizationsService_DeleteImpersonation(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/admin/users/u/authorizations", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Authorizations.DeleteImpersonation(context.Background(), "u") - if err != nil { - t.Errorf("Authorizations.DeleteImpersonation returned error: %+v", err) - } -} diff --git a/vendor/github.com/google/go-github/github/examples_test.go b/vendor/github.com/google/go-github/github/examples_test.go deleted file mode 100644 index f09d6505ac76..000000000000 --- a/vendor/github.com/google/go-github/github/examples_test.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github_test - -import ( - "context" - "fmt" - "log" - - "github.com/google/go-github/github" -) - -func ExampleClient_Markdown() { - client := github.NewClient(nil) - - input := "# heading #\n\nLink to issue #1" - opt := &github.MarkdownOptions{Mode: "gfm", Context: "google/go-github"} - - output, _, err := client.Markdown(context.Background(), input, opt) - if err != nil { - fmt.Println(err) - } - - fmt.Println(output) -} - -func ExampleRepositoriesService_GetReadme() { - client := github.NewClient(nil) - - readme, _, err := client.Repositories.GetReadme(context.Background(), "google", "go-github", nil) - if err != nil { - fmt.Println(err) - return - } - - content, err := readme.GetContent() - if err != nil { - fmt.Println(err) - return - } - - fmt.Printf("google/go-github README:\n%v\n", content) -} - -func ExampleRepositoriesService_List() { - client := github.NewClient(nil) - - user := "willnorris" - opt := &github.RepositoryListOptions{Type: "owner", Sort: "updated", Direction: "desc"} - - repos, _, err := client.Repositories.List(context.Background(), user, opt) - if err != nil { - fmt.Println(err) - } - - fmt.Printf("Recently updated repositories by %q: %v", user, github.Stringify(repos)) -} - -func ExampleUsersService_ListAll() { - client := github.NewClient(nil) - opts := &github.UserListOptions{} - for { - users, _, err := client.Users.ListAll(context.Background(), opts) - if err != nil { - log.Fatalf("error listing users: %v", err) - } - if len(users) == 0 { - break - } - opts.Since = *users[len(users)-1].ID - // Process users... - } -} diff --git a/vendor/github.com/google/go-github/github/gists_comments_test.go b/vendor/github.com/google/go-github/github/gists_comments_test.go deleted file mode 100644 index 4b6841363ea5..000000000000 --- a/vendor/github.com/google/go-github/github/gists_comments_test.go +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestGistsService_ListComments(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/comments", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id": 1}]`) - }) - - opt := &ListOptions{Page: 2} - comments, _, err := client.Gists.ListComments(context.Background(), "1", opt) - if err != nil { - t.Errorf("Gists.Comments returned error: %v", err) - } - - want := []*GistComment{{ID: Int(1)}} - if !reflect.DeepEqual(comments, want) { - t.Errorf("Gists.ListComments returned %+v, want %+v", comments, want) - } -} - -func TestGistsService_ListComments_invalidID(t *testing.T) { - _, _, err := client.Gists.ListComments(context.Background(), "%", nil) - testURLParseError(t, err) -} - -func TestGistsService_GetComment(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/comments/2", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id": 1}`) - }) - - comment, _, err := client.Gists.GetComment(context.Background(), "1", 2) - if err != nil { - t.Errorf("Gists.GetComment returned error: %v", err) - } - - want := &GistComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("Gists.GetComment returned %+v, want %+v", comment, want) - } -} - -func TestGistsService_GetComment_invalidID(t *testing.T) { - _, _, err := client.Gists.GetComment(context.Background(), "%", 1) - testURLParseError(t, err) -} - -func TestGistsService_CreateComment(t *testing.T) { - setup() - defer teardown() - - input := &GistComment{ID: Int(1), Body: String("b")} - - mux.HandleFunc("/gists/1/comments", func(w http.ResponseWriter, r *http.Request) { - v := new(GistComment) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.Gists.CreateComment(context.Background(), "1", input) - if err != nil { - t.Errorf("Gists.CreateComment returned error: %v", err) - } - - want := &GistComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("Gists.CreateComment returned %+v, want %+v", comment, want) - } -} - -func TestGistsService_CreateComment_invalidID(t *testing.T) { - _, _, err := client.Gists.CreateComment(context.Background(), "%", nil) - testURLParseError(t, err) -} - -func TestGistsService_EditComment(t *testing.T) { - setup() - defer teardown() - - input := &GistComment{ID: Int(1), Body: String("b")} - - mux.HandleFunc("/gists/1/comments/2", func(w http.ResponseWriter, r *http.Request) { - v := new(GistComment) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.Gists.EditComment(context.Background(), "1", 2, input) - if err != nil { - t.Errorf("Gists.EditComment returned error: %v", err) - } - - want := &GistComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("Gists.EditComment returned %+v, want %+v", comment, want) - } -} - -func TestGistsService_EditComment_invalidID(t *testing.T) { - _, _, err := client.Gists.EditComment(context.Background(), "%", 1, nil) - testURLParseError(t, err) -} - -func TestGistsService_DeleteComment(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/comments/2", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Gists.DeleteComment(context.Background(), "1", 2) - if err != nil { - t.Errorf("Gists.Delete returned error: %v", err) - } -} - -func TestGistsService_DeleteComment_invalidID(t *testing.T) { - _, err := client.Gists.DeleteComment(context.Background(), "%", 1) - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/gists_test.go b/vendor/github.com/google/go-github/github/gists_test.go deleted file mode 100644 index 6065f277d8ad..000000000000 --- a/vendor/github.com/google/go-github/github/gists_test.go +++ /dev/null @@ -1,507 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestGistsService_List_specifiedUser(t *testing.T) { - setup() - defer teardown() - - since := "2013-01-01T00:00:00Z" - - mux.HandleFunc("/users/u/gists", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "since": since, - }) - fmt.Fprint(w, `[{"id": "1"}]`) - }) - - opt := &GistListOptions{Since: time.Date(2013, time.January, 1, 0, 0, 0, 0, time.UTC)} - gists, _, err := client.Gists.List(context.Background(), "u", opt) - if err != nil { - t.Errorf("Gists.List returned error: %v", err) - } - - want := []*Gist{{ID: String("1")}} - if !reflect.DeepEqual(gists, want) { - t.Errorf("Gists.List returned %+v, want %+v", gists, want) - } -} - -func TestGistsService_List_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id": "1"}]`) - }) - - gists, _, err := client.Gists.List(context.Background(), "", nil) - if err != nil { - t.Errorf("Gists.List returned error: %v", err) - } - - want := []*Gist{{ID: String("1")}} - if !reflect.DeepEqual(gists, want) { - t.Errorf("Gists.List returned %+v, want %+v", gists, want) - } -} - -func TestGistsService_List_invalidUser(t *testing.T) { - _, _, err := client.Gists.List(context.Background(), "%", nil) - testURLParseError(t, err) -} - -func TestGistsService_ListAll(t *testing.T) { - setup() - defer teardown() - - since := "2013-01-01T00:00:00Z" - - mux.HandleFunc("/gists/public", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "since": since, - }) - fmt.Fprint(w, `[{"id": "1"}]`) - }) - - opt := &GistListOptions{Since: time.Date(2013, time.January, 1, 0, 0, 0, 0, time.UTC)} - gists, _, err := client.Gists.ListAll(context.Background(), opt) - if err != nil { - t.Errorf("Gists.ListAll returned error: %v", err) - } - - want := []*Gist{{ID: String("1")}} - if !reflect.DeepEqual(gists, want) { - t.Errorf("Gists.ListAll returned %+v, want %+v", gists, want) - } -} - -func TestGistsService_ListStarred(t *testing.T) { - setup() - defer teardown() - - since := "2013-01-01T00:00:00Z" - - mux.HandleFunc("/gists/starred", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "since": since, - }) - fmt.Fprint(w, `[{"id": "1"}]`) - }) - - opt := &GistListOptions{Since: time.Date(2013, time.January, 1, 0, 0, 0, 0, time.UTC)} - gists, _, err := client.Gists.ListStarred(context.Background(), opt) - if err != nil { - t.Errorf("Gists.ListStarred returned error: %v", err) - } - - want := []*Gist{{ID: String("1")}} - if !reflect.DeepEqual(gists, want) { - t.Errorf("Gists.ListStarred returned %+v, want %+v", gists, want) - } -} - -func TestGistsService_Get(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id": "1"}`) - }) - - gist, _, err := client.Gists.Get(context.Background(), "1") - if err != nil { - t.Errorf("Gists.Get returned error: %v", err) - } - - want := &Gist{ID: String("1")} - if !reflect.DeepEqual(gist, want) { - t.Errorf("Gists.Get returned %+v, want %+v", gist, want) - } -} - -func TestGistsService_Get_invalidID(t *testing.T) { - _, _, err := client.Gists.Get(context.Background(), "%") - testURLParseError(t, err) -} - -func TestGistsService_GetRevision(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/s", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id": "1"}`) - }) - - gist, _, err := client.Gists.GetRevision(context.Background(), "1", "s") - if err != nil { - t.Errorf("Gists.Get returned error: %v", err) - } - - want := &Gist{ID: String("1")} - if !reflect.DeepEqual(gist, want) { - t.Errorf("Gists.Get returned %+v, want %+v", gist, want) - } -} - -func TestGistsService_GetRevision_invalidID(t *testing.T) { - _, _, err := client.Gists.GetRevision(context.Background(), "%", "%") - testURLParseError(t, err) -} - -func TestGistsService_Create(t *testing.T) { - setup() - defer teardown() - - input := &Gist{ - Description: String("Gist description"), - Public: Bool(false), - Files: map[GistFilename]GistFile{ - "test.txt": {Content: String("Gist file content")}, - }, - } - - mux.HandleFunc("/gists", func(w http.ResponseWriter, r *http.Request) { - v := new(Gist) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, - ` - { - "id": "1", - "description": "Gist description", - "public": false, - "files": { - "test.txt": { - "filename": "test.txt" - } - } - }`) - }) - - gist, _, err := client.Gists.Create(context.Background(), input) - if err != nil { - t.Errorf("Gists.Create returned error: %v", err) - } - - want := &Gist{ - ID: String("1"), - Description: String("Gist description"), - Public: Bool(false), - Files: map[GistFilename]GistFile{ - "test.txt": {Filename: String("test.txt")}, - }, - } - if !reflect.DeepEqual(gist, want) { - t.Errorf("Gists.Create returned %+v, want %+v", gist, want) - } -} - -func TestGistsService_Edit(t *testing.T) { - setup() - defer teardown() - - input := &Gist{ - Description: String("New description"), - Files: map[GistFilename]GistFile{ - "new.txt": {Content: String("new file content")}, - }, - } - - mux.HandleFunc("/gists/1", func(w http.ResponseWriter, r *http.Request) { - v := new(Gist) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, - ` - { - "id": "1", - "description": "new description", - "public": false, - "files": { - "test.txt": { - "filename": "test.txt" - }, - "new.txt": { - "filename": "new.txt" - } - } - }`) - }) - - gist, _, err := client.Gists.Edit(context.Background(), "1", input) - if err != nil { - t.Errorf("Gists.Edit returned error: %v", err) - } - - want := &Gist{ - ID: String("1"), - Description: String("new description"), - Public: Bool(false), - Files: map[GistFilename]GistFile{ - "test.txt": {Filename: String("test.txt")}, - "new.txt": {Filename: String("new.txt")}, - }, - } - if !reflect.DeepEqual(gist, want) { - t.Errorf("Gists.Edit returned %+v, want %+v", gist, want) - } -} - -func TestGistsService_Edit_invalidID(t *testing.T) { - _, _, err := client.Gists.Edit(context.Background(), "%", nil) - testURLParseError(t, err) -} - -func TestGistsService_ListCommits(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/commits", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, nil) - fmt.Fprint(w, ` - [ - { - "url": "https://api.github.com/gists/1/1", - "version": "1", - "user": { - "id": 1 - }, - "change_status": { - "deletions": 0, - "additions": 180, - "total": 180 - }, - "committed_at": "2010-01-01T00:00:00Z" - } - ] - `) - }) - - gistCommits, _, err := client.Gists.ListCommits(context.Background(), "1", nil) - if err != nil { - t.Errorf("Gists.ListCommits returned error: %v", err) - } - - want := []*GistCommit{{ - URL: String("https://api.github.com/gists/1/1"), - Version: String("1"), - User: &User{ID: Int(1)}, - CommittedAt: &Timestamp{time.Date(2010, 1, 1, 00, 00, 00, 0, time.UTC)}, - ChangeStatus: &CommitStats{ - Additions: Int(180), - Deletions: Int(0), - Total: Int(180), - }}} - - if !reflect.DeepEqual(gistCommits, want) { - t.Errorf("Gists.ListCommits returned %+v, want %+v", gistCommits, want) - } -} - -func TestGistsService_ListCommits_withOptions(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/commits", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[]`) - }) - - _, _, err := client.Gists.ListCommits(context.Background(), "1", &ListOptions{Page: 2}) - if err != nil { - t.Errorf("Gists.ListCommits returned error: %v", err) - } -} - -func TestGistsService_Delete(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Gists.Delete(context.Background(), "1") - if err != nil { - t.Errorf("Gists.Delete returned error: %v", err) - } -} - -func TestGistsService_Delete_invalidID(t *testing.T) { - _, err := client.Gists.Delete(context.Background(), "%") - testURLParseError(t, err) -} - -func TestGistsService_Star(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/star", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - }) - - _, err := client.Gists.Star(context.Background(), "1") - if err != nil { - t.Errorf("Gists.Star returned error: %v", err) - } -} - -func TestGistsService_Star_invalidID(t *testing.T) { - _, err := client.Gists.Star(context.Background(), "%") - testURLParseError(t, err) -} - -func TestGistsService_Unstar(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/star", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Gists.Unstar(context.Background(), "1") - if err != nil { - t.Errorf("Gists.Unstar returned error: %v", err) - } -} - -func TestGistsService_Unstar_invalidID(t *testing.T) { - _, err := client.Gists.Unstar(context.Background(), "%") - testURLParseError(t, err) -} - -func TestGistsService_IsStarred_hasStar(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/star", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNoContent) - }) - - star, _, err := client.Gists.IsStarred(context.Background(), "1") - if err != nil { - t.Errorf("Gists.Starred returned error: %v", err) - } - if want := true; star != want { - t.Errorf("Gists.Starred returned %+v, want %+v", star, want) - } -} - -func TestGistsService_IsStarred_noStar(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/star", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - star, _, err := client.Gists.IsStarred(context.Background(), "1") - if err != nil { - t.Errorf("Gists.Starred returned error: %v", err) - } - if want := false; star != want { - t.Errorf("Gists.Starred returned %+v, want %+v", star, want) - } -} - -func TestGistsService_IsStarred_invalidID(t *testing.T) { - _, _, err := client.Gists.IsStarred(context.Background(), "%") - testURLParseError(t, err) -} - -func TestGistsService_Fork(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/forks", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - fmt.Fprint(w, `{"id": "2"}`) - }) - - gist, _, err := client.Gists.Fork(context.Background(), "1") - if err != nil { - t.Errorf("Gists.Fork returned error: %v", err) - } - - want := &Gist{ID: String("2")} - if !reflect.DeepEqual(gist, want) { - t.Errorf("Gists.Fork returned %+v, want %+v", gist, want) - } -} - -func TestGistsService_ListForks(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gists/1/forks", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, nil) - fmt.Fprint(w, ` - [ - {"url": "https://api.github.com/gists/1", - "user": {"id": 1}, - "id": "1", - "created_at": "2010-01-01T00:00:00Z", - "updated_at": "2013-01-01T00:00:00Z" - } - ] - `) - }) - - gistForks, _, err := client.Gists.ListForks(context.Background(), "1") - if err != nil { - t.Errorf("Gists.ListForks returned error: %v", err) - } - - want := []*GistFork{{ - URL: String("https://api.github.com/gists/1"), - ID: String("1"), - User: &User{ID: Int(1)}, - CreatedAt: &Timestamp{time.Date(2010, 1, 1, 00, 00, 00, 0, time.UTC)}, - UpdatedAt: &Timestamp{time.Date(2013, 1, 1, 00, 00, 00, 0, time.UTC)}}} - - if !reflect.DeepEqual(gistForks, want) { - t.Errorf("Gists.ListForks returned %+v, want %+v", gistForks, want) - } -} - -func TestGistsService_Fork_invalidID(t *testing.T) { - _, _, err := client.Gists.Fork(context.Background(), "%") - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/git_blobs_test.go b/vendor/github.com/google/go-github/github/git_blobs_test.go deleted file mode 100644 index 00861bb9a641..000000000000 --- a/vendor/github.com/google/go-github/github/git_blobs_test.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestGitService_GetBlob(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/blobs/s", func(w http.ResponseWriter, r *http.Request) { - if m := "GET"; m != r.Method { - t.Errorf("Request method = %v, want %v", r.Method, m) - } - fmt.Fprint(w, `{ - "sha": "s", - "content": "blob content" - }`) - }) - - blob, _, err := client.Git.GetBlob(context.Background(), "o", "r", "s") - if err != nil { - t.Errorf("Git.GetBlob returned error: %v", err) - } - - want := Blob{ - SHA: String("s"), - Content: String("blob content"), - } - - if !reflect.DeepEqual(*blob, want) { - t.Errorf("Blob.Get returned %+v, want %+v", *blob, want) - } -} - -func TestGitService_GetBlob_invalidOwner(t *testing.T) { - _, _, err := client.Git.GetBlob(context.Background(), "%", "%", "%") - testURLParseError(t, err) -} - -func TestGitService_CreateBlob(t *testing.T) { - setup() - defer teardown() - - input := &Blob{ - SHA: String("s"), - Content: String("blob content"), - Encoding: String("utf-8"), - Size: Int(12), - } - - mux.HandleFunc("/repos/o/r/git/blobs", func(w http.ResponseWriter, r *http.Request) { - v := new(Blob) - json.NewDecoder(r.Body).Decode(v) - - if m := "POST"; m != r.Method { - t.Errorf("Request method = %v, want %v", r.Method, m) - } - - want := input - if !reflect.DeepEqual(v, want) { - t.Errorf("Git.CreateBlob request body: %+v, want %+v", v, want) - } - - fmt.Fprint(w, `{ - "sha": "s", - "content": "blob content", - "encoding": "utf-8", - "size": 12 - }`) - }) - - blob, _, err := client.Git.CreateBlob(context.Background(), "o", "r", input) - if err != nil { - t.Errorf("Git.CreateBlob returned error: %v", err) - } - - want := input - - if !reflect.DeepEqual(*blob, *want) { - t.Errorf("Git.CreateBlob returned %+v, want %+v", *blob, *want) - } -} - -func TestGitService_CreateBlob_invalidOwner(t *testing.T) { - _, _, err := client.Git.CreateBlob(context.Background(), "%", "%", &Blob{}) - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/git_commits_test.go b/vendor/github.com/google/go-github/github/git_commits_test.go deleted file mode 100644 index cd392329ea2d..000000000000 --- a/vendor/github.com/google/go-github/github/git_commits_test.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestGitService_GetCommit(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/commits/s", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeGitSigningPreview) - fmt.Fprint(w, `{"sha":"s","message":"m","author":{"name":"n"}}`) - }) - - commit, _, err := client.Git.GetCommit(context.Background(), "o", "r", "s") - if err != nil { - t.Errorf("Git.GetCommit returned error: %v", err) - } - - want := &Commit{SHA: String("s"), Message: String("m"), Author: &CommitAuthor{Name: String("n")}} - if !reflect.DeepEqual(commit, want) { - t.Errorf("Git.GetCommit returned %+v, want %+v", commit, want) - } -} - -func TestGitService_GetCommit_invalidOwner(t *testing.T) { - _, _, err := client.Git.GetCommit(context.Background(), "%", "%", "%") - testURLParseError(t, err) -} - -func TestGitService_CreateCommit(t *testing.T) { - setup() - defer teardown() - - input := &Commit{ - Message: String("m"), - Tree: &Tree{SHA: String("t")}, - Parents: []Commit{{SHA: String("p")}}, - } - - mux.HandleFunc("/repos/o/r/git/commits", func(w http.ResponseWriter, r *http.Request) { - v := new(createCommit) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - - want := &createCommit{ - Message: input.Message, - Tree: String("t"), - Parents: []string{"p"}, - } - if !reflect.DeepEqual(v, want) { - t.Errorf("Request body = %+v, want %+v", v, want) - } - fmt.Fprint(w, `{"sha":"s"}`) - }) - - commit, _, err := client.Git.CreateCommit(context.Background(), "o", "r", input) - if err != nil { - t.Errorf("Git.CreateCommit returned error: %v", err) - } - - want := &Commit{SHA: String("s")} - if !reflect.DeepEqual(commit, want) { - t.Errorf("Git.CreateCommit returned %+v, want %+v", commit, want) - } -} - -func TestGitService_CreateCommit_invalidOwner(t *testing.T) { - _, _, err := client.Git.CreateCommit(context.Background(), "%", "%", &Commit{}) - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/git_refs_test.go b/vendor/github.com/google/go-github/github/git_refs_test.go deleted file mode 100644 index 62025bf44460..000000000000 --- a/vendor/github.com/google/go-github/github/git_refs_test.go +++ /dev/null @@ -1,429 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestGitService_GetRef_singleRef(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/refs/heads/b", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, ` - { - "ref": "refs/heads/b", - "url": "https://api.github.com/repos/o/r/git/refs/heads/b", - "object": { - "type": "commit", - "sha": "aa218f56b14c9653891f9e74264a383fa43fefbd", - "url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd" - } - }`) - }) - - ref, _, err := client.Git.GetRef(context.Background(), "o", "r", "refs/heads/b") - if err != nil { - t.Fatalf("Git.GetRef returned error: %v", err) - } - - want := &Reference{ - Ref: String("refs/heads/b"), - URL: String("https://api.github.com/repos/o/r/git/refs/heads/b"), - Object: &GitObject{ - Type: String("commit"), - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"), - }, - } - if !reflect.DeepEqual(ref, want) { - t.Errorf("Git.GetRef returned %+v, want %+v", ref, want) - } - - // without 'refs/' prefix - if _, _, err := client.Git.GetRef(context.Background(), "o", "r", "heads/b"); err != nil { - t.Errorf("Git.GetRef returned error: %v", err) - } -} - -func TestGitService_GetRef_multipleRefs(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/refs/heads/b", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, ` - [ - { - "ref": "refs/heads/booger", - "url": "https://api.github.com/repos/o/r/git/refs/heads/booger", - "object": { - "type": "commit", - "sha": "aa218f56b14c9653891f9e74264a383fa43fefbd", - "url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd" - } - }, - { - "ref": "refs/heads/bandsaw", - "url": "https://api.github.com/repos/o/r/git/refs/heads/bandsaw", - "object": { - "type": "commit", - "sha": "612077ae6dffb4d2fbd8ce0cccaa58893b07b5ac", - "url": "https://api.github.com/repos/o/r/git/commits/612077ae6dffb4d2fbd8ce0cccaa58893b07b5ac" - } - } - ] - `) - }) - - _, _, err := client.Git.GetRef(context.Background(), "o", "r", "refs/heads/b") - want := "no exact match found for this ref" - if err.Error() != want { - t.Errorf("Git.GetRef returned %+v, want %+v", err, want) - } - -} - -func TestGitService_GetRefs_singleRef(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/refs/heads/b", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, ` - { - "ref": "refs/heads/b", - "url": "https://api.github.com/repos/o/r/git/refs/heads/b", - "object": { - "type": "commit", - "sha": "aa218f56b14c9653891f9e74264a383fa43fefbd", - "url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd" - } - }`) - }) - - refs, _, err := client.Git.GetRefs(context.Background(), "o", "r", "refs/heads/b") - if err != nil { - t.Fatalf("Git.GetRefs returned error: %v", err) - } - - ref := refs[0] - want := &Reference{ - Ref: String("refs/heads/b"), - URL: String("https://api.github.com/repos/o/r/git/refs/heads/b"), - Object: &GitObject{ - Type: String("commit"), - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"), - }, - } - if !reflect.DeepEqual(ref, want) { - t.Errorf("Git.GetRefs returned %+v, want %+v", ref, want) - } - - // without 'refs/' prefix - if _, _, err := client.Git.GetRefs(context.Background(), "o", "r", "heads/b"); err != nil { - t.Errorf("Git.GetRefs returned error: %v", err) - } -} - -func TestGitService_GetRefs_multipleRefs(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/refs/heads/b", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, ` - [ - { - "ref": "refs/heads/booger", - "url": "https://api.github.com/repos/o/r/git/refs/heads/booger", - "object": { - "type": "commit", - "sha": "aa218f56b14c9653891f9e74264a383fa43fefbd", - "url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd" - } - }, - { - "ref": "refs/heads/bandsaw", - "url": "https://api.github.com/repos/o/r/git/refs/heads/bandsaw", - "object": { - "type": "commit", - "sha": "612077ae6dffb4d2fbd8ce0cccaa58893b07b5ac", - "url": "https://api.github.com/repos/o/r/git/commits/612077ae6dffb4d2fbd8ce0cccaa58893b07b5ac" - } - } - ] - `) - }) - - refs, _, err := client.Git.GetRefs(context.Background(), "o", "r", "refs/heads/b") - if err != nil { - t.Errorf("Git.GetRefs returned error: %v", err) - } - - want := &Reference{ - Ref: String("refs/heads/booger"), - URL: String("https://api.github.com/repos/o/r/git/refs/heads/booger"), - Object: &GitObject{ - Type: String("commit"), - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"), - }, - } - if !reflect.DeepEqual(refs[0], want) { - t.Errorf("Git.GetRefs returned %+v, want %+v", refs[0], want) - } -} - -// TestGitService_GetRefs_noRefs tests for behaviour resulting from an unexpected GH response. This should never actually happen. -func TestGitService_GetRefs_noRefs(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/refs/heads/b", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, "[]") - }) - - _, _, err := client.Git.GetRefs(context.Background(), "o", "r", "refs/heads/b") - want := "unexpected response from GitHub API: an array of refs with length 0" - if err.Error() != want { - t.Errorf("Git.GetRefs returned %+v, want %+v", err, want) - } - -} - -func TestGitService_ListRefs(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/refs", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, ` - [ - { - "ref": "refs/heads/branchA", - "url": "https://api.github.com/repos/o/r/git/refs/heads/branchA", - "object": { - "type": "commit", - "sha": "aa218f56b14c9653891f9e74264a383fa43fefbd", - "url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd" - } - }, - { - "ref": "refs/heads/branchB", - "url": "https://api.github.com/repos/o/r/git/refs/heads/branchB", - "object": { - "type": "commit", - "sha": "aa218f56b14c9653891f9e74264a383fa43fefbd", - "url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd" - } - } - ]`) - }) - - refs, _, err := client.Git.ListRefs(context.Background(), "o", "r", nil) - if err != nil { - t.Errorf("Git.ListRefs returned error: %v", err) - } - - want := []*Reference{ - { - Ref: String("refs/heads/branchA"), - URL: String("https://api.github.com/repos/o/r/git/refs/heads/branchA"), - Object: &GitObject{ - Type: String("commit"), - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"), - }, - }, - { - Ref: String("refs/heads/branchB"), - URL: String("https://api.github.com/repos/o/r/git/refs/heads/branchB"), - Object: &GitObject{ - Type: String("commit"), - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"), - }, - }, - } - if !reflect.DeepEqual(refs, want) { - t.Errorf("Git.ListRefs returned %+v, want %+v", refs, want) - } -} - -func TestGitService_ListRefs_options(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/refs/t", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"ref": "r"}]`) - }) - - opt := &ReferenceListOptions{Type: "t", ListOptions: ListOptions{Page: 2}} - refs, _, err := client.Git.ListRefs(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Git.ListRefs returned error: %v", err) - } - - want := []*Reference{{Ref: String("r")}} - if !reflect.DeepEqual(refs, want) { - t.Errorf("Git.ListRefs returned %+v, want %+v", refs, want) - } -} - -func TestGitService_CreateRef(t *testing.T) { - setup() - defer teardown() - - args := &createRefRequest{ - Ref: String("refs/heads/b"), - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - } - - mux.HandleFunc("/repos/o/r/git/refs", func(w http.ResponseWriter, r *http.Request) { - v := new(createRefRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, args) { - t.Errorf("Request body = %+v, want %+v", v, args) - } - fmt.Fprint(w, ` - { - "ref": "refs/heads/b", - "url": "https://api.github.com/repos/o/r/git/refs/heads/b", - "object": { - "type": "commit", - "sha": "aa218f56b14c9653891f9e74264a383fa43fefbd", - "url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd" - } - }`) - }) - - ref, _, err := client.Git.CreateRef(context.Background(), "o", "r", &Reference{ - Ref: String("refs/heads/b"), - Object: &GitObject{ - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - }, - }) - if err != nil { - t.Errorf("Git.CreateRef returned error: %v", err) - } - - want := &Reference{ - Ref: String("refs/heads/b"), - URL: String("https://api.github.com/repos/o/r/git/refs/heads/b"), - Object: &GitObject{ - Type: String("commit"), - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"), - }, - } - if !reflect.DeepEqual(ref, want) { - t.Errorf("Git.CreateRef returned %+v, want %+v", ref, want) - } - - // without 'refs/' prefix - _, _, err = client.Git.CreateRef(context.Background(), "o", "r", &Reference{ - Ref: String("heads/b"), - Object: &GitObject{ - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - }, - }) - if err != nil { - t.Errorf("Git.CreateRef returned error: %v", err) - } -} - -func TestGitService_UpdateRef(t *testing.T) { - setup() - defer teardown() - - args := &updateRefRequest{ - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - Force: Bool(true), - } - - mux.HandleFunc("/repos/o/r/git/refs/heads/b", func(w http.ResponseWriter, r *http.Request) { - v := new(updateRefRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, args) { - t.Errorf("Request body = %+v, want %+v", v, args) - } - fmt.Fprint(w, ` - { - "ref": "refs/heads/b", - "url": "https://api.github.com/repos/o/r/git/refs/heads/b", - "object": { - "type": "commit", - "sha": "aa218f56b14c9653891f9e74264a383fa43fefbd", - "url": "https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd" - } - }`) - }) - - ref, _, err := client.Git.UpdateRef(context.Background(), "o", "r", &Reference{ - Ref: String("refs/heads/b"), - Object: &GitObject{SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd")}, - }, true) - if err != nil { - t.Errorf("Git.UpdateRef returned error: %v", err) - } - - want := &Reference{ - Ref: String("refs/heads/b"), - URL: String("https://api.github.com/repos/o/r/git/refs/heads/b"), - Object: &GitObject{ - Type: String("commit"), - SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd"), - URL: String("https://api.github.com/repos/o/r/git/commits/aa218f56b14c9653891f9e74264a383fa43fefbd"), - }, - } - if !reflect.DeepEqual(ref, want) { - t.Errorf("Git.UpdateRef returned %+v, want %+v", ref, want) - } - - // without 'refs/' prefix - _, _, err = client.Git.UpdateRef(context.Background(), "o", "r", &Reference{ - Ref: String("heads/b"), - Object: &GitObject{SHA: String("aa218f56b14c9653891f9e74264a383fa43fefbd")}, - }, true) - if err != nil { - t.Errorf("Git.UpdateRef returned error: %v", err) - } -} - -func TestGitService_DeleteRef(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/refs/heads/b", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Git.DeleteRef(context.Background(), "o", "r", "refs/heads/b") - if err != nil { - t.Errorf("Git.DeleteRef returned error: %v", err) - } - - // without 'refs/' prefix - if _, err := client.Git.DeleteRef(context.Background(), "o", "r", "heads/b"); err != nil { - t.Errorf("Git.DeleteRef returned error: %v", err) - } -} diff --git a/vendor/github.com/google/go-github/github/git_tags_test.go b/vendor/github.com/google/go-github/github/git_tags_test.go deleted file mode 100644 index 7031fe8a4d3e..000000000000 --- a/vendor/github.com/google/go-github/github/git_tags_test.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestGitService_GetTag(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/tags/s", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeGitSigningPreview) - - fmt.Fprint(w, `{"tag": "t"}`) - }) - - tag, _, err := client.Git.GetTag(context.Background(), "o", "r", "s") - if err != nil { - t.Errorf("Git.GetTag returned error: %v", err) - } - - want := &Tag{Tag: String("t")} - if !reflect.DeepEqual(tag, want) { - t.Errorf("Git.GetTag returned %+v, want %+v", tag, want) - } -} - -func TestGitService_CreateTag(t *testing.T) { - setup() - defer teardown() - - input := &createTagRequest{Tag: String("t"), Object: String("s")} - - mux.HandleFunc("/repos/o/r/git/tags", func(w http.ResponseWriter, r *http.Request) { - v := new(createTagRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"tag": "t"}`) - }) - - tag, _, err := client.Git.CreateTag(context.Background(), "o", "r", &Tag{ - Tag: input.Tag, - Object: &GitObject{SHA: input.Object}, - }) - if err != nil { - t.Errorf("Git.CreateTag returned error: %v", err) - } - - want := &Tag{Tag: String("t")} - if !reflect.DeepEqual(tag, want) { - t.Errorf("Git.GetTag returned %+v, want %+v", tag, want) - } -} diff --git a/vendor/github.com/google/go-github/github/git_trees_test.go b/vendor/github.com/google/go-github/github/git_trees_test.go deleted file mode 100644 index 29728eee3819..000000000000 --- a/vendor/github.com/google/go-github/github/git_trees_test.go +++ /dev/null @@ -1,191 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestGitService_GetTree(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/git/trees/s", func(w http.ResponseWriter, r *http.Request) { - if m := "GET"; m != r.Method { - t.Errorf("Request method = %v, want %v", r.Method, m) - } - fmt.Fprint(w, `{ - "sha": "s", - "tree": [ { "type": "blob" } ] - }`) - }) - - tree, _, err := client.Git.GetTree(context.Background(), "o", "r", "s", true) - if err != nil { - t.Errorf("Git.GetTree returned error: %v", err) - } - - want := Tree{ - SHA: String("s"), - Entries: []TreeEntry{ - { - Type: String("blob"), - }, - }, - } - if !reflect.DeepEqual(*tree, want) { - t.Errorf("Tree.Get returned %+v, want %+v", *tree, want) - } -} - -func TestGitService_GetTree_invalidOwner(t *testing.T) { - _, _, err := client.Git.GetTree(context.Background(), "%", "%", "%", false) - testURLParseError(t, err) -} - -func TestGitService_CreateTree(t *testing.T) { - setup() - defer teardown() - - input := []TreeEntry{ - { - Path: String("file.rb"), - Mode: String("100644"), - Type: String("blob"), - SHA: String("7c258a9869f33c1e1e1f74fbb32f07c86cb5a75b"), - }, - } - - mux.HandleFunc("/repos/o/r/git/trees", func(w http.ResponseWriter, r *http.Request) { - v := new(createTree) - json.NewDecoder(r.Body).Decode(v) - - if m := "POST"; m != r.Method { - t.Errorf("Request method = %v, want %v", r.Method, m) - } - - want := &createTree{ - BaseTree: "b", - Entries: input, - } - if !reflect.DeepEqual(v, want) { - t.Errorf("Git.CreateTree request body: %+v, want %+v", v, want) - } - - fmt.Fprint(w, `{ - "sha": "cd8274d15fa3ae2ab983129fb037999f264ba9a7", - "tree": [ - { - "path": "file.rb", - "mode": "100644", - "type": "blob", - "size": 132, - "sha": "7c258a9869f33c1e1e1f74fbb32f07c86cb5a75b" - } - ] - }`) - }) - - tree, _, err := client.Git.CreateTree(context.Background(), "o", "r", "b", input) - if err != nil { - t.Errorf("Git.CreateTree returned error: %v", err) - } - - want := Tree{ - String("cd8274d15fa3ae2ab983129fb037999f264ba9a7"), - []TreeEntry{ - { - Path: String("file.rb"), - Mode: String("100644"), - Type: String("blob"), - Size: Int(132), - SHA: String("7c258a9869f33c1e1e1f74fbb32f07c86cb5a75b"), - }, - }, - } - - if !reflect.DeepEqual(*tree, want) { - t.Errorf("Git.CreateTree returned %+v, want %+v", *tree, want) - } -} - -func TestGitService_CreateTree_Content(t *testing.T) { - setup() - defer teardown() - - input := []TreeEntry{ - { - Path: String("content.md"), - Mode: String("100644"), - Content: String("file content"), - }, - } - - mux.HandleFunc("/repos/o/r/git/trees", func(w http.ResponseWriter, r *http.Request) { - v := new(createTree) - json.NewDecoder(r.Body).Decode(v) - - if m := "POST"; m != r.Method { - t.Errorf("Request method = %v, want %v", r.Method, m) - } - - want := &createTree{ - BaseTree: "b", - Entries: input, - } - if !reflect.DeepEqual(v, want) { - t.Errorf("Git.CreateTree request body: %+v, want %+v", v, want) - } - - fmt.Fprint(w, `{ - "sha": "5c6780ad2c68743383b740fd1dab6f6a33202b11", - "url": "https://api.github.com/repos/o/r/git/trees/5c6780ad2c68743383b740fd1dab6f6a33202b11", - "tree": [ - { - "mode": "100644", - "type": "blob", - "sha": "aad8feacf6f8063150476a7b2bd9770f2794c08b", - "path": "content.md", - "size": 12, - "url": "https://api.github.com/repos/o/r/git/blobs/aad8feacf6f8063150476a7b2bd9770f2794c08b" - } - ] - }`) - }) - - tree, _, err := client.Git.CreateTree(context.Background(), "o", "r", "b", input) - if err != nil { - t.Errorf("Git.CreateTree returned error: %v", err) - } - - want := Tree{ - String("5c6780ad2c68743383b740fd1dab6f6a33202b11"), - []TreeEntry{ - { - Path: String("content.md"), - Mode: String("100644"), - Type: String("blob"), - Size: Int(12), - SHA: String("aad8feacf6f8063150476a7b2bd9770f2794c08b"), - URL: String("https://api.github.com/repos/o/r/git/blobs/aad8feacf6f8063150476a7b2bd9770f2794c08b"), - }, - }, - } - - if !reflect.DeepEqual(*tree, want) { - t.Errorf("Git.CreateTree returned %+v, want %+v", *tree, want) - } -} - -func TestGitService_CreateTree_invalidOwner(t *testing.T) { - _, _, err := client.Git.CreateTree(context.Background(), "%", "%", "", nil) - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/github_test.go b/vendor/github.com/google/go-github/github/github_test.go deleted file mode 100644 index ed8ab1a2b8b1..000000000000 --- a/vendor/github.com/google/go-github/github/github_test.go +++ /dev/null @@ -1,913 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "net/url" - "os" - "path" - "reflect" - "strings" - "testing" - "time" -) - -var ( - // mux is the HTTP request multiplexer used with the test server. - mux *http.ServeMux - - // client is the GitHub client being tested. - client *Client - - // server is a test HTTP server used to provide mock API responses. - server *httptest.Server -) - -// setup sets up a test HTTP server along with a github.Client that is -// configured to talk to that test server. Tests should register handlers on -// mux which provide mock responses for the API method being tested. -func setup() { - // test server - mux = http.NewServeMux() - server = httptest.NewServer(mux) - - // github client configured to use test server - client = NewClient(nil) - url, _ := url.Parse(server.URL) - client.BaseURL = url - client.UploadURL = url -} - -// teardown closes the test HTTP server. -func teardown() { - server.Close() -} - -// openTestFile creates a new file with the given name and content for testing. -// In order to ensure the exact file name, this function will create a new temp -// directory, and create the file in that directory. It is the caller's -// responsibility to remove the directory and its contents when no longer needed. -func openTestFile(name, content string) (file *os.File, dir string, err error) { - dir, err = ioutil.TempDir("", "go-github") - if err != nil { - return nil, dir, err - } - - file, err = os.OpenFile(path.Join(dir, name), os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) - if err != nil { - return nil, dir, err - } - - fmt.Fprint(file, content) - - // close and re-open the file to keep file.Stat() happy - file.Close() - file, err = os.Open(file.Name()) - if err != nil { - return nil, dir, err - } - - return file, dir, err -} - -func testMethod(t *testing.T, r *http.Request, want string) { - if got := r.Method; got != want { - t.Errorf("Request method: %v, want %v", got, want) - } -} - -type values map[string]string - -func testFormValues(t *testing.T, r *http.Request, values values) { - want := url.Values{} - for k, v := range values { - want.Set(k, v) - } - - r.ParseForm() - if got := r.Form; !reflect.DeepEqual(got, want) { - t.Errorf("Request parameters: %v, want %v", got, want) - } -} - -func testHeader(t *testing.T, r *http.Request, header string, want string) { - if got := r.Header.Get(header); got != want { - t.Errorf("Header.Get(%q) returned %q, want %q", header, got, want) - } -} - -func testURLParseError(t *testing.T, err error) { - if err == nil { - t.Errorf("Expected error to be returned") - } - if err, ok := err.(*url.Error); !ok || err.Op != "parse" { - t.Errorf("Expected URL parse error, got %+v", err) - } -} - -func testBody(t *testing.T, r *http.Request, want string) { - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Errorf("Error reading request body: %v", err) - } - if got := string(b); got != want { - t.Errorf("request Body is %s, want %s", got, want) - } -} - -// Helper function to test that a value is marshalled to JSON as expected. -func testJSONMarshal(t *testing.T, v interface{}, want string) { - j, err := json.Marshal(v) - if err != nil { - t.Errorf("Unable to marshal JSON for %v", v) - } - - w := new(bytes.Buffer) - err = json.Compact(w, []byte(want)) - if err != nil { - t.Errorf("String is not valid json: %s", want) - } - - if w.String() != string(j) { - t.Errorf("json.Marshal(%q) returned %s, want %s", v, j, w) - } - - // now go the other direction and make sure things unmarshal as expected - u := reflect.ValueOf(v).Interface() - if err := json.Unmarshal([]byte(want), u); err != nil { - t.Errorf("Unable to unmarshal JSON for %v", want) - } - - if !reflect.DeepEqual(v, u) { - t.Errorf("json.Unmarshal(%q) returned %s, want %s", want, u, v) - } -} - -func TestNewClient(t *testing.T) { - c := NewClient(nil) - - if got, want := c.BaseURL.String(), defaultBaseURL; got != want { - t.Errorf("NewClient BaseURL is %v, want %v", got, want) - } - if got, want := c.UserAgent, userAgent; got != want { - t.Errorf("NewClient UserAgent is %v, want %v", got, want) - } -} - -// Ensure that length of Client.rateLimits is the same as number of fields in RateLimits struct. -func TestClient_rateLimits(t *testing.T) { - if got, want := len(Client{}.rateLimits), reflect.TypeOf(RateLimits{}).NumField(); got != want { - t.Errorf("len(Client{}.rateLimits) is %v, want %v", got, want) - } -} - -func TestNewRequest(t *testing.T) { - c := NewClient(nil) - - inURL, outURL := "/foo", defaultBaseURL+"foo" - inBody, outBody := &User{Login: String("l")}, `{"login":"l"}`+"\n" - req, _ := c.NewRequest("GET", inURL, inBody) - - // test that relative URL was expanded - if got, want := req.URL.String(), outURL; got != want { - t.Errorf("NewRequest(%q) URL is %v, want %v", inURL, got, want) - } - - // test that body was JSON encoded - body, _ := ioutil.ReadAll(req.Body) - if got, want := string(body), outBody; got != want { - t.Errorf("NewRequest(%q) Body is %v, want %v", inBody, got, want) - } - - // test that default user-agent is attached to the request - if got, want := req.Header.Get("User-Agent"), c.UserAgent; got != want { - t.Errorf("NewRequest() User-Agent is %v, want %v", got, want) - } -} - -func TestNewRequest_invalidJSON(t *testing.T) { - c := NewClient(nil) - - type T struct { - A map[interface{}]interface{} - } - _, err := c.NewRequest("GET", "/", &T{}) - - if err == nil { - t.Error("Expected error to be returned.") - } - if err, ok := err.(*json.UnsupportedTypeError); !ok { - t.Errorf("Expected a JSON error; got %#v.", err) - } -} - -func TestNewRequest_badURL(t *testing.T) { - c := NewClient(nil) - _, err := c.NewRequest("GET", ":", nil) - testURLParseError(t, err) -} - -// ensure that no User-Agent header is set if the client's UserAgent is empty. -// This caused a problem with Google's internal http client. -func TestNewRequest_emptyUserAgent(t *testing.T) { - c := NewClient(nil) - c.UserAgent = "" - req, err := c.NewRequest("GET", "/", nil) - if err != nil { - t.Fatalf("NewRequest returned unexpected error: %v", err) - } - if _, ok := req.Header["User-Agent"]; ok { - t.Fatal("constructed request contains unexpected User-Agent header") - } -} - -// If a nil body is passed to github.NewRequest, make sure that nil is also -// passed to http.NewRequest. In most cases, passing an io.Reader that returns -// no content is fine, since there is no difference between an HTTP request -// body that is an empty string versus one that is not set at all. However in -// certain cases, intermediate systems may treat these differently resulting in -// subtle errors. -func TestNewRequest_emptyBody(t *testing.T) { - c := NewClient(nil) - req, err := c.NewRequest("GET", "/", nil) - if err != nil { - t.Fatalf("NewRequest returned unexpected error: %v", err) - } - if req.Body != nil { - t.Fatalf("constructed request contains a non-nil Body") - } -} - -func TestResponse_populatePageValues(t *testing.T) { - r := http.Response{ - Header: http.Header{ - "Link": {`; rel="first",` + - ` ; rel="prev",` + - ` ; rel="next",` + - ` ; rel="last"`, - }, - }, - } - - response := newResponse(&r) - if got, want := response.FirstPage, 1; got != want { - t.Errorf("response.FirstPage: %v, want %v", got, want) - } - if got, want := response.PrevPage, 2; want != got { - t.Errorf("response.PrevPage: %v, want %v", got, want) - } - if got, want := response.NextPage, 4; want != got { - t.Errorf("response.NextPage: %v, want %v", got, want) - } - if got, want := response.LastPage, 5; want != got { - t.Errorf("response.LastPage: %v, want %v", got, want) - } -} - -func TestResponse_populatePageValues_invalid(t *testing.T) { - r := http.Response{ - Header: http.Header{ - "Link": {`,` + - `; rel="first",` + - `https://api.github.com/?page=2; rel="prev",` + - `; rel="next",` + - `; rel="last"`, - }, - }, - } - - response := newResponse(&r) - if got, want := response.FirstPage, 0; got != want { - t.Errorf("response.FirstPage: %v, want %v", got, want) - } - if got, want := response.PrevPage, 0; got != want { - t.Errorf("response.PrevPage: %v, want %v", got, want) - } - if got, want := response.NextPage, 0; got != want { - t.Errorf("response.NextPage: %v, want %v", got, want) - } - if got, want := response.LastPage, 0; got != want { - t.Errorf("response.LastPage: %v, want %v", got, want) - } - - // more invalid URLs - r = http.Response{ - Header: http.Header{ - "Link": {`; rel="first"`}, - }, - } - - response = newResponse(&r) - if got, want := response.FirstPage, 0; got != want { - t.Errorf("response.FirstPage: %v, want %v", got, want) - } -} - -func TestDo(t *testing.T) { - setup() - defer teardown() - - type foo struct { - A string - } - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - if m := "GET"; m != r.Method { - t.Errorf("Request method = %v, want %v", r.Method, m) - } - fmt.Fprint(w, `{"A":"a"}`) - }) - - req, _ := client.NewRequest("GET", "/", nil) - body := new(foo) - client.Do(context.Background(), req, body) - - want := &foo{"a"} - if !reflect.DeepEqual(body, want) { - t.Errorf("Response body = %v, want %v", body, want) - } -} - -func TestDo_httpError(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - http.Error(w, "Bad Request", 400) - }) - - req, _ := client.NewRequest("GET", "/", nil) - _, err := client.Do(context.Background(), req, nil) - - if err == nil { - t.Error("Expected HTTP 400 error.") - } -} - -// Test handling of an error caused by the internal http client's Do() -// function. A redirect loop is pretty unlikely to occur within the GitHub -// API, but does allow us to exercise the right code path. -func TestDo_redirectLoop(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - http.Redirect(w, r, "/", http.StatusFound) - }) - - req, _ := client.NewRequest("GET", "/", nil) - _, err := client.Do(context.Background(), req, nil) - - if err == nil { - t.Error("Expected error to be returned.") - } - if err, ok := err.(*url.Error); !ok { - t.Errorf("Expected a URL error; got %#v.", err) - } -} - -// Test that an error caused by the internal http client's Do() function -// does not leak the client secret. -func TestDo_sanitizeURL(t *testing.T) { - tp := &UnauthenticatedRateLimitedTransport{ - ClientID: "id", - ClientSecret: "secret", - } - unauthedClient := NewClient(tp.Client()) - unauthedClient.BaseURL = &url.URL{Scheme: "http", Host: "127.0.0.1:0", Path: "/"} // Use port 0 on purpose to trigger a dial TCP error, expect to get "dial tcp 127.0.0.1:0: connect: can't assign requested address". - req, err := unauthedClient.NewRequest("GET", "/", nil) - if err != nil { - t.Fatalf("NewRequest returned unexpected error: %v", err) - } - _, err = unauthedClient.Do(context.Background(), req, nil) - if err == nil { - t.Fatal("Expected error to be returned.") - } - if strings.Contains(err.Error(), "client_secret=secret") { - t.Errorf("Do error contains secret, should be redacted:\n%q", err) - } -} - -func TestDo_rateLimit(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set(headerRateLimit, "60") - w.Header().Set(headerRateRemaining, "59") - w.Header().Set(headerRateReset, "1372700873") - }) - - req, _ := client.NewRequest("GET", "/", nil) - resp, err := client.Do(context.Background(), req, nil) - if err != nil { - t.Errorf("Do returned unexpected error: %v", err) - } - if got, want := resp.Rate.Limit, 60; got != want { - t.Errorf("Client rate limit = %v, want %v", got, want) - } - if got, want := resp.Rate.Remaining, 59; got != want { - t.Errorf("Client rate remaining = %v, want %v", got, want) - } - reset := time.Date(2013, 7, 1, 17, 47, 53, 0, time.UTC) - if resp.Rate.Reset.UTC() != reset { - t.Errorf("Client rate reset = %v, want %v", resp.Rate.Reset, reset) - } -} - -// ensure rate limit is still parsed, even for error responses -func TestDo_rateLimit_errorResponse(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set(headerRateLimit, "60") - w.Header().Set(headerRateRemaining, "59") - w.Header().Set(headerRateReset, "1372700873") - http.Error(w, "Bad Request", 400) - }) - - req, _ := client.NewRequest("GET", "/", nil) - resp, err := client.Do(context.Background(), req, nil) - if err == nil { - t.Error("Expected error to be returned.") - } - if _, ok := err.(*RateLimitError); ok { - t.Errorf("Did not expect a *RateLimitError error; got %#v.", err) - } - if got, want := resp.Rate.Limit, 60; got != want { - t.Errorf("Client rate limit = %v, want %v", got, want) - } - if got, want := resp.Rate.Remaining, 59; got != want { - t.Errorf("Client rate remaining = %v, want %v", got, want) - } - reset := time.Date(2013, 7, 1, 17, 47, 53, 0, time.UTC) - if resp.Rate.Reset.UTC() != reset { - t.Errorf("Client rate reset = %v, want %v", resp.Rate.Reset, reset) - } -} - -// Ensure *RateLimitError is returned when API rate limit is exceeded. -func TestDo_rateLimit_rateLimitError(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set(headerRateLimit, "60") - w.Header().Set(headerRateRemaining, "0") - w.Header().Set(headerRateReset, "1372700873") - w.Header().Set("Content-Type", "application/json; charset=utf-8") - w.WriteHeader(http.StatusForbidden) - fmt.Fprintln(w, `{ - "message": "API rate limit exceeded for xxx.xxx.xxx.xxx. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)", - "documentation_url": "https://developer.github.com/v3/#rate-limiting" -}`) - }) - - req, _ := client.NewRequest("GET", "/", nil) - _, err := client.Do(context.Background(), req, nil) - - if err == nil { - t.Error("Expected error to be returned.") - } - rateLimitErr, ok := err.(*RateLimitError) - if !ok { - t.Fatalf("Expected a *RateLimitError error; got %#v.", err) - } - if got, want := rateLimitErr.Rate.Limit, 60; got != want { - t.Errorf("rateLimitErr rate limit = %v, want %v", got, want) - } - if got, want := rateLimitErr.Rate.Remaining, 0; got != want { - t.Errorf("rateLimitErr rate remaining = %v, want %v", got, want) - } - reset := time.Date(2013, 7, 1, 17, 47, 53, 0, time.UTC) - if rateLimitErr.Rate.Reset.UTC() != reset { - t.Errorf("rateLimitErr rate reset = %v, want %v", rateLimitErr.Rate.Reset.UTC(), reset) - } -} - -// Ensure a network call is not made when it's known that API rate limit is still exceeded. -func TestDo_rateLimit_noNetworkCall(t *testing.T) { - setup() - defer teardown() - - reset := time.Now().UTC().Add(time.Minute).Round(time.Second) // Rate reset is a minute from now, with 1 second precision. - - mux.HandleFunc("/first", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set(headerRateLimit, "60") - w.Header().Set(headerRateRemaining, "0") - w.Header().Set(headerRateReset, fmt.Sprint(reset.Unix())) - w.Header().Set("Content-Type", "application/json; charset=utf-8") - w.WriteHeader(http.StatusForbidden) - fmt.Fprintln(w, `{ - "message": "API rate limit exceeded for xxx.xxx.xxx.xxx. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)", - "documentation_url": "https://developer.github.com/v3/#rate-limiting" -}`) - }) - - madeNetworkCall := false - mux.HandleFunc("/second", func(w http.ResponseWriter, r *http.Request) { - madeNetworkCall = true - }) - - // First request is made, and it makes the client aware of rate reset time being in the future. - req, _ := client.NewRequest("GET", "/first", nil) - client.Do(context.Background(), req, nil) - - // Second request should not cause a network call to be made, since client can predict a rate limit error. - req, _ = client.NewRequest("GET", "/second", nil) - _, err := client.Do(context.Background(), req, nil) - - if madeNetworkCall { - t.Fatal("Network call was made, even though rate limit is known to still be exceeded.") - } - - if err == nil { - t.Error("Expected error to be returned.") - } - rateLimitErr, ok := err.(*RateLimitError) - if !ok { - t.Fatalf("Expected a *RateLimitError error; got %#v.", err) - } - if got, want := rateLimitErr.Rate.Limit, 60; got != want { - t.Errorf("rateLimitErr rate limit = %v, want %v", got, want) - } - if got, want := rateLimitErr.Rate.Remaining, 0; got != want { - t.Errorf("rateLimitErr rate remaining = %v, want %v", got, want) - } - if rateLimitErr.Rate.Reset.UTC() != reset { - t.Errorf("rateLimitErr rate reset = %v, want %v", rateLimitErr.Rate.Reset.UTC(), reset) - } -} - -// Ensure *AbuseRateLimitError is returned when the response indicates that -// the client has triggered an abuse detection mechanism. -func TestDo_rateLimit_abuseRateLimitError(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json; charset=utf-8") - w.WriteHeader(http.StatusForbidden) - // When the abuse rate limit error is of the "temporarily blocked from content creation" type, - // there is no "Retry-After" header. - fmt.Fprintln(w, `{ - "message": "You have triggered an abuse detection mechanism and have been temporarily blocked from content creation. Please retry your request again later.", - "documentation_url": "https://developer.github.com/v3#abuse-rate-limits" -}`) - }) - - req, _ := client.NewRequest("GET", "/", nil) - _, err := client.Do(context.Background(), req, nil) - - if err == nil { - t.Error("Expected error to be returned.") - } - abuseRateLimitErr, ok := err.(*AbuseRateLimitError) - if !ok { - t.Fatalf("Expected a *AbuseRateLimitError error; got %#v.", err) - } - if got, want := abuseRateLimitErr.RetryAfter, (*time.Duration)(nil); got != want { - t.Errorf("abuseRateLimitErr RetryAfter = %v, want %v", got, want) - } -} - -// Ensure *AbuseRateLimitError.RetryAfter is parsed correctly. -func TestDo_rateLimit_abuseRateLimitError_retryAfter(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json; charset=utf-8") - w.Header().Set("Retry-After", "123") // Retry after value of 123 seconds. - w.WriteHeader(http.StatusForbidden) - fmt.Fprintln(w, `{ - "message": "You have triggered an abuse detection mechanism ...", - "documentation_url": "https://developer.github.com/v3#abuse-rate-limits" -}`) - }) - - req, _ := client.NewRequest("GET", "/", nil) - _, err := client.Do(context.Background(), req, nil) - - if err == nil { - t.Error("Expected error to be returned.") - } - abuseRateLimitErr, ok := err.(*AbuseRateLimitError) - if !ok { - t.Fatalf("Expected a *AbuseRateLimitError error; got %#v.", err) - } - if abuseRateLimitErr.RetryAfter == nil { - t.Fatalf("abuseRateLimitErr RetryAfter is nil, expected not-nil") - } - if got, want := *abuseRateLimitErr.RetryAfter, 123*time.Second; got != want { - t.Errorf("abuseRateLimitErr RetryAfter = %v, want %v", got, want) - } -} - -func TestDo_noContent(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNoContent) - }) - - var body json.RawMessage - - req, _ := client.NewRequest("GET", "/", nil) - _, err := client.Do(context.Background(), req, &body) - if err != nil { - t.Fatalf("Do returned unexpected error: %v", err) - } -} - -func TestSanitizeURL(t *testing.T) { - tests := []struct { - in, want string - }{ - {"/?a=b", "/?a=b"}, - {"/?a=b&client_secret=secret", "/?a=b&client_secret=REDACTED"}, - {"/?a=b&client_id=id&client_secret=secret", "/?a=b&client_id=id&client_secret=REDACTED"}, - } - - for _, tt := range tests { - inURL, _ := url.Parse(tt.in) - want, _ := url.Parse(tt.want) - - if got := sanitizeURL(inURL); !reflect.DeepEqual(got, want) { - t.Errorf("sanitizeURL(%v) returned %v, want %v", tt.in, got, want) - } - } -} - -func TestCheckResponse(t *testing.T) { - res := &http.Response{ - Request: &http.Request{}, - StatusCode: http.StatusBadRequest, - Body: ioutil.NopCloser(strings.NewReader(`{"message":"m", - "errors": [{"resource": "r", "field": "f", "code": "c"}], - "block": {"reason": "dmca", "created_at": "2016-03-17T15:39:46Z"}}`)), - } - err := CheckResponse(res).(*ErrorResponse) - - if err == nil { - t.Errorf("Expected error response.") - } - - want := &ErrorResponse{ - Response: res, - Message: "m", - Errors: []Error{{Resource: "r", Field: "f", Code: "c"}}, - Block: &struct { - Reason string `json:"reason,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - }{ - Reason: "dmca", - CreatedAt: &Timestamp{time.Date(2016, 3, 17, 15, 39, 46, 0, time.UTC)}, - }, - } - if !reflect.DeepEqual(err, want) { - t.Errorf("Error = %#v, want %#v", err, want) - } -} - -// ensure that we properly handle API errors that do not contain a response body -func TestCheckResponse_noBody(t *testing.T) { - res := &http.Response{ - Request: &http.Request{}, - StatusCode: http.StatusBadRequest, - Body: ioutil.NopCloser(strings.NewReader("")), - } - err := CheckResponse(res).(*ErrorResponse) - - if err == nil { - t.Errorf("Expected error response.") - } - - want := &ErrorResponse{ - Response: res, - } - if !reflect.DeepEqual(err, want) { - t.Errorf("Error = %#v, want %#v", err, want) - } -} - -func TestParseBooleanResponse_true(t *testing.T) { - result, err := parseBoolResponse(nil) - if err != nil { - t.Errorf("parseBoolResponse returned error: %+v", err) - } - - if want := true; result != want { - t.Errorf("parseBoolResponse returned %+v, want: %+v", result, want) - } -} - -func TestParseBooleanResponse_false(t *testing.T) { - v := &ErrorResponse{Response: &http.Response{StatusCode: http.StatusNotFound}} - result, err := parseBoolResponse(v) - if err != nil { - t.Errorf("parseBoolResponse returned error: %+v", err) - } - - if want := false; result != want { - t.Errorf("parseBoolResponse returned %+v, want: %+v", result, want) - } -} - -func TestParseBooleanResponse_error(t *testing.T) { - v := &ErrorResponse{Response: &http.Response{StatusCode: http.StatusBadRequest}} - result, err := parseBoolResponse(v) - - if err == nil { - t.Errorf("Expected error to be returned.") - } - - if want := false; result != want { - t.Errorf("parseBoolResponse returned %+v, want: %+v", result, want) - } -} - -func TestErrorResponse_Error(t *testing.T) { - res := &http.Response{Request: &http.Request{}} - err := ErrorResponse{Message: "m", Response: res} - if err.Error() == "" { - t.Errorf("Expected non-empty ErrorResponse.Error()") - } -} - -func TestError_Error(t *testing.T) { - err := Error{} - if err.Error() == "" { - t.Errorf("Expected non-empty Error.Error()") - } -} - -func TestRateLimits(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/rate_limit", func(w http.ResponseWriter, r *http.Request) { - if m := "GET"; m != r.Method { - t.Errorf("Request method = %v, want %v", r.Method, m) - } - fmt.Fprint(w, `{"resources":{ - "core": {"limit":2,"remaining":1,"reset":1372700873}, - "search": {"limit":3,"remaining":2,"reset":1372700874} - }}`) - }) - - rate, _, err := client.RateLimits(context.Background()) - if err != nil { - t.Errorf("RateLimits returned error: %v", err) - } - - want := &RateLimits{ - Core: &Rate{ - Limit: 2, - Remaining: 1, - Reset: Timestamp{time.Date(2013, 7, 1, 17, 47, 53, 0, time.UTC).Local()}, - }, - Search: &Rate{ - Limit: 3, - Remaining: 2, - Reset: Timestamp{time.Date(2013, 7, 1, 17, 47, 54, 0, time.UTC).Local()}, - }, - } - if !reflect.DeepEqual(rate, want) { - t.Errorf("RateLimits returned %+v, want %+v", rate, want) - } - - if got, want := client.rateLimits[coreCategory], *want.Core; got != want { - t.Errorf("client.rateLimits[coreCategory] is %+v, want %+v", got, want) - } - if got, want := client.rateLimits[searchCategory], *want.Search; got != want { - t.Errorf("client.rateLimits[searchCategory] is %+v, want %+v", got, want) - } -} - -func TestUnauthenticatedRateLimitedTransport(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - var v, want string - q := r.URL.Query() - if v, want = q.Get("client_id"), "id"; v != want { - t.Errorf("OAuth Client ID = %v, want %v", v, want) - } - if v, want = q.Get("client_secret"), "secret"; v != want { - t.Errorf("OAuth Client Secret = %v, want %v", v, want) - } - }) - - tp := &UnauthenticatedRateLimitedTransport{ - ClientID: "id", - ClientSecret: "secret", - } - unauthedClient := NewClient(tp.Client()) - unauthedClient.BaseURL = client.BaseURL - req, _ := unauthedClient.NewRequest("GET", "/", nil) - unauthedClient.Do(context.Background(), req, nil) -} - -func TestUnauthenticatedRateLimitedTransport_missingFields(t *testing.T) { - // missing ClientID - tp := &UnauthenticatedRateLimitedTransport{ - ClientSecret: "secret", - } - _, err := tp.RoundTrip(nil) - if err == nil { - t.Errorf("Expected error to be returned") - } - - // missing ClientSecret - tp = &UnauthenticatedRateLimitedTransport{ - ClientID: "id", - } - _, err = tp.RoundTrip(nil) - if err == nil { - t.Errorf("Expected error to be returned") - } -} - -func TestUnauthenticatedRateLimitedTransport_transport(t *testing.T) { - // default transport - tp := &UnauthenticatedRateLimitedTransport{ - ClientID: "id", - ClientSecret: "secret", - } - if tp.transport() != http.DefaultTransport { - t.Errorf("Expected http.DefaultTransport to be used.") - } - - // custom transport - tp = &UnauthenticatedRateLimitedTransport{ - ClientID: "id", - ClientSecret: "secret", - Transport: &http.Transport{}, - } - if tp.transport() == http.DefaultTransport { - t.Errorf("Expected custom transport to be used.") - } -} - -func TestBasicAuthTransport(t *testing.T) { - setup() - defer teardown() - - username, password, otp := "u", "p", "123456" - - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - u, p, ok := r.BasicAuth() - if !ok { - t.Errorf("request does not contain basic auth credentials") - } - if u != username { - t.Errorf("request contained basic auth username %q, want %q", u, username) - } - if p != password { - t.Errorf("request contained basic auth password %q, want %q", p, password) - } - if got, want := r.Header.Get(headerOTP), otp; got != want { - t.Errorf("request contained OTP %q, want %q", got, want) - } - }) - - tp := &BasicAuthTransport{ - Username: username, - Password: password, - OTP: otp, - } - basicAuthClient := NewClient(tp.Client()) - basicAuthClient.BaseURL = client.BaseURL - req, _ := basicAuthClient.NewRequest("GET", "/", nil) - basicAuthClient.Do(context.Background(), req, nil) -} - -func TestBasicAuthTransport_transport(t *testing.T) { - // default transport - tp := &BasicAuthTransport{} - if tp.transport() != http.DefaultTransport { - t.Errorf("Expected http.DefaultTransport to be used.") - } - - // custom transport - tp = &BasicAuthTransport{ - Transport: &http.Transport{}, - } - if tp.transport() == http.DefaultTransport { - t.Errorf("Expected custom transport to be used.") - } -} diff --git a/vendor/github.com/google/go-github/github/gitignore_test.go b/vendor/github.com/google/go-github/github/gitignore_test.go deleted file mode 100644 index e5a62643b5df..000000000000 --- a/vendor/github.com/google/go-github/github/gitignore_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestGitignoresService_List(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gitignore/templates", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `["C", "Go"]`) - }) - - available, _, err := client.Gitignores.List(context.Background()) - if err != nil { - t.Errorf("Gitignores.List returned error: %v", err) - } - - want := []string{"C", "Go"} - if !reflect.DeepEqual(available, want) { - t.Errorf("Gitignores.List returned %+v, want %+v", available, want) - } -} - -func TestGitignoresService_Get(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/gitignore/templates/name", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"name":"Name","source":"template source"}`) - }) - - gitignore, _, err := client.Gitignores.Get(context.Background(), "name") - if err != nil { - t.Errorf("Gitignores.List returned error: %v", err) - } - - want := &Gitignore{Name: String("Name"), Source: String("template source")} - if !reflect.DeepEqual(gitignore, want) { - t.Errorf("Gitignores.Get returned %+v, want %+v", gitignore, want) - } -} - -func TestGitignoresService_Get_invalidTemplate(t *testing.T) { - _, _, err := client.Gitignores.Get(context.Background(), "%") - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/issues_assignees_test.go b/vendor/github.com/google/go-github/github/issues_assignees_test.go deleted file mode 100644 index d88a7888a4e2..000000000000 --- a/vendor/github.com/google/go-github/github/issues_assignees_test.go +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestIssuesService_ListAssignees(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/assignees", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - assignees, _, err := client.Issues.ListAssignees(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Issues.ListAssignees returned error: %v", err) - } - - want := []*User{{ID: Int(1)}} - if !reflect.DeepEqual(assignees, want) { - t.Errorf("Issues.ListAssignees returned %+v, want %+v", assignees, want) - } -} - -func TestIssuesService_ListAssignees_invalidOwner(t *testing.T) { - _, _, err := client.Issues.ListAssignees(context.Background(), "%", "r", nil) - testURLParseError(t, err) -} - -func TestIssuesService_IsAssignee_true(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/assignees/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - }) - - assignee, _, err := client.Issues.IsAssignee(context.Background(), "o", "r", "u") - if err != nil { - t.Errorf("Issues.IsAssignee returned error: %v", err) - } - if want := true; assignee != want { - t.Errorf("Issues.IsAssignee returned %+v, want %+v", assignee, want) - } -} - -func TestIssuesService_IsAssignee_false(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/assignees/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - assignee, _, err := client.Issues.IsAssignee(context.Background(), "o", "r", "u") - if err != nil { - t.Errorf("Issues.IsAssignee returned error: %v", err) - } - if want := false; assignee != want { - t.Errorf("Issues.IsAssignee returned %+v, want %+v", assignee, want) - } -} - -func TestIssuesService_IsAssignee_error(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/assignees/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - http.Error(w, "BadRequest", http.StatusBadRequest) - }) - - assignee, _, err := client.Issues.IsAssignee(context.Background(), "o", "r", "u") - if err == nil { - t.Errorf("Expected HTTP 400 response") - } - if want := false; assignee != want { - t.Errorf("Issues.IsAssignee returned %+v, want %+v", assignee, want) - } -} - -func TestIssuesService_IsAssignee_invalidOwner(t *testing.T) { - _, _, err := client.Issues.IsAssignee(context.Background(), "%", "r", "u") - testURLParseError(t, err) -} - -func TestIssuesService_AddAssignees(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/1/assignees", func(w http.ResponseWriter, r *http.Request) { - var assignees struct { - Assignees []string `json:"assignees,omitempty"` - } - json.NewDecoder(r.Body).Decode(&assignees) - - testMethod(t, r, "POST") - want := []string{"user1", "user2"} - if !reflect.DeepEqual(assignees.Assignees, want) { - t.Errorf("assignees = %+v, want %+v", assignees, want) - } - fmt.Fprint(w, `{"number":1,"assignees":[{"login":"user1"},{"login":"user2"}]}`) - }) - - got, _, err := client.Issues.AddAssignees(context.Background(), "o", "r", 1, []string{"user1", "user2"}) - if err != nil { - t.Errorf("Issues.AddAssignees returned error: %v", err) - } - - want := &Issue{Number: Int(1), Assignees: []*User{{Login: String("user1")}, {Login: String("user2")}}} - if !reflect.DeepEqual(got, want) { - t.Errorf("Issues.AddAssignees = %+v, want %+v", got, want) - } -} - -func TestIssuesService_RemoveAssignees(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/1/assignees", func(w http.ResponseWriter, r *http.Request) { - var assignees struct { - Assignees []string `json:"assignees,omitempty"` - } - json.NewDecoder(r.Body).Decode(&assignees) - - testMethod(t, r, "DELETE") - want := []string{"user1", "user2"} - if !reflect.DeepEqual(assignees.Assignees, want) { - t.Errorf("assignees = %+v, want %+v", assignees, want) - } - fmt.Fprint(w, `{"number":1,"assignees":[]}`) - }) - - got, _, err := client.Issues.RemoveAssignees(context.Background(), "o", "r", 1, []string{"user1", "user2"}) - if err != nil { - t.Errorf("Issues.RemoveAssignees returned error: %v", err) - } - - want := &Issue{Number: Int(1), Assignees: []*User{}} - if !reflect.DeepEqual(got, want) { - t.Errorf("Issues.RemoveAssignees = %+v, want %+v", got, want) - } -} diff --git a/vendor/github.com/google/go-github/github/issues_comments_test.go b/vendor/github.com/google/go-github/github/issues_comments_test.go deleted file mode 100644 index 78c486362f43..000000000000 --- a/vendor/github.com/google/go-github/github/issues_comments_test.go +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestIssuesService_ListComments_allIssues(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/comments", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - testFormValues(t, r, values{ - "sort": "updated", - "direction": "desc", - "since": "2002-02-10T15:30:00Z", - "page": "2", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &IssueListCommentsOptions{ - Sort: "updated", - Direction: "desc", - Since: time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC), - ListOptions: ListOptions{Page: 2}, - } - comments, _, err := client.Issues.ListComments(context.Background(), "o", "r", 0, opt) - if err != nil { - t.Errorf("Issues.ListComments returned error: %v", err) - } - - want := []*IssueComment{{ID: Int(1)}} - if !reflect.DeepEqual(comments, want) { - t.Errorf("Issues.ListComments returned %+v, want %+v", comments, want) - } -} - -func TestIssuesService_ListComments_specificIssue(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/1/comments", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - fmt.Fprint(w, `[{"id":1}]`) - }) - - comments, _, err := client.Issues.ListComments(context.Background(), "o", "r", 1, nil) - if err != nil { - t.Errorf("Issues.ListComments returned error: %v", err) - } - - want := []*IssueComment{{ID: Int(1)}} - if !reflect.DeepEqual(comments, want) { - t.Errorf("Issues.ListComments returned %+v, want %+v", comments, want) - } -} - -func TestIssuesService_ListComments_invalidOwner(t *testing.T) { - _, _, err := client.Issues.ListComments(context.Background(), "%", "r", 1, nil) - testURLParseError(t, err) -} - -func TestIssuesService_GetComment(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/comments/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.Issues.GetComment(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Issues.GetComment returned error: %v", err) - } - - want := &IssueComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("Issues.GetComment returned %+v, want %+v", comment, want) - } -} - -func TestIssuesService_GetComment_invalidOrg(t *testing.T) { - _, _, err := client.Issues.GetComment(context.Background(), "%", "r", 1) - testURLParseError(t, err) -} - -func TestIssuesService_CreateComment(t *testing.T) { - setup() - defer teardown() - - input := &IssueComment{Body: String("b")} - - mux.HandleFunc("/repos/o/r/issues/1/comments", func(w http.ResponseWriter, r *http.Request) { - v := new(IssueComment) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.Issues.CreateComment(context.Background(), "o", "r", 1, input) - if err != nil { - t.Errorf("Issues.CreateComment returned error: %v", err) - } - - want := &IssueComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("Issues.CreateComment returned %+v, want %+v", comment, want) - } -} - -func TestIssuesService_CreateComment_invalidOrg(t *testing.T) { - _, _, err := client.Issues.CreateComment(context.Background(), "%", "r", 1, nil) - testURLParseError(t, err) -} - -func TestIssuesService_EditComment(t *testing.T) { - setup() - defer teardown() - - input := &IssueComment{Body: String("b")} - - mux.HandleFunc("/repos/o/r/issues/comments/1", func(w http.ResponseWriter, r *http.Request) { - v := new(IssueComment) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.Issues.EditComment(context.Background(), "o", "r", 1, input) - if err != nil { - t.Errorf("Issues.EditComment returned error: %v", err) - } - - want := &IssueComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("Issues.EditComment returned %+v, want %+v", comment, want) - } -} - -func TestIssuesService_EditComment_invalidOwner(t *testing.T) { - _, _, err := client.Issues.EditComment(context.Background(), "%", "r", 1, nil) - testURLParseError(t, err) -} - -func TestIssuesService_DeleteComment(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/comments/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Issues.DeleteComment(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Issues.DeleteComments returned error: %v", err) - } -} - -func TestIssuesService_DeleteComment_invalidOwner(t *testing.T) { - _, err := client.Issues.DeleteComment(context.Background(), "%", "r", 1) - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/issues_events_test.go b/vendor/github.com/google/go-github/github/issues_events_test.go deleted file mode 100644 index d85b6223eaa1..000000000000 --- a/vendor/github.com/google/go-github/github/issues_events_test.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestIssuesService_ListIssueEvents(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/1/events", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "1", - "per_page": "2", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 1, PerPage: 2} - events, _, err := client.Issues.ListIssueEvents(context.Background(), "o", "r", 1, opt) - if err != nil { - t.Errorf("Issues.ListIssueEvents returned error: %v", err) - } - - want := []*IssueEvent{{ID: Int(1)}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Issues.ListIssueEvents returned %+v, want %+v", events, want) - } -} - -func TestIssuesService_ListRepositoryEvents(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/events", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "1", - "per_page": "2", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 1, PerPage: 2} - events, _, err := client.Issues.ListRepositoryEvents(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Issues.ListRepositoryEvents returned error: %v", err) - } - - want := []*IssueEvent{{ID: Int(1)}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Issues.ListRepositoryEvents returned %+v, want %+v", events, want) - } -} - -func TestIssuesService_GetEvent(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/events/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - event, _, err := client.Issues.GetEvent(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Issues.GetEvent returned error: %v", err) - } - - want := &IssueEvent{ID: Int(1)} - if !reflect.DeepEqual(event, want) { - t.Errorf("Issues.GetEvent returned %+v, want %+v", event, want) - } -} diff --git a/vendor/github.com/google/go-github/github/issues_labels_test.go b/vendor/github.com/google/go-github/github/issues_labels_test.go deleted file mode 100644 index 5380427a1e61..000000000000 --- a/vendor/github.com/google/go-github/github/issues_labels_test.go +++ /dev/null @@ -1,317 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestIssuesService_ListLabels(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/labels", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"name": "a"},{"name": "b"}]`) - }) - - opt := &ListOptions{Page: 2} - labels, _, err := client.Issues.ListLabels(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Issues.ListLabels returned error: %v", err) - } - - want := []*Label{{Name: String("a")}, {Name: String("b")}} - if !reflect.DeepEqual(labels, want) { - t.Errorf("Issues.ListLabels returned %+v, want %+v", labels, want) - } -} - -func TestIssuesService_ListLabels_invalidOwner(t *testing.T) { - _, _, err := client.Issues.ListLabels(context.Background(), "%", "%", nil) - testURLParseError(t, err) -} - -func TestIssuesService_GetLabel(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/labels/n", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"url":"u", "name": "n", "color": "c"}`) - }) - - label, _, err := client.Issues.GetLabel(context.Background(), "o", "r", "n") - if err != nil { - t.Errorf("Issues.GetLabel returned error: %v", err) - } - - want := &Label{URL: String("u"), Name: String("n"), Color: String("c")} - if !reflect.DeepEqual(label, want) { - t.Errorf("Issues.GetLabel returned %+v, want %+v", label, want) - } -} - -func TestIssuesService_GetLabel_invalidOwner(t *testing.T) { - _, _, err := client.Issues.GetLabel(context.Background(), "%", "%", "%") - testURLParseError(t, err) -} - -func TestIssuesService_CreateLabel(t *testing.T) { - setup() - defer teardown() - - input := &Label{Name: String("n")} - - mux.HandleFunc("/repos/o/r/labels", func(w http.ResponseWriter, r *http.Request) { - v := new(Label) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"url":"u"}`) - }) - - label, _, err := client.Issues.CreateLabel(context.Background(), "o", "r", input) - if err != nil { - t.Errorf("Issues.CreateLabel returned error: %v", err) - } - - want := &Label{URL: String("u")} - if !reflect.DeepEqual(label, want) { - t.Errorf("Issues.CreateLabel returned %+v, want %+v", label, want) - } -} - -func TestIssuesService_CreateLabel_invalidOwner(t *testing.T) { - _, _, err := client.Issues.CreateLabel(context.Background(), "%", "%", nil) - testURLParseError(t, err) -} - -func TestIssuesService_EditLabel(t *testing.T) { - setup() - defer teardown() - - input := &Label{Name: String("z")} - - mux.HandleFunc("/repos/o/r/labels/n", func(w http.ResponseWriter, r *http.Request) { - v := new(Label) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"url":"u"}`) - }) - - label, _, err := client.Issues.EditLabel(context.Background(), "o", "r", "n", input) - if err != nil { - t.Errorf("Issues.EditLabel returned error: %v", err) - } - - want := &Label{URL: String("u")} - if !reflect.DeepEqual(label, want) { - t.Errorf("Issues.EditLabel returned %+v, want %+v", label, want) - } -} - -func TestIssuesService_EditLabel_invalidOwner(t *testing.T) { - _, _, err := client.Issues.EditLabel(context.Background(), "%", "%", "%", nil) - testURLParseError(t, err) -} - -func TestIssuesService_DeleteLabel(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/labels/n", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Issues.DeleteLabel(context.Background(), "o", "r", "n") - if err != nil { - t.Errorf("Issues.DeleteLabel returned error: %v", err) - } -} - -func TestIssuesService_DeleteLabel_invalidOwner(t *testing.T) { - _, err := client.Issues.DeleteLabel(context.Background(), "%", "%", "%") - testURLParseError(t, err) -} - -func TestIssuesService_ListLabelsByIssue(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/1/labels", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"name":"a","id":1},{"name":"b","id":2}]`) - }) - - opt := &ListOptions{Page: 2} - labels, _, err := client.Issues.ListLabelsByIssue(context.Background(), "o", "r", 1, opt) - if err != nil { - t.Errorf("Issues.ListLabelsByIssue returned error: %v", err) - } - - want := []*Label{ - {Name: String("a"), ID: Int(1)}, - {Name: String("b"), ID: Int(2)}, - } - if !reflect.DeepEqual(labels, want) { - t.Errorf("Issues.ListLabelsByIssue returned %+v, want %+v", labels, want) - } -} - -func TestIssuesService_ListLabelsByIssue_invalidOwner(t *testing.T) { - _, _, err := client.Issues.ListLabelsByIssue(context.Background(), "%", "%", 1, nil) - testURLParseError(t, err) -} - -func TestIssuesService_AddLabelsToIssue(t *testing.T) { - setup() - defer teardown() - - input := []string{"a", "b"} - - mux.HandleFunc("/repos/o/r/issues/1/labels", func(w http.ResponseWriter, r *http.Request) { - var v []string - json.NewDecoder(r.Body).Decode(&v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `[{"url":"u"}]`) - }) - - labels, _, err := client.Issues.AddLabelsToIssue(context.Background(), "o", "r", 1, input) - if err != nil { - t.Errorf("Issues.AddLabelsToIssue returned error: %v", err) - } - - want := []*Label{{URL: String("u")}} - if !reflect.DeepEqual(labels, want) { - t.Errorf("Issues.AddLabelsToIssue returned %+v, want %+v", labels, want) - } -} - -func TestIssuesService_AddLabelsToIssue_invalidOwner(t *testing.T) { - _, _, err := client.Issues.AddLabelsToIssue(context.Background(), "%", "%", 1, nil) - testURLParseError(t, err) -} - -func TestIssuesService_RemoveLabelForIssue(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/1/labels/l", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Issues.RemoveLabelForIssue(context.Background(), "o", "r", 1, "l") - if err != nil { - t.Errorf("Issues.RemoveLabelForIssue returned error: %v", err) - } -} - -func TestIssuesService_RemoveLabelForIssue_invalidOwner(t *testing.T) { - _, err := client.Issues.RemoveLabelForIssue(context.Background(), "%", "%", 1, "%") - testURLParseError(t, err) -} - -func TestIssuesService_ReplaceLabelsForIssue(t *testing.T) { - setup() - defer teardown() - - input := []string{"a", "b"} - - mux.HandleFunc("/repos/o/r/issues/1/labels", func(w http.ResponseWriter, r *http.Request) { - var v []string - json.NewDecoder(r.Body).Decode(&v) - - testMethod(t, r, "PUT") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `[{"url":"u"}]`) - }) - - labels, _, err := client.Issues.ReplaceLabelsForIssue(context.Background(), "o", "r", 1, input) - if err != nil { - t.Errorf("Issues.ReplaceLabelsForIssue returned error: %v", err) - } - - want := []*Label{{URL: String("u")}} - if !reflect.DeepEqual(labels, want) { - t.Errorf("Issues.ReplaceLabelsForIssue returned %+v, want %+v", labels, want) - } -} - -func TestIssuesService_ReplaceLabelsForIssue_invalidOwner(t *testing.T) { - _, _, err := client.Issues.ReplaceLabelsForIssue(context.Background(), "%", "%", 1, nil) - testURLParseError(t, err) -} - -func TestIssuesService_RemoveLabelsForIssue(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/1/labels", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Issues.RemoveLabelsForIssue(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Issues.RemoveLabelsForIssue returned error: %v", err) - } -} - -func TestIssuesService_RemoveLabelsForIssue_invalidOwner(t *testing.T) { - _, err := client.Issues.RemoveLabelsForIssue(context.Background(), "%", "%", 1) - testURLParseError(t, err) -} - -func TestIssuesService_ListLabelsForMilestone(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/milestones/1/labels", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"name": "a"},{"name": "b"}]`) - }) - - opt := &ListOptions{Page: 2} - labels, _, err := client.Issues.ListLabelsForMilestone(context.Background(), "o", "r", 1, opt) - if err != nil { - t.Errorf("Issues.ListLabelsForMilestone returned error: %v", err) - } - - want := []*Label{{Name: String("a")}, {Name: String("b")}} - if !reflect.DeepEqual(labels, want) { - t.Errorf("Issues.ListLabelsForMilestone returned %+v, want %+v", labels, want) - } -} - -func TestIssuesService_ListLabelsForMilestone_invalidOwner(t *testing.T) { - _, _, err := client.Issues.ListLabelsForMilestone(context.Background(), "%", "%", 1, nil) - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/issues_milestones_test.go b/vendor/github.com/google/go-github/github/issues_milestones_test.go deleted file mode 100644 index befa1b48727c..000000000000 --- a/vendor/github.com/google/go-github/github/issues_milestones_test.go +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestIssuesService_ListMilestones(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/milestones", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "state": "closed", - "sort": "due_date", - "direction": "asc", - "page": "2", - }) - fmt.Fprint(w, `[{"number":1}]`) - }) - - opt := &MilestoneListOptions{"closed", "due_date", "asc", ListOptions{Page: 2}} - milestones, _, err := client.Issues.ListMilestones(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("IssuesService.ListMilestones returned error: %v", err) - } - - want := []*Milestone{{Number: Int(1)}} - if !reflect.DeepEqual(milestones, want) { - t.Errorf("IssuesService.ListMilestones returned %+v, want %+v", milestones, want) - } -} - -func TestIssuesService_ListMilestones_invalidOwner(t *testing.T) { - _, _, err := client.Issues.ListMilestones(context.Background(), "%", "r", nil) - testURLParseError(t, err) -} - -func TestIssuesService_GetMilestone(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/milestones/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"number":1}`) - }) - - milestone, _, err := client.Issues.GetMilestone(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("IssuesService.GetMilestone returned error: %v", err) - } - - want := &Milestone{Number: Int(1)} - if !reflect.DeepEqual(milestone, want) { - t.Errorf("IssuesService.GetMilestone returned %+v, want %+v", milestone, want) - } -} - -func TestIssuesService_GetMilestone_invalidOwner(t *testing.T) { - _, _, err := client.Issues.GetMilestone(context.Background(), "%", "r", 1) - testURLParseError(t, err) -} - -func TestIssuesService_CreateMilestone(t *testing.T) { - setup() - defer teardown() - - input := &Milestone{Title: String("t")} - - mux.HandleFunc("/repos/o/r/milestones", func(w http.ResponseWriter, r *http.Request) { - v := new(Milestone) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"number":1}`) - }) - - milestone, _, err := client.Issues.CreateMilestone(context.Background(), "o", "r", input) - if err != nil { - t.Errorf("IssuesService.CreateMilestone returned error: %v", err) - } - - want := &Milestone{Number: Int(1)} - if !reflect.DeepEqual(milestone, want) { - t.Errorf("IssuesService.CreateMilestone returned %+v, want %+v", milestone, want) - } -} - -func TestIssuesService_CreateMilestone_invalidOwner(t *testing.T) { - _, _, err := client.Issues.CreateMilestone(context.Background(), "%", "r", nil) - testURLParseError(t, err) -} - -func TestIssuesService_EditMilestone(t *testing.T) { - setup() - defer teardown() - - input := &Milestone{Title: String("t")} - - mux.HandleFunc("/repos/o/r/milestones/1", func(w http.ResponseWriter, r *http.Request) { - v := new(Milestone) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"number":1}`) - }) - - milestone, _, err := client.Issues.EditMilestone(context.Background(), "o", "r", 1, input) - if err != nil { - t.Errorf("IssuesService.EditMilestone returned error: %v", err) - } - - want := &Milestone{Number: Int(1)} - if !reflect.DeepEqual(milestone, want) { - t.Errorf("IssuesService.EditMilestone returned %+v, want %+v", milestone, want) - } -} - -func TestIssuesService_EditMilestone_invalidOwner(t *testing.T) { - _, _, err := client.Issues.EditMilestone(context.Background(), "%", "r", 1, nil) - testURLParseError(t, err) -} - -func TestIssuesService_DeleteMilestone(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/milestones/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Issues.DeleteMilestone(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("IssuesService.DeleteMilestone returned error: %v", err) - } -} - -func TestIssuesService_DeleteMilestone_invalidOwner(t *testing.T) { - _, err := client.Issues.DeleteMilestone(context.Background(), "%", "r", 1) - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/issues_test.go b/vendor/github.com/google/go-github/github/issues_test.go deleted file mode 100644 index dadee75573e3..000000000000 --- a/vendor/github.com/google/go-github/github/issues_test.go +++ /dev/null @@ -1,277 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestIssuesService_List_all(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/issues", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - testFormValues(t, r, values{ - "filter": "all", - "state": "closed", - "labels": "a,b", - "sort": "updated", - "direction": "asc", - "since": "2002-02-10T15:30:00Z", - "page": "1", - "per_page": "2", - }) - fmt.Fprint(w, `[{"number":1}]`) - }) - - opt := &IssueListOptions{ - "all", "closed", []string{"a", "b"}, "updated", "asc", - time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC), - ListOptions{Page: 1, PerPage: 2}, - } - issues, _, err := client.Issues.List(context.Background(), true, opt) - if err != nil { - t.Errorf("Issues.List returned error: %v", err) - } - - want := []*Issue{{Number: Int(1)}} - if !reflect.DeepEqual(issues, want) { - t.Errorf("Issues.List returned %+v, want %+v", issues, want) - } -} - -func TestIssuesService_List_owned(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/issues", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - fmt.Fprint(w, `[{"number":1}]`) - }) - - issues, _, err := client.Issues.List(context.Background(), false, nil) - if err != nil { - t.Errorf("Issues.List returned error: %v", err) - } - - want := []*Issue{{Number: Int(1)}} - if !reflect.DeepEqual(issues, want) { - t.Errorf("Issues.List returned %+v, want %+v", issues, want) - } -} - -func TestIssuesService_ListByOrg(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/issues", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - fmt.Fprint(w, `[{"number":1}]`) - }) - - issues, _, err := client.Issues.ListByOrg(context.Background(), "o", nil) - if err != nil { - t.Errorf("Issues.ListByOrg returned error: %v", err) - } - - want := []*Issue{{Number: Int(1)}} - if !reflect.DeepEqual(issues, want) { - t.Errorf("Issues.List returned %+v, want %+v", issues, want) - } -} - -func TestIssuesService_ListByOrg_invalidOrg(t *testing.T) { - _, _, err := client.Issues.ListByOrg(context.Background(), "%", nil) - testURLParseError(t, err) -} - -func TestIssuesService_ListByRepo(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - testFormValues(t, r, values{ - "milestone": "*", - "state": "closed", - "assignee": "a", - "creator": "c", - "mentioned": "m", - "labels": "a,b", - "sort": "updated", - "direction": "asc", - "since": "2002-02-10T15:30:00Z", - }) - fmt.Fprint(w, `[{"number":1}]`) - }) - - opt := &IssueListByRepoOptions{ - "*", "closed", "a", "c", "m", []string{"a", "b"}, "updated", "asc", - time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC), - ListOptions{0, 0}, - } - issues, _, err := client.Issues.ListByRepo(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Issues.ListByOrg returned error: %v", err) - } - - want := []*Issue{{Number: Int(1)}} - if !reflect.DeepEqual(issues, want) { - t.Errorf("Issues.List returned %+v, want %+v", issues, want) - } -} - -func TestIssuesService_ListByRepo_invalidOwner(t *testing.T) { - _, _, err := client.Issues.ListByRepo(context.Background(), "%", "r", nil) - testURLParseError(t, err) -} - -func TestIssuesService_Get(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - fmt.Fprint(w, `{"number":1, "labels": [{"url": "u", "name": "n", "color": "c"}]}`) - }) - - issue, _, err := client.Issues.Get(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Issues.Get returned error: %v", err) - } - - want := &Issue{ - Number: Int(1), - Labels: []Label{{ - URL: String("u"), - Name: String("n"), - Color: String("c"), - }}, - } - if !reflect.DeepEqual(issue, want) { - t.Errorf("Issues.Get returned %+v, want %+v", issue, want) - } -} - -func TestIssuesService_Get_invalidOwner(t *testing.T) { - _, _, err := client.Issues.Get(context.Background(), "%", "r", 1) - testURLParseError(t, err) -} - -func TestIssuesService_Create(t *testing.T) { - setup() - defer teardown() - - input := &IssueRequest{ - Title: String("t"), - Body: String("b"), - Assignee: String("a"), - Labels: &[]string{"l1", "l2"}, - } - - mux.HandleFunc("/repos/o/r/issues", func(w http.ResponseWriter, r *http.Request) { - v := new(IssueRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"number":1}`) - }) - - issue, _, err := client.Issues.Create(context.Background(), "o", "r", input) - if err != nil { - t.Errorf("Issues.Create returned error: %v", err) - } - - want := &Issue{Number: Int(1)} - if !reflect.DeepEqual(issue, want) { - t.Errorf("Issues.Create returned %+v, want %+v", issue, want) - } -} - -func TestIssuesService_Create_invalidOwner(t *testing.T) { - _, _, err := client.Issues.Create(context.Background(), "%", "r", nil) - testURLParseError(t, err) -} - -func TestIssuesService_Edit(t *testing.T) { - setup() - defer teardown() - - input := &IssueRequest{Title: String("t")} - - mux.HandleFunc("/repos/o/r/issues/1", func(w http.ResponseWriter, r *http.Request) { - v := new(IssueRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"number":1}`) - }) - - issue, _, err := client.Issues.Edit(context.Background(), "o", "r", 1, input) - if err != nil { - t.Errorf("Issues.Edit returned error: %v", err) - } - - want := &Issue{Number: Int(1)} - if !reflect.DeepEqual(issue, want) { - t.Errorf("Issues.Edit returned %+v, want %+v", issue, want) - } -} - -func TestIssuesService_Edit_invalidOwner(t *testing.T) { - _, _, err := client.Issues.Edit(context.Background(), "%", "r", 1, nil) - testURLParseError(t, err) -} - -func TestIssuesService_Lock(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/1/lock", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - - w.WriteHeader(http.StatusNoContent) - }) - - if _, err := client.Issues.Lock(context.Background(), "o", "r", 1); err != nil { - t.Errorf("Issues.Lock returned error: %v", err) - } -} - -func TestIssuesService_Unlock(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/1/lock", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - - w.WriteHeader(http.StatusNoContent) - }) - - if _, err := client.Issues.Unlock(context.Background(), "o", "r", 1); err != nil { - t.Errorf("Issues.Unlock returned error: %v", err) - } -} diff --git a/vendor/github.com/google/go-github/github/issues_timeline_test.go b/vendor/github.com/google/go-github/github/issues_timeline_test.go deleted file mode 100644 index 2fd22109b06b..000000000000 --- a/vendor/github.com/google/go-github/github/issues_timeline_test.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestIssuesService_ListIssueTimeline(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/1/timeline", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeTimelinePreview) - testFormValues(t, r, values{ - "page": "1", - "per_page": "2", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 1, PerPage: 2} - events, _, err := client.Issues.ListIssueTimeline(context.Background(), "o", "r", 1, opt) - if err != nil { - t.Errorf("Issues.ListIssueTimeline returned error: %v", err) - } - - want := []*Timeline{{ID: Int(1)}} - if !reflect.DeepEqual(events, want) { - t.Errorf("Issues.ListIssueTimeline = %+v, want %+v", events, want) - } -} diff --git a/vendor/github.com/google/go-github/github/licenses_test.go b/vendor/github.com/google/go-github/github/licenses_test.go deleted file mode 100644 index 5c06e6598543..000000000000 --- a/vendor/github.com/google/go-github/github/licenses_test.go +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestLicensesService_List(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/licenses", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeLicensesPreview) - fmt.Fprint(w, `[{"key":"mit","name":"MIT","spdx_id":"MIT","url":"https://api.github.com/licenses/mit","featured":true}]`) - }) - - licenses, _, err := client.Licenses.List(context.Background()) - if err != nil { - t.Errorf("Licenses.List returned error: %v", err) - } - - want := []*License{{ - Key: String("mit"), - Name: String("MIT"), - SPDXID: String("MIT"), - URL: String("https://api.github.com/licenses/mit"), - Featured: Bool(true), - }} - if !reflect.DeepEqual(licenses, want) { - t.Errorf("Licenses.List returned %+v, want %+v", licenses, want) - } -} - -func TestLicensesService_Get(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/licenses/mit", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeLicensesPreview) - fmt.Fprint(w, `{"key":"mit","name":"MIT"}`) - }) - - license, _, err := client.Licenses.Get(context.Background(), "mit") - if err != nil { - t.Errorf("Licenses.Get returned error: %v", err) - } - - want := &License{Key: String("mit"), Name: String("MIT")} - if !reflect.DeepEqual(license, want) { - t.Errorf("Licenses.Get returned %+v, want %+v", license, want) - } -} - -func TestLicensesService_Get_invalidTemplate(t *testing.T) { - _, _, err := client.Licenses.Get(context.Background(), "%") - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/messages_test.go b/vendor/github.com/google/go-github/github/messages_test.go deleted file mode 100644 index 5f348f2aa6f3..000000000000 --- a/vendor/github.com/google/go-github/github/messages_test.go +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "bytes" - "encoding/json" - "net/http" - "reflect" - "testing" -) - -func TestValidatePayload(t *testing.T) { - const defaultBody = `{"yo":true}` // All tests below use the default request body and signature. - const defaultSignature = "sha1=126f2c800419c60137ce748d7672e77b65cf16d6" - secretKey := []byte("0123456789abcdef") - tests := []struct { - signature string - eventID string - event string - wantEventID string - wantEvent string - wantPayload string - }{ - // The following tests generate expected errors: - {}, // Missing signature - {signature: "yo"}, // Missing signature prefix - {signature: "sha1=yo"}, // Signature not hex string - {signature: "sha1=012345"}, // Invalid signature - // The following tests expect err=nil: - { - signature: defaultSignature, - eventID: "dead-beef", - event: "ping", - wantEventID: "dead-beef", - wantEvent: "ping", - wantPayload: defaultBody, - }, - { - signature: defaultSignature, - event: "ping", - wantEvent: "ping", - wantPayload: defaultBody, - }, - { - signature: "sha256=b1f8020f5b4cd42042f807dd939015c4a418bc1ff7f604dd55b0a19b5d953d9b", - event: "ping", - wantEvent: "ping", - wantPayload: defaultBody, - }, - { - signature: "sha512=8456767023c1195682e182a23b3f5d19150ecea598fde8cb85918f7281b16079471b1329f92b912c4d8bd7455cb159777db8f29608b20c7c87323ba65ae62e1f", - event: "ping", - wantEvent: "ping", - wantPayload: defaultBody, - }, - } - - for _, test := range tests { - buf := bytes.NewBufferString(defaultBody) - req, err := http.NewRequest("GET", "http://localhost/event", buf) - if err != nil { - t.Fatalf("NewRequest: %v", err) - } - if test.signature != "" { - req.Header.Set(signatureHeader, test.signature) - } - - got, err := ValidatePayload(req, secretKey) - if err != nil { - if test.wantPayload != "" { - t.Errorf("ValidatePayload(%#v): err = %v, want nil", test, err) - } - continue - } - if string(got) != test.wantPayload { - t.Errorf("ValidatePayload = %q, want %q", got, test.wantPayload) - } - } -} - -func TestParseWebHook(t *testing.T) { - tests := []struct { - payload interface{} - messageType string - }{ - { - payload: &CommitCommentEvent{}, - messageType: "commit_comment", - }, - { - payload: &CreateEvent{}, - messageType: "create", - }, - { - payload: &DeleteEvent{}, - messageType: "delete", - }, - { - payload: &DeploymentEvent{}, - messageType: "deployment", - }, - - { - payload: &DeploymentStatusEvent{}, - messageType: "deployment_status", - }, - { - payload: &ForkEvent{}, - messageType: "fork", - }, - { - payload: &GollumEvent{}, - messageType: "gollum", - }, - { - payload: &InstallationEvent{}, - messageType: "installation", - }, - { - payload: &InstallationRepositoriesEvent{}, - messageType: "installation_repositories", - }, - { - payload: &IssueCommentEvent{}, - messageType: "issue_comment", - }, - { - payload: &IssuesEvent{}, - messageType: "issues", - }, - { - payload: &LabelEvent{}, - messageType: "label", - }, - { - payload: &MemberEvent{}, - messageType: "member", - }, - { - payload: &MembershipEvent{}, - messageType: "membership", - }, - { - payload: &MilestoneEvent{}, - messageType: "milestone", - }, - { - payload: &OrganizationEvent{}, - messageType: "organization", - }, - { - payload: &OrgBlockEvent{}, - messageType: "org_block", - }, - { - payload: &PageBuildEvent{}, - messageType: "page_build", - }, - { - payload: &PingEvent{}, - messageType: "ping", - }, - { - payload: &ProjectEvent{}, - messageType: "project", - }, - { - payload: &ProjectCardEvent{}, - messageType: "project_card", - }, - { - payload: &ProjectColumnEvent{}, - messageType: "project_column", - }, - { - payload: &PublicEvent{}, - messageType: "public", - }, - { - payload: &PullRequestEvent{}, - messageType: "pull_request", - }, - { - payload: &PullRequestReviewEvent{}, - messageType: "pull_request_review", - }, - { - payload: &PullRequestReviewCommentEvent{}, - messageType: "pull_request_review_comment", - }, - { - payload: &PushEvent{}, - messageType: "push", - }, - { - payload: &ReleaseEvent{}, - messageType: "release", - }, - { - payload: &RepositoryEvent{}, - messageType: "repository", - }, - { - payload: &StatusEvent{}, - messageType: "status", - }, - { - payload: &TeamEvent{}, - messageType: "team", - }, - { - payload: &TeamAddEvent{}, - messageType: "team_add", - }, - { - payload: &WatchEvent{}, - messageType: "watch", - }, - } - - for _, test := range tests { - p, err := json.Marshal(test.payload) - if err != nil { - t.Fatalf("Marshal(%#v): %v", test.payload, err) - } - got, err := ParseWebHook(test.messageType, p) - if err != nil { - t.Fatalf("ParseWebHook: %v", err) - } - if want := test.payload; !reflect.DeepEqual(got, want) { - t.Errorf("ParseWebHook(%#v, %#v) = %#v, want %#v", test.messageType, p, got, want) - } - } -} - -func TestDeliveryID(t *testing.T) { - id := "8970a780-244e-11e7-91ca-da3aabcb9793" - req, err := http.NewRequest("POST", "http://localhost", nil) - if err != nil { - t.Fatalf("DeliveryID: %v", err) - } - req.Header.Set("X-Github-Delivery", id) - - got := DeliveryID(req) - if got != id { - t.Errorf("DeliveryID(%#v) = %q, want %q", req, got, id) - } -} diff --git a/vendor/github.com/google/go-github/github/migrations_source_import_test.go b/vendor/github.com/google/go-github/github/migrations_source_import_test.go deleted file mode 100644 index 67b98fb42b90..000000000000 --- a/vendor/github.com/google/go-github/github/migrations_source_import_test.go +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestMigrationService_StartImport(t *testing.T) { - setup() - defer teardown() - - input := &Import{ - VCS: String("git"), - VCSURL: String("url"), - VCSUsername: String("u"), - VCSPassword: String("p"), - } - - mux.HandleFunc("/repos/o/r/import", func(w http.ResponseWriter, r *http.Request) { - v := new(Import) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PUT") - testHeader(t, r, "Accept", mediaTypeImportPreview) - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - w.WriteHeader(http.StatusCreated) - fmt.Fprint(w, `{"status":"importing"}`) - }) - - got, _, err := client.Migrations.StartImport(context.Background(), "o", "r", input) - if err != nil { - t.Errorf("StartImport returned error: %v", err) - } - want := &Import{Status: String("importing")} - if !reflect.DeepEqual(got, want) { - t.Errorf("StartImport = %+v, want %+v", got, want) - } -} - -func TestMigrationService_ImportProgress(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/import", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeImportPreview) - fmt.Fprint(w, `{"status":"complete"}`) - }) - - got, _, err := client.Migrations.ImportProgress(context.Background(), "o", "r") - if err != nil { - t.Errorf("ImportProgress returned error: %v", err) - } - want := &Import{Status: String("complete")} - if !reflect.DeepEqual(got, want) { - t.Errorf("ImportProgress = %+v, want %+v", got, want) - } -} - -func TestMigrationService_UpdateImport(t *testing.T) { - setup() - defer teardown() - - input := &Import{ - VCS: String("git"), - VCSURL: String("url"), - VCSUsername: String("u"), - VCSPassword: String("p"), - } - - mux.HandleFunc("/repos/o/r/import", func(w http.ResponseWriter, r *http.Request) { - v := new(Import) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - testHeader(t, r, "Accept", mediaTypeImportPreview) - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - w.WriteHeader(http.StatusCreated) - fmt.Fprint(w, `{"status":"importing"}`) - }) - - got, _, err := client.Migrations.UpdateImport(context.Background(), "o", "r", input) - if err != nil { - t.Errorf("UpdateImport returned error: %v", err) - } - want := &Import{Status: String("importing")} - if !reflect.DeepEqual(got, want) { - t.Errorf("UpdateImport = %+v, want %+v", got, want) - } -} - -func TestMigrationService_CommitAuthors(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/import/authors", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeImportPreview) - fmt.Fprint(w, `[{"id":1,"name":"a"},{"id":2,"name":"b"}]`) - }) - - got, _, err := client.Migrations.CommitAuthors(context.Background(), "o", "r") - if err != nil { - t.Errorf("CommitAuthors returned error: %v", err) - } - want := []*SourceImportAuthor{ - {ID: Int(1), Name: String("a")}, - {ID: Int(2), Name: String("b")}, - } - if !reflect.DeepEqual(got, want) { - t.Errorf("CommitAuthors = %+v, want %+v", got, want) - } -} - -func TestMigrationService_MapCommitAuthor(t *testing.T) { - setup() - defer teardown() - - input := &SourceImportAuthor{Name: String("n"), Email: String("e")} - - mux.HandleFunc("/repos/o/r/import/authors/1", func(w http.ResponseWriter, r *http.Request) { - v := new(SourceImportAuthor) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - testHeader(t, r, "Accept", mediaTypeImportPreview) - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id": 1}`) - }) - - got, _, err := client.Migrations.MapCommitAuthor(context.Background(), "o", "r", 1, input) - if err != nil { - t.Errorf("MapCommitAuthor returned error: %v", err) - } - want := &SourceImportAuthor{ID: Int(1)} - if !reflect.DeepEqual(got, want) { - t.Errorf("MapCommitAuthor = %+v, want %+v", got, want) - } -} - -func TestMigrationService_SetLFSPreference(t *testing.T) { - setup() - defer teardown() - - input := &Import{UseLFS: String("opt_in")} - - mux.HandleFunc("/repos/o/r/import/lfs", func(w http.ResponseWriter, r *http.Request) { - v := new(Import) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - testHeader(t, r, "Accept", mediaTypeImportPreview) - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - w.WriteHeader(http.StatusCreated) - fmt.Fprint(w, `{"status":"importing"}`) - }) - - got, _, err := client.Migrations.SetLFSPreference(context.Background(), "o", "r", input) - if err != nil { - t.Errorf("SetLFSPreference returned error: %v", err) - } - want := &Import{Status: String("importing")} - if !reflect.DeepEqual(got, want) { - t.Errorf("SetLFSPreference = %+v, want %+v", got, want) - } -} - -func TestMigrationService_LargeFiles(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/import/large_files", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeImportPreview) - fmt.Fprint(w, `[{"oid":"a"},{"oid":"b"}]`) - }) - - got, _, err := client.Migrations.LargeFiles(context.Background(), "o", "r") - if err != nil { - t.Errorf("LargeFiles returned error: %v", err) - } - want := []*LargeFile{ - {OID: String("a")}, - {OID: String("b")}, - } - if !reflect.DeepEqual(got, want) { - t.Errorf("LargeFiles = %+v, want %+v", got, want) - } -} - -func TestMigrationService_CancelImport(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/import", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - testHeader(t, r, "Accept", mediaTypeImportPreview) - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Migrations.CancelImport(context.Background(), "o", "r") - if err != nil { - t.Errorf("CancelImport returned error: %v", err) - } -} diff --git a/vendor/github.com/google/go-github/github/migrations_test.go b/vendor/github.com/google/go-github/github/migrations_test.go deleted file mode 100644 index 7e0ac0f75069..000000000000 --- a/vendor/github.com/google/go-github/github/migrations_test.go +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "strings" - "testing" -) - -func TestMigrationService_StartMigration(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/migrations", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testHeader(t, r, "Accept", mediaTypeMigrationsPreview) - - w.WriteHeader(http.StatusCreated) - w.Write(migrationJSON) - }) - - opt := &MigrationOptions{ - LockRepositories: true, - ExcludeAttachments: false, - } - got, _, err := client.Migrations.StartMigration(context.Background(), "o", []string{"r"}, opt) - if err != nil { - t.Errorf("StartMigration returned error: %v", err) - } - if want := wantMigration; !reflect.DeepEqual(got, want) { - t.Errorf("StartMigration = %+v, want %+v", got, want) - } -} - -func TestMigrationService_ListMigrations(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/migrations", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeMigrationsPreview) - - w.WriteHeader(http.StatusOK) - w.Write([]byte(fmt.Sprintf("[%s]", migrationJSON))) - }) - - got, _, err := client.Migrations.ListMigrations(context.Background(), "o") - if err != nil { - t.Errorf("ListMigrations returned error: %v", err) - } - if want := []*Migration{wantMigration}; !reflect.DeepEqual(got, want) { - t.Errorf("ListMigrations = %+v, want %+v", got, want) - } -} - -func TestMigrationService_MigrationStatus(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/migrations/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeMigrationsPreview) - - w.WriteHeader(http.StatusOK) - w.Write(migrationJSON) - }) - - got, _, err := client.Migrations.MigrationStatus(context.Background(), "o", 1) - if err != nil { - t.Errorf("MigrationStatus returned error: %v", err) - } - if want := wantMigration; !reflect.DeepEqual(got, want) { - t.Errorf("MigrationStatus = %+v, want %+v", got, want) - } -} - -func TestMigrationService_MigrationArchiveURL(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/migrations/1/archive", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeMigrationsPreview) - - http.Redirect(w, r, "/yo", http.StatusFound) - }) - mux.HandleFunc("/yo", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - - w.WriteHeader(http.StatusOK) - w.Write([]byte("0123456789abcdef")) - }) - - got, err := client.Migrations.MigrationArchiveURL(context.Background(), "o", 1) - if err != nil { - t.Errorf("MigrationStatus returned error: %v", err) - } - if want := "/yo"; !strings.HasSuffix(got, want) { - t.Errorf("MigrationArchiveURL = %+v, want %+v", got, want) - } -} - -func TestMigrationService_DeleteMigration(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/migrations/1/archive", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - testHeader(t, r, "Accept", mediaTypeMigrationsPreview) - - w.WriteHeader(http.StatusNoContent) - }) - - if _, err := client.Migrations.DeleteMigration(context.Background(), "o", 1); err != nil { - t.Errorf("DeleteMigration returned error: %v", err) - } -} - -func TestMigrationService_UnlockRepo(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/migrations/1/repos/r/lock", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - testHeader(t, r, "Accept", mediaTypeMigrationsPreview) - - w.WriteHeader(http.StatusNoContent) - }) - - if _, err := client.Migrations.UnlockRepo(context.Background(), "o", 1, "r"); err != nil { - t.Errorf("UnlockRepo returned error: %v", err) - } -} - -var migrationJSON = []byte(`{ - "id": 79, - "guid": "0b989ba4-242f-11e5-81e1-c7b6966d2516", - "state": "pending", - "lock_repositories": true, - "exclude_attachments": false, - "url": "https://api.github.com/orgs/octo-org/migrations/79", - "created_at": "2015-07-06T15:33:38-07:00", - "updated_at": "2015-07-06T15:33:38-07:00", - "repositories": [ - { - "id": 1296269, - "name": "Hello-World", - "full_name": "octocat/Hello-World", - "description": "This your first repo!" - } - ] -}`) - -var wantMigration = &Migration{ - ID: Int(79), - GUID: String("0b989ba4-242f-11e5-81e1-c7b6966d2516"), - State: String("pending"), - LockRepositories: Bool(true), - ExcludeAttachments: Bool(false), - URL: String("https://api.github.com/orgs/octo-org/migrations/79"), - CreatedAt: String("2015-07-06T15:33:38-07:00"), - UpdatedAt: String("2015-07-06T15:33:38-07:00"), - Repositories: []*Repository{ - { - ID: Int(1296269), - Name: String("Hello-World"), - FullName: String("octocat/Hello-World"), - Description: String("This your first repo!"), - }, - }, -} diff --git a/vendor/github.com/google/go-github/github/misc_test.go b/vendor/github.com/google/go-github/github/misc_test.go deleted file mode 100644 index f2b2df44b5e9..000000000000 --- a/vendor/github.com/google/go-github/github/misc_test.go +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestMarkdown(t *testing.T) { - setup() - defer teardown() - - input := &markdownRequest{ - Text: String("# text #"), - Mode: String("gfm"), - Context: String("google/go-github"), - } - mux.HandleFunc("/markdown", func(w http.ResponseWriter, r *http.Request) { - v := new(markdownRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - fmt.Fprint(w, `

text

`) - }) - - md, _, err := client.Markdown(context.Background(), "# text #", &MarkdownOptions{ - Mode: "gfm", - Context: "google/go-github", - }) - if err != nil { - t.Errorf("Markdown returned error: %v", err) - } - - if want := "

text

"; want != md { - t.Errorf("Markdown returned %+v, want %+v", md, want) - } -} - -func TestListEmojis(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/emojis", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"+1": "+1.png"}`) - }) - - emoji, _, err := client.ListEmojis(context.Background()) - if err != nil { - t.Errorf("ListEmojis returned error: %v", err) - } - - want := map[string]string{"+1": "+1.png"} - if !reflect.DeepEqual(want, emoji) { - t.Errorf("ListEmojis returned %+v, want %+v", emoji, want) - } -} - -func TestListCodesOfConduct(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/codes_of_conduct", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeCodesOfConductPreview) - fmt.Fprint(w, `[{ - "key": "key", - "name": "name", - "url": "url"} - ]`) - }) - - cs, _, err := client.ListCodesOfConduct(context.Background()) - if err != nil { - t.Errorf("ListCodesOfConduct returned error: %v", err) - } - - want := []*CodeOfConduct{ - { - Key: String("key"), - Name: String("name"), - URL: String("url"), - }} - if !reflect.DeepEqual(want, cs) { - t.Errorf("ListCodesOfConduct returned %+v, want %+v", cs, want) - } -} - -func TestGetCodeOfConduct(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/codes_of_conduct/k", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeCodesOfConductPreview) - fmt.Fprint(w, `{ - "key": "key", - "name": "name", - "url": "url", - "body": "body"}`, - ) - }) - - coc, _, err := client.GetCodeOfConduct(context.Background(), "k") - if err != nil { - t.Errorf("ListCodesOfConduct returned error: %v", err) - } - - want := &CodeOfConduct{ - Key: String("key"), - Name: String("name"), - URL: String("url"), - Body: String("body"), - } - if !reflect.DeepEqual(want, coc) { - t.Errorf("GetCodeOfConductByKey returned %+v, want %+v", coc, want) - } -} - -func TestAPIMeta(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/meta", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"hooks":["h"], "git":["g"], "pages":["p"], "verifiable_password_authentication": true}`) - }) - - meta, _, err := client.APIMeta(context.Background()) - if err != nil { - t.Errorf("APIMeta returned error: %v", err) - } - - want := &APIMeta{ - Hooks: []string{"h"}, - Git: []string{"g"}, - Pages: []string{"p"}, - VerifiablePasswordAuthentication: Bool(true), - } - if !reflect.DeepEqual(want, meta) { - t.Errorf("APIMeta returned %+v, want %+v", meta, want) - } -} - -func TestOctocat(t *testing.T) { - setup() - defer teardown() - - input := "input" - output := "sample text" - - mux.HandleFunc("/octocat", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"s": input}) - w.Header().Set("Content-Type", "application/octocat-stream") - fmt.Fprint(w, output) - }) - - got, _, err := client.Octocat(context.Background(), input) - if err != nil { - t.Errorf("Octocat returned error: %v", err) - } - - if want := output; got != want { - t.Errorf("Octocat returned %+v, want %+v", got, want) - } -} - -func TestZen(t *testing.T) { - setup() - defer teardown() - - output := "sample text" - - mux.HandleFunc("/zen", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.Header().Set("Content-Type", "text/plain;charset=utf-8") - fmt.Fprint(w, output) - }) - - got, _, err := client.Zen(context.Background()) - if err != nil { - t.Errorf("Zen returned error: %v", err) - } - - if want := output; got != want { - t.Errorf("Zen returned %+v, want %+v", got, want) - } -} - -func TestListServiceHooks(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/hooks", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{ - "name":"n", - "events":["e"], - "supported_events":["s"], - "schema":[ - ["a", "b"] - ] - }]`) - }) - - hooks, _, err := client.ListServiceHooks(context.Background()) - if err != nil { - t.Errorf("ListServiceHooks returned error: %v", err) - } - - want := []*ServiceHook{{ - Name: String("n"), - Events: []string{"e"}, - SupportedEvents: []string{"s"}, - Schema: [][]string{{"a", "b"}}, - }} - if !reflect.DeepEqual(hooks, want) { - t.Errorf("ListServiceHooks returned %+v, want %+v", hooks, want) - } -} diff --git a/vendor/github.com/google/go-github/github/orgs_hooks_test.go b/vendor/github.com/google/go-github/github/orgs_hooks_test.go deleted file mode 100644 index 69e75f9f4ac1..000000000000 --- a/vendor/github.com/google/go-github/github/orgs_hooks_test.go +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright 2015 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestOrganizationsService_ListHooks(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/hooks", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}, {"id":2}]`) - }) - - opt := &ListOptions{Page: 2} - - hooks, _, err := client.Organizations.ListHooks(context.Background(), "o", opt) - if err != nil { - t.Errorf("Organizations.ListHooks returned error: %v", err) - } - - want := []*Hook{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(hooks, want) { - t.Errorf("Organizations.ListHooks returned %+v, want %+v", hooks, want) - } -} - -func TestOrganizationsService_ListHooks_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.ListHooks(context.Background(), "%", nil) - testURLParseError(t, err) -} - -func TestOrganizationsService_GetHook(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/hooks/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - hook, _, err := client.Organizations.GetHook(context.Background(), "o", 1) - if err != nil { - t.Errorf("Organizations.GetHook returned error: %v", err) - } - - want := &Hook{ID: Int(1)} - if !reflect.DeepEqual(hook, want) { - t.Errorf("Organizations.GetHook returned %+v, want %+v", hook, want) - } -} - -func TestOrganizationsService_GetHook_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.GetHook(context.Background(), "%", 1) - testURLParseError(t, err) -} - -func TestOrganizationsService_EditHook(t *testing.T) { - setup() - defer teardown() - - input := &Hook{Name: String("t")} - - mux.HandleFunc("/orgs/o/hooks/1", func(w http.ResponseWriter, r *http.Request) { - v := new(Hook) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - hook, _, err := client.Organizations.EditHook(context.Background(), "o", 1, input) - if err != nil { - t.Errorf("Organizations.EditHook returned error: %v", err) - } - - want := &Hook{ID: Int(1)} - if !reflect.DeepEqual(hook, want) { - t.Errorf("Organizations.EditHook returned %+v, want %+v", hook, want) - } -} - -func TestOrganizationsService_EditHook_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.EditHook(context.Background(), "%", 1, nil) - testURLParseError(t, err) -} - -func TestOrganizationsService_PingHook(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/hooks/1/pings", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - }) - - _, err := client.Organizations.PingHook(context.Background(), "o", 1) - if err != nil { - t.Errorf("Organizations.PingHook returned error: %v", err) - } -} - -func TestOrganizationsService_DeleteHook(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/hooks/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Organizations.DeleteHook(context.Background(), "o", 1) - if err != nil { - t.Errorf("Organizations.DeleteHook returned error: %v", err) - } -} - -func TestOrganizationsService_DeleteHook_invalidOrg(t *testing.T) { - _, err := client.Organizations.DeleteHook(context.Background(), "%", 1) - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/orgs_members_test.go b/vendor/github.com/google/go-github/github/orgs_members_test.go deleted file mode 100644 index a17c51865df6..000000000000 --- a/vendor/github.com/google/go-github/github/orgs_members_test.go +++ /dev/null @@ -1,434 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestOrganizationsService_ListMembers(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/members", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "filter": "2fa_disabled", - "role": "admin", - "page": "2", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListMembersOptions{ - PublicOnly: false, - Filter: "2fa_disabled", - Role: "admin", - ListOptions: ListOptions{Page: 2}, - } - members, _, err := client.Organizations.ListMembers(context.Background(), "o", opt) - if err != nil { - t.Errorf("Organizations.ListMembers returned error: %v", err) - } - - want := []*User{{ID: Int(1)}} - if !reflect.DeepEqual(members, want) { - t.Errorf("Organizations.ListMembers returned %+v, want %+v", members, want) - } -} - -func TestOrganizationsService_ListMembers_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.ListMembers(context.Background(), "%", nil) - testURLParseError(t, err) -} - -func TestOrganizationsService_ListMembers_public(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/public_members", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListMembersOptions{PublicOnly: true} - members, _, err := client.Organizations.ListMembers(context.Background(), "o", opt) - if err != nil { - t.Errorf("Organizations.ListMembers returned error: %v", err) - } - - want := []*User{{ID: Int(1)}} - if !reflect.DeepEqual(members, want) { - t.Errorf("Organizations.ListMembers returned %+v, want %+v", members, want) - } -} - -func TestOrganizationsService_IsMember(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNoContent) - }) - - member, _, err := client.Organizations.IsMember(context.Background(), "o", "u") - if err != nil { - t.Errorf("Organizations.IsMember returned error: %v", err) - } - if want := true; member != want { - t.Errorf("Organizations.IsMember returned %+v, want %+v", member, want) - } -} - -// ensure that a 404 response is interpreted as "false" and not an error -func TestOrganizationsService_IsMember_notMember(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - member, _, err := client.Organizations.IsMember(context.Background(), "o", "u") - if err != nil { - t.Errorf("Organizations.IsMember returned error: %+v", err) - } - if want := false; member != want { - t.Errorf("Organizations.IsMember returned %+v, want %+v", member, want) - } -} - -// ensure that a 400 response is interpreted as an actual error, and not simply -// as "false" like the above case of a 404 -func TestOrganizationsService_IsMember_error(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - http.Error(w, "BadRequest", http.StatusBadRequest) - }) - - member, _, err := client.Organizations.IsMember(context.Background(), "o", "u") - if err == nil { - t.Errorf("Expected HTTP 400 response") - } - if want := false; member != want { - t.Errorf("Organizations.IsMember returned %+v, want %+v", member, want) - } -} - -func TestOrganizationsService_IsMember_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.IsMember(context.Background(), "%", "u") - testURLParseError(t, err) -} - -func TestOrganizationsService_IsPublicMember(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/public_members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNoContent) - }) - - member, _, err := client.Organizations.IsPublicMember(context.Background(), "o", "u") - if err != nil { - t.Errorf("Organizations.IsPublicMember returned error: %v", err) - } - if want := true; member != want { - t.Errorf("Organizations.IsPublicMember returned %+v, want %+v", member, want) - } -} - -// ensure that a 404 response is interpreted as "false" and not an error -func TestOrganizationsService_IsPublicMember_notMember(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/public_members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - member, _, err := client.Organizations.IsPublicMember(context.Background(), "o", "u") - if err != nil { - t.Errorf("Organizations.IsPublicMember returned error: %v", err) - } - if want := false; member != want { - t.Errorf("Organizations.IsPublicMember returned %+v, want %+v", member, want) - } -} - -// ensure that a 400 response is interpreted as an actual error, and not simply -// as "false" like the above case of a 404 -func TestOrganizationsService_IsPublicMember_error(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/public_members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - http.Error(w, "BadRequest", http.StatusBadRequest) - }) - - member, _, err := client.Organizations.IsPublicMember(context.Background(), "o", "u") - if err == nil { - t.Errorf("Expected HTTP 400 response") - } - if want := false; member != want { - t.Errorf("Organizations.IsPublicMember returned %+v, want %+v", member, want) - } -} - -func TestOrganizationsService_IsPublicMember_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.IsPublicMember(context.Background(), "%", "u") - testURLParseError(t, err) -} - -func TestOrganizationsService_RemoveMember(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Organizations.RemoveMember(context.Background(), "o", "u") - if err != nil { - t.Errorf("Organizations.RemoveMember returned error: %v", err) - } -} - -func TestOrganizationsService_RemoveMember_invalidOrg(t *testing.T) { - _, err := client.Organizations.RemoveMember(context.Background(), "%", "u") - testURLParseError(t, err) -} - -func TestOrganizationsService_ListOrgMemberships(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/memberships/orgs", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "state": "active", - "page": "2", - }) - fmt.Fprint(w, `[{"url":"u"}]`) - }) - - opt := &ListOrgMembershipsOptions{ - State: "active", - ListOptions: ListOptions{Page: 2}, - } - memberships, _, err := client.Organizations.ListOrgMemberships(context.Background(), opt) - if err != nil { - t.Errorf("Organizations.ListOrgMemberships returned error: %v", err) - } - - want := []*Membership{{URL: String("u")}} - if !reflect.DeepEqual(memberships, want) { - t.Errorf("Organizations.ListOrgMemberships returned %+v, want %+v", memberships, want) - } -} - -func TestOrganizationsService_GetOrgMembership_AuthenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/memberships/orgs/o", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"url":"u"}`) - }) - - membership, _, err := client.Organizations.GetOrgMembership(context.Background(), "", "o") - if err != nil { - t.Errorf("Organizations.GetOrgMembership returned error: %v", err) - } - - want := &Membership{URL: String("u")} - if !reflect.DeepEqual(membership, want) { - t.Errorf("Organizations.GetOrgMembership returned %+v, want %+v", membership, want) - } -} - -func TestOrganizationsService_GetOrgMembership_SpecifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/memberships/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"url":"u"}`) - }) - - membership, _, err := client.Organizations.GetOrgMembership(context.Background(), "u", "o") - if err != nil { - t.Errorf("Organizations.GetOrgMembership returned error: %v", err) - } - - want := &Membership{URL: String("u")} - if !reflect.DeepEqual(membership, want) { - t.Errorf("Organizations.GetOrgMembership returned %+v, want %+v", membership, want) - } -} - -func TestOrganizationsService_EditOrgMembership_AuthenticatedUser(t *testing.T) { - setup() - defer teardown() - - input := &Membership{State: String("active")} - - mux.HandleFunc("/user/memberships/orgs/o", func(w http.ResponseWriter, r *http.Request) { - v := new(Membership) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"url":"u"}`) - }) - - membership, _, err := client.Organizations.EditOrgMembership(context.Background(), "", "o", input) - if err != nil { - t.Errorf("Organizations.EditOrgMembership returned error: %v", err) - } - - want := &Membership{URL: String("u")} - if !reflect.DeepEqual(membership, want) { - t.Errorf("Organizations.EditOrgMembership returned %+v, want %+v", membership, want) - } -} - -func TestOrganizationsService_EditOrgMembership_SpecifiedUser(t *testing.T) { - setup() - defer teardown() - - input := &Membership{State: String("active")} - - mux.HandleFunc("/orgs/o/memberships/u", func(w http.ResponseWriter, r *http.Request) { - v := new(Membership) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PUT") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"url":"u"}`) - }) - - membership, _, err := client.Organizations.EditOrgMembership(context.Background(), "u", "o", input) - if err != nil { - t.Errorf("Organizations.EditOrgMembership returned error: %v", err) - } - - want := &Membership{URL: String("u")} - if !reflect.DeepEqual(membership, want) { - t.Errorf("Organizations.EditOrgMembership returned %+v, want %+v", membership, want) - } -} - -func TestOrganizationsService_RemoveOrgMembership(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/memberships/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Organizations.RemoveOrgMembership(context.Background(), "u", "o") - if err != nil { - t.Errorf("Organizations.RemoveOrgMembership returned error: %v", err) - } -} - -func TestOrganizationsService_ListPendingOrgInvitations(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/1/invitations", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "1"}) - fmt.Fprint(w, `[ - { - "id": 1, - "login": "monalisa", - "email": "octocat@github.com", - "role": "direct_member", - "created_at": "2017-01-21T00:00:00Z", - "inviter": { - "login": "other_user", - "id": 1, - "avatar_url": "https://github.com/images/error/other_user_happy.gif", - "gravatar_id": "", - "url": "https://api.github.com/users/other_user", - "html_url": "https://github.com/other_user", - "followers_url": "https://api.github.com/users/other_user/followers", - "following_url": "https://api.github.com/users/other_user/following/other_user", - "gists_url": "https://api.github.com/users/other_user/gists/gist_id", - "starred_url": "https://api.github.com/users/other_user/starred/owner/repo", - "subscriptions_url": "https://api.github.com/users/other_user/subscriptions", - "organizations_url": "https://api.github.com/users/other_user/orgs", - "repos_url": "https://api.github.com/users/other_user/repos", - "events_url": "https://api.github.com/users/other_user/events/privacy", - "received_events_url": "https://api.github.com/users/other_user/received_events/privacy", - "type": "User", - "site_admin": false - } - } - ]`) - }) - - opt := &ListOptions{Page: 1} - invitations, _, err := client.Organizations.ListPendingOrgInvitations(context.Background(), 1, opt) - if err != nil { - t.Errorf("Organizations.ListPendingOrgInvitations returned error: %v", err) - } - - createdAt := time.Date(2017, 01, 21, 0, 0, 0, 0, time.UTC) - want := []*Invitation{ - { - ID: Int(1), - Login: String("monalisa"), - Email: String("octocat@github.com"), - Role: String("direct_member"), - CreatedAt: &createdAt, - Inviter: &User{ - Login: String("other_user"), - ID: Int(1), - AvatarURL: String("https://github.com/images/error/other_user_happy.gif"), - GravatarID: String(""), - URL: String("https://api.github.com/users/other_user"), - HTMLURL: String("https://github.com/other_user"), - FollowersURL: String("https://api.github.com/users/other_user/followers"), - FollowingURL: String("https://api.github.com/users/other_user/following/other_user"), - GistsURL: String("https://api.github.com/users/other_user/gists/gist_id"), - StarredURL: String("https://api.github.com/users/other_user/starred/owner/repo"), - SubscriptionsURL: String("https://api.github.com/users/other_user/subscriptions"), - OrganizationsURL: String("https://api.github.com/users/other_user/orgs"), - ReposURL: String("https://api.github.com/users/other_user/repos"), - EventsURL: String("https://api.github.com/users/other_user/events/privacy"), - ReceivedEventsURL: String("https://api.github.com/users/other_user/received_events/privacy"), - Type: String("User"), - SiteAdmin: Bool(false), - }, - }} - - if !reflect.DeepEqual(invitations, want) { - t.Errorf("Organizations.ListPendingOrgInvitations returned %+v, want %+v", invitations, want) - } -} diff --git a/vendor/github.com/google/go-github/github/orgs_outside_collaborators_test.go b/vendor/github.com/google/go-github/github/orgs_outside_collaborators_test.go deleted file mode 100644 index 536006119b09..000000000000 --- a/vendor/github.com/google/go-github/github/orgs_outside_collaborators_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestOrganizationsService_ListOutsideCollaborators(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/outside_collaborators", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "filter": "2fa_disabled", - "page": "2", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOutsideCollaboratorsOptions{ - Filter: "2fa_disabled", - ListOptions: ListOptions{Page: 2}, - } - members, _, err := client.Organizations.ListOutsideCollaborators(context.Background(), "o", opt) - if err != nil { - t.Errorf("Organizations.ListOutsideCollaborators returned error: %v", err) - } - - want := []*User{{ID: Int(1)}} - if !reflect.DeepEqual(members, want) { - t.Errorf("Organizations.ListOutsideCollaborators returned %+v, want %+v", members, want) - } -} - -func TestOrganizationsService_ListOutsideCollaborators_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.ListOutsideCollaborators(context.Background(), "%", nil) - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/orgs_projects_test.go b/vendor/github.com/google/go-github/github/orgs_projects_test.go deleted file mode 100644 index 533f691968d5..000000000000 --- a/vendor/github.com/google/go-github/github/orgs_projects_test.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestOrganizationsService_ListProjects(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/projects", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeProjectsPreview) - testFormValues(t, r, values{"state": "open", "page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ProjectListOptions{State: "open", ListOptions: ListOptions{Page: 2}} - projects, _, err := client.Organizations.ListProjects(context.Background(), "o", opt) - if err != nil { - t.Errorf("Organizations.ListProjects returned error: %v", err) - } - - want := []*Project{{ID: Int(1)}} - if !reflect.DeepEqual(projects, want) { - t.Errorf("Organizations.ListProjects returned %+v, want %+v", projects, want) - } -} - -func TestOrganizationsService_CreateProject(t *testing.T) { - setup() - defer teardown() - - input := &ProjectOptions{Name: "Project Name", Body: "Project body."} - - mux.HandleFunc("/orgs/o/projects", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testHeader(t, r, "Accept", mediaTypeProjectsPreview) - - v := &ProjectOptions{} - json.NewDecoder(r.Body).Decode(v) - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - project, _, err := client.Organizations.CreateProject(context.Background(), "o", input) - if err != nil { - t.Errorf("Organizations.CreateProject returned error: %v", err) - } - - want := &Project{ID: Int(1)} - if !reflect.DeepEqual(project, want) { - t.Errorf("Organizations.CreateProject returned %+v, want %+v", project, want) - } -} diff --git a/vendor/github.com/google/go-github/github/orgs_teams_test.go b/vendor/github.com/google/go-github/github/orgs_teams_test.go deleted file mode 100644 index e9342fb9b794..000000000000 --- a/vendor/github.com/google/go-github/github/orgs_teams_test.go +++ /dev/null @@ -1,580 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestOrganizationsService_ListTeams(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/teams", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - teams, _, err := client.Organizations.ListTeams(context.Background(), "o", opt) - if err != nil { - t.Errorf("Organizations.ListTeams returned error: %v", err) - } - - want := []*Team{{ID: Int(1)}} - if !reflect.DeepEqual(teams, want) { - t.Errorf("Organizations.ListTeams returned %+v, want %+v", teams, want) - } -} - -func TestOrganizationsService_ListTeams_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.ListTeams(context.Background(), "%", nil) - testURLParseError(t, err) -} - -func TestOrganizationsService_GetTeam(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1, "name":"n", "description": "d", "url":"u", "slug": "s", "permission":"p", "ldap_dn":"cn=n,ou=groups,dc=example,dc=com"}`) - }) - - team, _, err := client.Organizations.GetTeam(context.Background(), 1) - if err != nil { - t.Errorf("Organizations.GetTeam returned error: %v", err) - } - - want := &Team{ID: Int(1), Name: String("n"), Description: String("d"), URL: String("u"), Slug: String("s"), Permission: String("p"), LDAPDN: String("cn=n,ou=groups,dc=example,dc=com")} - if !reflect.DeepEqual(team, want) { - t.Errorf("Organizations.GetTeam returned %+v, want %+v", team, want) - } -} - -func TestOrganizationsService_CreateTeam(t *testing.T) { - setup() - defer teardown() - - input := &Team{Name: String("n"), Privacy: String("closed")} - - mux.HandleFunc("/orgs/o/teams", func(w http.ResponseWriter, r *http.Request) { - v := new(Team) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - team, _, err := client.Organizations.CreateTeam(context.Background(), "o", input) - if err != nil { - t.Errorf("Organizations.CreateTeam returned error: %v", err) - } - - want := &Team{ID: Int(1)} - if !reflect.DeepEqual(team, want) { - t.Errorf("Organizations.CreateTeam returned %+v, want %+v", team, want) - } -} - -func TestOrganizationsService_CreateTeam_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.CreateTeam(context.Background(), "%", nil) - testURLParseError(t, err) -} - -func TestOrganizationsService_EditTeam(t *testing.T) { - setup() - defer teardown() - - input := &Team{Name: String("n"), Privacy: String("closed")} - - mux.HandleFunc("/teams/1", func(w http.ResponseWriter, r *http.Request) { - v := new(Team) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - team, _, err := client.Organizations.EditTeam(context.Background(), 1, input) - if err != nil { - t.Errorf("Organizations.EditTeam returned error: %v", err) - } - - want := &Team{ID: Int(1)} - if !reflect.DeepEqual(team, want) { - t.Errorf("Organizations.EditTeam returned %+v, want %+v", team, want) - } -} - -func TestOrganizationsService_DeleteTeam(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Organizations.DeleteTeam(context.Background(), 1) - if err != nil { - t.Errorf("Organizations.DeleteTeam returned error: %v", err) - } -} - -func TestOrganizationsService_ListTeamMembers(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/members", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"role": "member", "page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &OrganizationListTeamMembersOptions{Role: "member", ListOptions: ListOptions{Page: 2}} - members, _, err := client.Organizations.ListTeamMembers(context.Background(), 1, opt) - if err != nil { - t.Errorf("Organizations.ListTeamMembers returned error: %v", err) - } - - want := []*User{{ID: Int(1)}} - if !reflect.DeepEqual(members, want) { - t.Errorf("Organizations.ListTeamMembers returned %+v, want %+v", members, want) - } -} - -func TestOrganizationsService_IsTeamMember_true(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - }) - - member, _, err := client.Organizations.IsTeamMember(context.Background(), 1, "u") - if err != nil { - t.Errorf("Organizations.IsTeamMember returned error: %v", err) - } - if want := true; member != want { - t.Errorf("Organizations.IsTeamMember returned %+v, want %+v", member, want) - } -} - -// ensure that a 404 response is interpreted as "false" and not an error -func TestOrganizationsService_IsTeamMember_false(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - member, _, err := client.Organizations.IsTeamMember(context.Background(), 1, "u") - if err != nil { - t.Errorf("Organizations.IsTeamMember returned error: %+v", err) - } - if want := false; member != want { - t.Errorf("Organizations.IsTeamMember returned %+v, want %+v", member, want) - } -} - -// ensure that a 400 response is interpreted as an actual error, and not simply -// as "false" like the above case of a 404 -func TestOrganizationsService_IsTeamMember_error(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - http.Error(w, "BadRequest", http.StatusBadRequest) - }) - - member, _, err := client.Organizations.IsTeamMember(context.Background(), 1, "u") - if err == nil { - t.Errorf("Expected HTTP 400 response") - } - if want := false; member != want { - t.Errorf("Organizations.IsTeamMember returned %+v, want %+v", member, want) - } -} - -func TestOrganizationsService_IsTeamMember_invalidUser(t *testing.T) { - _, _, err := client.Organizations.IsTeamMember(context.Background(), 1, "%") - testURLParseError(t, err) -} - -func TestOrganizationsService_PublicizeMembership(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/public_members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Organizations.PublicizeMembership(context.Background(), "o", "u") - if err != nil { - t.Errorf("Organizations.PublicizeMembership returned error: %v", err) - } -} - -func TestOrganizationsService_PublicizeMembership_invalidOrg(t *testing.T) { - _, err := client.Organizations.PublicizeMembership(context.Background(), "%", "u") - testURLParseError(t, err) -} - -func TestOrganizationsService_ConcealMembership(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/public_members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Organizations.ConcealMembership(context.Background(), "o", "u") - if err != nil { - t.Errorf("Organizations.ConcealMembership returned error: %v", err) - } -} - -func TestOrganizationsService_ConcealMembership_invalidOrg(t *testing.T) { - _, err := client.Organizations.ConcealMembership(context.Background(), "%", "u") - testURLParseError(t, err) -} - -func TestOrganizationsService_ListTeamRepos(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/repos", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - members, _, err := client.Organizations.ListTeamRepos(context.Background(), 1, opt) - if err != nil { - t.Errorf("Organizations.ListTeamRepos returned error: %v", err) - } - - want := []*Repository{{ID: Int(1)}} - if !reflect.DeepEqual(members, want) { - t.Errorf("Organizations.ListTeamRepos returned %+v, want %+v", members, want) - } -} - -func TestOrganizationsService_IsTeamRepo_true(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/repos/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeOrgPermissionRepo) - fmt.Fprint(w, `{"id":1}`) - }) - - repo, _, err := client.Organizations.IsTeamRepo(context.Background(), 1, "o", "r") - if err != nil { - t.Errorf("Organizations.IsTeamRepo returned error: %v", err) - } - - want := &Repository{ID: Int(1)} - if !reflect.DeepEqual(repo, want) { - t.Errorf("Organizations.IsTeamRepo returned %+v, want %+v", repo, want) - } -} - -func TestOrganizationsService_IsTeamRepo_false(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/repos/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - repo, resp, err := client.Organizations.IsTeamRepo(context.Background(), 1, "o", "r") - if err == nil { - t.Errorf("Expected HTTP 404 response") - } - if got, want := resp.Response.StatusCode, http.StatusNotFound; got != want { - t.Errorf("Organizations.IsTeamRepo returned status %d, want %d", got, want) - } - if repo != nil { - t.Errorf("Organizations.IsTeamRepo returned %+v, want nil", repo) - } -} - -func TestOrganizationsService_IsTeamRepo_error(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/repos/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - http.Error(w, "BadRequest", http.StatusBadRequest) - }) - - repo, resp, err := client.Organizations.IsTeamRepo(context.Background(), 1, "o", "r") - if err == nil { - t.Errorf("Expected HTTP 400 response") - } - if got, want := resp.Response.StatusCode, http.StatusBadRequest; got != want { - t.Errorf("Organizations.IsTeamRepo returned status %d, want %d", got, want) - } - if repo != nil { - t.Errorf("Organizations.IsTeamRepo returned %+v, want nil", repo) - } -} - -func TestOrganizationsService_IsTeamRepo_invalidOwner(t *testing.T) { - _, _, err := client.Organizations.IsTeamRepo(context.Background(), 1, "%", "r") - testURLParseError(t, err) -} - -func TestOrganizationsService_AddTeamRepo(t *testing.T) { - setup() - defer teardown() - - opt := &OrganizationAddTeamRepoOptions{Permission: "admin"} - - mux.HandleFunc("/teams/1/repos/o/r", func(w http.ResponseWriter, r *http.Request) { - v := new(OrganizationAddTeamRepoOptions) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PUT") - if !reflect.DeepEqual(v, opt) { - t.Errorf("Request body = %+v, want %+v", v, opt) - } - - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Organizations.AddTeamRepo(context.Background(), 1, "o", "r", opt) - if err != nil { - t.Errorf("Organizations.AddTeamRepo returned error: %v", err) - } -} - -func TestOrganizationsService_AddTeamRepo_noAccess(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/repos/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - w.WriteHeader(http.StatusUnprocessableEntity) - }) - - _, err := client.Organizations.AddTeamRepo(context.Background(), 1, "o", "r", nil) - if err == nil { - t.Errorf("Expcted error to be returned") - } -} - -func TestOrganizationsService_AddTeamRepo_invalidOwner(t *testing.T) { - _, err := client.Organizations.AddTeamRepo(context.Background(), 1, "%", "r", nil) - testURLParseError(t, err) -} - -func TestOrganizationsService_RemoveTeamRepo(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/repos/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Organizations.RemoveTeamRepo(context.Background(), 1, "o", "r") - if err != nil { - t.Errorf("Organizations.RemoveTeamRepo returned error: %v", err) - } -} - -func TestOrganizationsService_RemoveTeamRepo_invalidOwner(t *testing.T) { - _, err := client.Organizations.RemoveTeamRepo(context.Background(), 1, "%", "r") - testURLParseError(t, err) -} - -func TestOrganizationsService_GetTeamMembership(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/memberships/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"url":"u", "state":"active"}`) - }) - - membership, _, err := client.Organizations.GetTeamMembership(context.Background(), 1, "u") - if err != nil { - t.Errorf("Organizations.GetTeamMembership returned error: %v", err) - } - - want := &Membership{URL: String("u"), State: String("active")} - if !reflect.DeepEqual(membership, want) { - t.Errorf("Organizations.GetTeamMembership returned %+v, want %+v", membership, want) - } -} - -func TestOrganizationsService_AddTeamMembership(t *testing.T) { - setup() - defer teardown() - - opt := &OrganizationAddTeamMembershipOptions{Role: "maintainer"} - - mux.HandleFunc("/teams/1/memberships/u", func(w http.ResponseWriter, r *http.Request) { - v := new(OrganizationAddTeamMembershipOptions) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PUT") - if !reflect.DeepEqual(v, opt) { - t.Errorf("Request body = %+v, want %+v", v, opt) - } - - fmt.Fprint(w, `{"url":"u", "state":"pending"}`) - }) - - membership, _, err := client.Organizations.AddTeamMembership(context.Background(), 1, "u", opt) - if err != nil { - t.Errorf("Organizations.AddTeamMembership returned error: %v", err) - } - - want := &Membership{URL: String("u"), State: String("pending")} - if !reflect.DeepEqual(membership, want) { - t.Errorf("Organizations.AddTeamMembership returned %+v, want %+v", membership, want) - } -} - -func TestOrganizationsService_RemoveTeamMembership(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/memberships/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Organizations.RemoveTeamMembership(context.Background(), 1, "u") - if err != nil { - t.Errorf("Organizations.RemoveTeamMembership returned error: %v", err) - } -} - -func TestOrganizationsService_ListUserTeams(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/teams", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "1"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 1} - teams, _, err := client.Organizations.ListUserTeams(context.Background(), opt) - if err != nil { - t.Errorf("Organizations.ListUserTeams returned error: %v", err) - } - - want := []*Team{{ID: Int(1)}} - if !reflect.DeepEqual(teams, want) { - t.Errorf("Organizations.ListUserTeams returned %+v, want %+v", teams, want) - } -} - -func TestOrganizationsService_ListPendingTeamInvitations(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/invitations", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "1"}) - fmt.Fprint(w, `[ - { - "id": 1, - "login": "monalisa", - "email": "octocat@github.com", - "role": "direct_member", - "created_at": "2017-01-21T00:00:00Z", - "inviter": { - "login": "other_user", - "id": 1, - "avatar_url": "https://github.com/images/error/other_user_happy.gif", - "gravatar_id": "", - "url": "https://api.github.com/users/other_user", - "html_url": "https://github.com/other_user", - "followers_url": "https://api.github.com/users/other_user/followers", - "following_url": "https://api.github.com/users/other_user/following/other_user", - "gists_url": "https://api.github.com/users/other_user/gists/gist_id", - "starred_url": "https://api.github.com/users/other_user/starred/owner/repo", - "subscriptions_url": "https://api.github.com/users/other_user/subscriptions", - "organizations_url": "https://api.github.com/users/other_user/orgs", - "repos_url": "https://api.github.com/users/other_user/repos", - "events_url": "https://api.github.com/users/other_user/events/privacy", - "received_events_url": "https://api.github.com/users/other_user/received_events/privacy", - "type": "User", - "site_admin": false - } - } - ]`) - }) - - opt := &ListOptions{Page: 1} - invitations, _, err := client.Organizations.ListPendingTeamInvitations(context.Background(), 1, opt) - if err != nil { - t.Errorf("Organizations.ListPendingTeamInvitations returned error: %v", err) - } - - createdAt := time.Date(2017, 01, 21, 0, 0, 0, 0, time.UTC) - want := []*Invitation{ - { - ID: Int(1), - Login: String("monalisa"), - Email: String("octocat@github.com"), - Role: String("direct_member"), - CreatedAt: &createdAt, - Inviter: &User{ - Login: String("other_user"), - ID: Int(1), - AvatarURL: String("https://github.com/images/error/other_user_happy.gif"), - GravatarID: String(""), - URL: String("https://api.github.com/users/other_user"), - HTMLURL: String("https://github.com/other_user"), - FollowersURL: String("https://api.github.com/users/other_user/followers"), - FollowingURL: String("https://api.github.com/users/other_user/following/other_user"), - GistsURL: String("https://api.github.com/users/other_user/gists/gist_id"), - StarredURL: String("https://api.github.com/users/other_user/starred/owner/repo"), - SubscriptionsURL: String("https://api.github.com/users/other_user/subscriptions"), - OrganizationsURL: String("https://api.github.com/users/other_user/orgs"), - ReposURL: String("https://api.github.com/users/other_user/repos"), - EventsURL: String("https://api.github.com/users/other_user/events/privacy"), - ReceivedEventsURL: String("https://api.github.com/users/other_user/received_events/privacy"), - Type: String("User"), - SiteAdmin: Bool(false), - }, - }} - - if !reflect.DeepEqual(invitations, want) { - t.Errorf("Organizations.ListPendingTeamInvitations returned %+v, want %+v", invitations, want) - } -} diff --git a/vendor/github.com/google/go-github/github/orgs_test.go b/vendor/github.com/google/go-github/github/orgs_test.go deleted file mode 100644 index f80c9496a80a..000000000000 --- a/vendor/github.com/google/go-github/github/orgs_test.go +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestOrganizationsService_ListAll(t *testing.T) { - setup() - defer teardown() - - since := 1342004 - mux.HandleFunc("/organizations", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"since": "1342004"}) - fmt.Fprint(w, `[{"id":4314092}]`) - }) - - opt := &OrganizationsListOptions{Since: since} - orgs, _, err := client.Organizations.ListAll(context.Background(), opt) - if err != nil { - t.Errorf("Organizations.ListAll returned error: %v", err) - } - - want := []*Organization{{ID: Int(4314092)}} - if !reflect.DeepEqual(orgs, want) { - t.Errorf("Organizations.ListAll returned %+v, want %+v", orgs, want) - } -} - -func TestOrganizationsService_List_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/orgs", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":1},{"id":2}]`) - }) - - orgs, _, err := client.Organizations.List(context.Background(), "", nil) - if err != nil { - t.Errorf("Organizations.List returned error: %v", err) - } - - want := []*Organization{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(orgs, want) { - t.Errorf("Organizations.List returned %+v, want %+v", orgs, want) - } -} - -func TestOrganizationsService_List_specifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/orgs", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1},{"id":2}]`) - }) - - opt := &ListOptions{Page: 2} - orgs, _, err := client.Organizations.List(context.Background(), "u", opt) - if err != nil { - t.Errorf("Organizations.List returned error: %v", err) - } - - want := []*Organization{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(orgs, want) { - t.Errorf("Organizations.List returned %+v, want %+v", orgs, want) - } -} - -func TestOrganizationsService_List_invalidUser(t *testing.T) { - _, _, err := client.Organizations.List(context.Background(), "%", nil) - testURLParseError(t, err) -} - -func TestOrganizationsService_Get(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1, "login":"l", "url":"u", "avatar_url": "a", "location":"l"}`) - }) - - org, _, err := client.Organizations.Get(context.Background(), "o") - if err != nil { - t.Errorf("Organizations.Get returned error: %v", err) - } - - want := &Organization{ID: Int(1), Login: String("l"), URL: String("u"), AvatarURL: String("a"), Location: String("l")} - if !reflect.DeepEqual(org, want) { - t.Errorf("Organizations.Get returned %+v, want %+v", org, want) - } -} - -func TestOrganizationsService_Get_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.Get(context.Background(), "%") - testURLParseError(t, err) -} - -func TestOrganizationsService_Edit(t *testing.T) { - setup() - defer teardown() - - input := &Organization{Login: String("l")} - - mux.HandleFunc("/orgs/o", func(w http.ResponseWriter, r *http.Request) { - v := new(Organization) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - org, _, err := client.Organizations.Edit(context.Background(), "o", input) - if err != nil { - t.Errorf("Organizations.Edit returned error: %v", err) - } - - want := &Organization{ID: Int(1)} - if !reflect.DeepEqual(org, want) { - t.Errorf("Organizations.Edit returned %+v, want %+v", org, want) - } -} - -func TestOrganizationsService_Edit_invalidOrg(t *testing.T) { - _, _, err := client.Organizations.Edit(context.Background(), "%", nil) - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/orgs_users_blocking_test.go b/vendor/github.com/google/go-github/github/orgs_users_blocking_test.go deleted file mode 100644 index 53be507ef215..000000000000 --- a/vendor/github.com/google/go-github/github/orgs_users_blocking_test.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestOrganizationsService_ListBlockedUsers(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/blocks", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeBlockUsersPreview) - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{ - "login": "octocat" - }]`) - }) - - opt := &ListOptions{Page: 2} - blockedUsers, _, err := client.Organizations.ListBlockedUsers(context.Background(), "o", opt) - if err != nil { - t.Errorf("Organizations.ListBlockedUsers returned error: %v", err) - } - - want := []*User{{Login: String("octocat")}} - if !reflect.DeepEqual(blockedUsers, want) { - t.Errorf("Organizations.ListBlockedUsers returned %+v, want %+v", blockedUsers, want) - } -} - -func TestOrganizationsService_IsBlocked(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/blocks/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeBlockUsersPreview) - w.WriteHeader(http.StatusNoContent) - }) - - isBlocked, _, err := client.Organizations.IsBlocked(context.Background(), "o", "u") - if err != nil { - t.Errorf("Organizations.IsBlocked returned error: %v", err) - } - if want := true; isBlocked != want { - t.Errorf("Organizations.IsBlocked returned %+v, want %+v", isBlocked, want) - } -} - -func TestOrganizationsService_BlockUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/blocks/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - testHeader(t, r, "Accept", mediaTypeBlockUsersPreview) - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Organizations.BlockUser(context.Background(), "o", "u") - if err != nil { - t.Errorf("Organizations.BlockUser returned error: %v", err) - } -} - -func TestOrganizationsService_UnblockUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/blocks/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - testHeader(t, r, "Accept", mediaTypeBlockUsersPreview) - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Organizations.UnblockUser(context.Background(), "o", "u") - if err != nil { - t.Errorf("Organizations.UnblockUser returned error: %v", err) - } -} diff --git a/vendor/github.com/google/go-github/github/projects_test.go b/vendor/github.com/google/go-github/github/projects_test.go deleted file mode 100644 index 1045ca9befa6..000000000000 --- a/vendor/github.com/google/go-github/github/projects_test.go +++ /dev/null @@ -1,371 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestProjectsService_UpdateProject(t *testing.T) { - setup() - defer teardown() - - input := &ProjectOptions{Name: "Project Name", Body: "Project body."} - - mux.HandleFunc("/projects/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PATCH") - testHeader(t, r, "Accept", mediaTypeProjectsPreview) - - v := &ProjectOptions{} - json.NewDecoder(r.Body).Decode(v) - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - project, _, err := client.Projects.UpdateProject(context.Background(), 1, input) - if err != nil { - t.Errorf("Projects.UpdateProject returned error: %v", err) - } - - want := &Project{ID: Int(1)} - if !reflect.DeepEqual(project, want) { - t.Errorf("Projects.UpdateProject returned %+v, want %+v", project, want) - } -} - -func TestProjectsService_GetProject(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/projects/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeProjectsPreview) - fmt.Fprint(w, `{"id":1}`) - }) - - project, _, err := client.Projects.GetProject(context.Background(), 1) - if err != nil { - t.Errorf("Projects.GetProject returned error: %v", err) - } - - want := &Project{ID: Int(1)} - if !reflect.DeepEqual(project, want) { - t.Errorf("Projects.GetProject returned %+v, want %+v", project, want) - } -} - -func TestProjectsService_DeleteProject(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/projects/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - testHeader(t, r, "Accept", mediaTypeProjectsPreview) - }) - - _, err := client.Projects.DeleteProject(context.Background(), 1) - if err != nil { - t.Errorf("Projects.DeleteProject returned error: %v", err) - } -} - -func TestProjectsService_ListProjectColumns(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/projects/1/columns", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeProjectsPreview) - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - columns, _, err := client.Projects.ListProjectColumns(context.Background(), 1, opt) - if err != nil { - t.Errorf("Projects.ListProjectColumns returned error: %v", err) - } - - want := []*ProjectColumn{{ID: Int(1)}} - if !reflect.DeepEqual(columns, want) { - t.Errorf("Projects.ListProjectColumns returned %+v, want %+v", columns, want) - } -} - -func TestProjectsService_GetProjectColumn(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/projects/columns/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeProjectsPreview) - fmt.Fprint(w, `{"id":1}`) - }) - - column, _, err := client.Projects.GetProjectColumn(context.Background(), 1) - if err != nil { - t.Errorf("Projects.GetProjectColumn returned error: %v", err) - } - - want := &ProjectColumn{ID: Int(1)} - if !reflect.DeepEqual(column, want) { - t.Errorf("Projects.GetProjectColumn returned %+v, want %+v", column, want) - } -} - -func TestProjectsService_CreateProjectColumn(t *testing.T) { - setup() - defer teardown() - - input := &ProjectColumnOptions{Name: "Column Name"} - - mux.HandleFunc("/projects/1/columns", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testHeader(t, r, "Accept", mediaTypeProjectsPreview) - - v := &ProjectColumnOptions{} - json.NewDecoder(r.Body).Decode(v) - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - column, _, err := client.Projects.CreateProjectColumn(context.Background(), 1, input) - if err != nil { - t.Errorf("Projects.CreateProjectColumn returned error: %v", err) - } - - want := &ProjectColumn{ID: Int(1)} - if !reflect.DeepEqual(column, want) { - t.Errorf("Projects.CreateProjectColumn returned %+v, want %+v", column, want) - } -} - -func TestProjectsService_UpdateProjectColumn(t *testing.T) { - setup() - defer teardown() - - input := &ProjectColumnOptions{Name: "Column Name"} - - mux.HandleFunc("/projects/columns/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PATCH") - testHeader(t, r, "Accept", mediaTypeProjectsPreview) - - v := &ProjectColumnOptions{} - json.NewDecoder(r.Body).Decode(v) - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - column, _, err := client.Projects.UpdateProjectColumn(context.Background(), 1, input) - if err != nil { - t.Errorf("Projects.UpdateProjectColumn returned error: %v", err) - } - - want := &ProjectColumn{ID: Int(1)} - if !reflect.DeepEqual(column, want) { - t.Errorf("Projects.UpdateProjectColumn returned %+v, want %+v", column, want) - } -} - -func TestProjectsService_DeleteProjectColumn(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/projects/columns/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - testHeader(t, r, "Accept", mediaTypeProjectsPreview) - }) - - _, err := client.Projects.DeleteProjectColumn(context.Background(), 1) - if err != nil { - t.Errorf("Projects.DeleteProjectColumn returned error: %v", err) - } -} - -func TestProjectsService_MoveProjectColumn(t *testing.T) { - setup() - defer teardown() - - input := &ProjectColumnMoveOptions{Position: "after:12345"} - - mux.HandleFunc("/projects/columns/1/moves", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testHeader(t, r, "Accept", mediaTypeProjectsPreview) - - v := &ProjectColumnMoveOptions{} - json.NewDecoder(r.Body).Decode(v) - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - }) - - _, err := client.Projects.MoveProjectColumn(context.Background(), 1, input) - if err != nil { - t.Errorf("Projects.MoveProjectColumn returned error: %v", err) - } -} - -func TestProjectsService_ListProjectCards(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/projects/columns/1/cards", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeProjectsPreview) - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - cards, _, err := client.Projects.ListProjectCards(context.Background(), 1, opt) - if err != nil { - t.Errorf("Projects.ListProjectCards returned error: %v", err) - } - - want := []*ProjectCard{{ID: Int(1)}} - if !reflect.DeepEqual(cards, want) { - t.Errorf("Projects.ListProjectCards returned %+v, want %+v", cards, want) - } -} - -func TestProjectsService_GetProjectCard(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/projects/columns/cards/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeProjectsPreview) - fmt.Fprint(w, `{"id":1}`) - }) - - card, _, err := client.Projects.GetProjectCard(context.Background(), 1) - if err != nil { - t.Errorf("Projects.GetProjectCard returned error: %v", err) - } - - want := &ProjectCard{ID: Int(1)} - if !reflect.DeepEqual(card, want) { - t.Errorf("Projects.GetProjectCard returned %+v, want %+v", card, want) - } -} - -func TestProjectsService_CreateProjectCard(t *testing.T) { - setup() - defer teardown() - - input := &ProjectCardOptions{ - ContentID: 12345, - ContentType: "Issue", - } - - mux.HandleFunc("/projects/columns/1/cards", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testHeader(t, r, "Accept", mediaTypeProjectsPreview) - - v := &ProjectCardOptions{} - json.NewDecoder(r.Body).Decode(v) - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - card, _, err := client.Projects.CreateProjectCard(context.Background(), 1, input) - if err != nil { - t.Errorf("Projects.CreateProjectCard returned error: %v", err) - } - - want := &ProjectCard{ID: Int(1)} - if !reflect.DeepEqual(card, want) { - t.Errorf("Projects.CreateProjectCard returned %+v, want %+v", card, want) - } -} - -func TestProjectsService_UpdateProjectCard(t *testing.T) { - setup() - defer teardown() - - input := &ProjectCardOptions{ - ContentID: 12345, - ContentType: "Issue", - } - - mux.HandleFunc("/projects/columns/cards/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PATCH") - testHeader(t, r, "Accept", mediaTypeProjectsPreview) - - v := &ProjectCardOptions{} - json.NewDecoder(r.Body).Decode(v) - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - card, _, err := client.Projects.UpdateProjectCard(context.Background(), 1, input) - if err != nil { - t.Errorf("Projects.UpdateProjectCard returned error: %v", err) - } - - want := &ProjectCard{ID: Int(1)} - if !reflect.DeepEqual(card, want) { - t.Errorf("Projects.UpdateProjectCard returned %+v, want %+v", card, want) - } -} - -func TestProjectsService_DeleteProjectCard(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/projects/columns/cards/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - testHeader(t, r, "Accept", mediaTypeProjectsPreview) - }) - - _, err := client.Projects.DeleteProjectCard(context.Background(), 1) - if err != nil { - t.Errorf("Projects.DeleteProjectCard returned error: %v", err) - } -} - -func TestProjectsService_MoveProjectCard(t *testing.T) { - setup() - defer teardown() - - input := &ProjectCardMoveOptions{Position: "after:12345"} - - mux.HandleFunc("/projects/columns/cards/1/moves", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testHeader(t, r, "Accept", mediaTypeProjectsPreview) - - v := &ProjectCardMoveOptions{} - json.NewDecoder(r.Body).Decode(v) - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - }) - - _, err := client.Projects.MoveProjectCard(context.Background(), 1, input) - if err != nil { - t.Errorf("Projects.MoveProjectCard returned error: %v", err) - } -} diff --git a/vendor/github.com/google/go-github/github/pulls_comments_test.go b/vendor/github.com/google/go-github/github/pulls_comments_test.go deleted file mode 100644 index e35b04f7b7b8..000000000000 --- a/vendor/github.com/google/go-github/github/pulls_comments_test.go +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestPullRequestsService_ListComments_allPulls(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/comments", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - testFormValues(t, r, values{ - "sort": "updated", - "direction": "desc", - "since": "2002-02-10T15:30:00Z", - "page": "2", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &PullRequestListCommentsOptions{ - Sort: "updated", - Direction: "desc", - Since: time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC), - ListOptions: ListOptions{Page: 2}, - } - pulls, _, err := client.PullRequests.ListComments(context.Background(), "o", "r", 0, opt) - if err != nil { - t.Errorf("PullRequests.ListComments returned error: %v", err) - } - - want := []*PullRequestComment{{ID: Int(1)}} - if !reflect.DeepEqual(pulls, want) { - t.Errorf("PullRequests.ListComments returned %+v, want %+v", pulls, want) - } -} - -func TestPullRequestsService_ListComments_specificPull(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1/comments", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - fmt.Fprint(w, `[{"id":1}]`) - }) - - pulls, _, err := client.PullRequests.ListComments(context.Background(), "o", "r", 1, nil) - if err != nil { - t.Errorf("PullRequests.ListComments returned error: %v", err) - } - - want := []*PullRequestComment{{ID: Int(1)}} - if !reflect.DeepEqual(pulls, want) { - t.Errorf("PullRequests.ListComments returned %+v, want %+v", pulls, want) - } -} - -func TestPullRequestsService_ListComments_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.ListComments(context.Background(), "%", "r", 1, nil) - testURLParseError(t, err) -} - -func TestPullRequestsService_GetComment(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/comments/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.PullRequests.GetComment(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("PullRequests.GetComment returned error: %v", err) - } - - want := &PullRequestComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("PullRequests.GetComment returned %+v, want %+v", comment, want) - } -} - -func TestPullRequestsService_GetComment_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.GetComment(context.Background(), "%", "r", 1) - testURLParseError(t, err) -} - -func TestPullRequestsService_CreateComment(t *testing.T) { - setup() - defer teardown() - - input := &PullRequestComment{Body: String("b")} - - mux.HandleFunc("/repos/o/r/pulls/1/comments", func(w http.ResponseWriter, r *http.Request) { - v := new(PullRequestComment) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.PullRequests.CreateComment(context.Background(), "o", "r", 1, input) - if err != nil { - t.Errorf("PullRequests.CreateComment returned error: %v", err) - } - - want := &PullRequestComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("PullRequests.CreateComment returned %+v, want %+v", comment, want) - } -} - -func TestPullRequestsService_CreateComment_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.CreateComment(context.Background(), "%", "r", 1, nil) - testURLParseError(t, err) -} - -func TestPullRequestsService_EditComment(t *testing.T) { - setup() - defer teardown() - - input := &PullRequestComment{Body: String("b")} - - mux.HandleFunc("/repos/o/r/pulls/comments/1", func(w http.ResponseWriter, r *http.Request) { - v := new(PullRequestComment) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.PullRequests.EditComment(context.Background(), "o", "r", 1, input) - if err != nil { - t.Errorf("PullRequests.EditComment returned error: %v", err) - } - - want := &PullRequestComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("PullRequests.EditComment returned %+v, want %+v", comment, want) - } -} - -func TestPullRequestsService_EditComment_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.EditComment(context.Background(), "%", "r", 1, nil) - testURLParseError(t, err) -} - -func TestPullRequestsService_DeleteComment(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/comments/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.PullRequests.DeleteComment(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("PullRequests.DeleteComment returned error: %v", err) - } -} - -func TestPullRequestsService_DeleteComment_invalidOwner(t *testing.T) { - _, err := client.PullRequests.DeleteComment(context.Background(), "%", "r", 1) - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/pulls_reviewers_test.go b/vendor/github.com/google/go-github/github/pulls_reviewers_test.go deleted file mode 100644 index a60f2e77b387..000000000000 --- a/vendor/github.com/google/go-github/github/pulls_reviewers_test.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRequestReviewers(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1/requested_reviewers", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testBody(t, r, `{"reviewers":["octocat","googlebot"]}`+"\n") - fmt.Fprint(w, `{"number":1}`) - }) - - // This returns a PR, unmarshalling of which is tested elsewhere - pull, _, err := client.PullRequests.RequestReviewers(context.Background(), "o", "r", 1, []string{"octocat", "googlebot"}) - if err != nil { - t.Errorf("PullRequests.RequestReviewers returned error: %v", err) - } - want := &PullRequest{Number: Int(1)} - if !reflect.DeepEqual(pull, want) { - t.Errorf("PullRequests.RequestReviewers returned %+v, want %+v", pull, want) - } -} - -func TestRemoveReviewers(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1/requested_reviewers", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - testBody(t, r, `{"reviewers":["octocat","googlebot"]}`+"\n") - }) - - _, err := client.PullRequests.RemoveReviewers(context.Background(), "o", "r", 1, []string{"octocat", "googlebot"}) - if err != nil { - t.Errorf("PullRequests.RemoveReviewers returned error: %v", err) - } -} - -func TestListReviewers(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1/requested_reviewers", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"login":"octocat","id":1}]`) - }) - - reviewers, _, err := client.PullRequests.ListReviewers(context.Background(), "o", "r", 1, nil) - if err != nil { - t.Errorf("PullRequests.ListReviewers returned error: %v", err) - } - - want := []*User{ - { - Login: String("octocat"), - ID: Int(1), - }, - } - if !reflect.DeepEqual(reviewers, want) { - t.Errorf("PullRequests.ListReviewers returned %+v, want %+v", reviewers, want) - } -} - -func TestListReviewers_withOptions(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1/requested_reviewers", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[]`) - }) - - _, _, err := client.PullRequests.ListReviewers(context.Background(), "o", "r", 1, &ListOptions{Page: 2}) - if err != nil { - t.Errorf("PullRequests.ListReviewers returned error: %v", err) - } -} diff --git a/vendor/github.com/google/go-github/github/pulls_reviews_test.go b/vendor/github.com/google/go-github/github/pulls_reviews_test.go deleted file mode 100644 index d72de4709b09..000000000000 --- a/vendor/github.com/google/go-github/github/pulls_reviews_test.go +++ /dev/null @@ -1,251 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestPullRequestsService_ListReviews(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1/reviews", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[{"id":1},{"id":2}]`) - }) - - opt := &ListOptions{Page: 2} - reviews, _, err := client.PullRequests.ListReviews(context.Background(), "o", "r", 1, opt) - if err != nil { - t.Errorf("PullRequests.ListReviews returned error: %v", err) - } - - want := []*PullRequestReview{ - {ID: Int(1)}, - {ID: Int(2)}, - } - if !reflect.DeepEqual(reviews, want) { - t.Errorf("PullRequests.ListReviews returned %+v, want %+v", reviews, want) - } -} - -func TestPullRequestsService_ListReviews_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.ListReviews(context.Background(), "%", "r", 1, nil) - testURLParseError(t, err) -} - -func TestPullRequestsService_GetReview(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1/reviews/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - review, _, err := client.PullRequests.GetReview(context.Background(), "o", "r", 1, 1) - if err != nil { - t.Errorf("PullRequests.GetReview returned error: %v", err) - } - - want := &PullRequestReview{ID: Int(1)} - if !reflect.DeepEqual(review, want) { - t.Errorf("PullRequests.GetReview returned %+v, want %+v", review, want) - } -} - -func TestPullRequestsService_GetReview_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.GetReview(context.Background(), "%", "r", 1, 1) - testURLParseError(t, err) -} - -func TestPullRequestsService_DeletePendingReview(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1/reviews/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - fmt.Fprint(w, `{"id":1}`) - }) - - review, _, err := client.PullRequests.DeletePendingReview(context.Background(), "o", "r", 1, 1) - if err != nil { - t.Errorf("PullRequests.DeletePendingReview returned error: %v", err) - } - - want := &PullRequestReview{ID: Int(1)} - if !reflect.DeepEqual(review, want) { - t.Errorf("PullRequests.DeletePendingReview returned %+v, want %+v", review, want) - } -} - -func TestPullRequestsService_DeletePendingReview_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.DeletePendingReview(context.Background(), "%", "r", 1, 1) - testURLParseError(t, err) -} - -func TestPullRequestsService_ListReviewComments(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1/reviews/1/comments", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":1},{"id":2}]`) - }) - - comments, _, err := client.PullRequests.ListReviewComments(context.Background(), "o", "r", 1, 1, nil) - if err != nil { - t.Errorf("PullRequests.ListReviewComments returned error: %v", err) - } - - want := []*PullRequestComment{ - {ID: Int(1)}, - {ID: Int(2)}, - } - if !reflect.DeepEqual(comments, want) { - t.Errorf("PullRequests.ListReviewComments returned %+v, want %+v", comments, want) - } -} - -func TestPullRequestsService_ListReviewComments_withOptions(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1/reviews/1/comments", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[]`) - }) - - _, _, err := client.PullRequests.ListReviewComments(context.Background(), "o", "r", 1, 1, &ListOptions{Page: 2}) - if err != nil { - t.Errorf("PullRequests.ListReviewComments returned error: %v", err) - } -} - -func TestPullRequestsService_ListReviewComments_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.ListReviewComments(context.Background(), "%", "r", 1, 1, nil) - testURLParseError(t, err) -} - -func TestPullRequestsService_CreateReview(t *testing.T) { - setup() - defer teardown() - - input := &PullRequestReviewRequest{ - Body: String("b"), - Event: String("APPROVE"), - } - - mux.HandleFunc("/repos/o/r/pulls/1/reviews", func(w http.ResponseWriter, r *http.Request) { - v := new(PullRequestReviewRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - review, _, err := client.PullRequests.CreateReview(context.Background(), "o", "r", 1, input) - if err != nil { - t.Errorf("PullRequests.CreateReview returned error: %v", err) - } - - want := &PullRequestReview{ID: Int(1)} - if !reflect.DeepEqual(review, want) { - t.Errorf("PullRequests.CreateReview returned %+v, want %+v", review, want) - } -} - -func TestPullRequestsService_CreateReview_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.CreateReview(context.Background(), "%", "r", 1, &PullRequestReviewRequest{}) - testURLParseError(t, err) -} - -func TestPullRequestsService_SubmitReview(t *testing.T) { - setup() - defer teardown() - - input := &PullRequestReviewRequest{ - Body: String("b"), - Event: String("APPROVE"), - } - - mux.HandleFunc("/repos/o/r/pulls/1/reviews/1/events", func(w http.ResponseWriter, r *http.Request) { - v := new(PullRequestReviewRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - review, _, err := client.PullRequests.SubmitReview(context.Background(), "o", "r", 1, 1, input) - if err != nil { - t.Errorf("PullRequests.SubmitReview returned error: %v", err) - } - - want := &PullRequestReview{ID: Int(1)} - if !reflect.DeepEqual(review, want) { - t.Errorf("PullRequests.SubmitReview returned %+v, want %+v", review, want) - } -} - -func TestPullRequestsService_SubmitReview_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.SubmitReview(context.Background(), "%", "r", 1, 1, &PullRequestReviewRequest{}) - testURLParseError(t, err) -} - -func TestPullRequestsService_DismissReview(t *testing.T) { - setup() - defer teardown() - - input := &PullRequestReviewDismissalRequest{Message: String("m")} - - mux.HandleFunc("/repos/o/r/pulls/1/reviews/1/dismissals", func(w http.ResponseWriter, r *http.Request) { - v := new(PullRequestReviewDismissalRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PUT") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - review, _, err := client.PullRequests.DismissReview(context.Background(), "o", "r", 1, 1, input) - if err != nil { - t.Errorf("PullRequests.DismissReview returned error: %v", err) - } - - want := &PullRequestReview{ID: Int(1)} - if !reflect.DeepEqual(review, want) { - t.Errorf("PullRequests.DismissReview returned %+v, want %+v", review, want) - } -} - -func TestPullRequestsService_DismissReview_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.DismissReview(context.Background(), "%", "r", 1, 1, &PullRequestReviewDismissalRequest{}) - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/pulls_test.go b/vendor/github.com/google/go-github/github/pulls_test.go deleted file mode 100644 index b45883141686..000000000000 --- a/vendor/github.com/google/go-github/github/pulls_test.go +++ /dev/null @@ -1,512 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "reflect" - "strings" - "testing" -) - -func TestPullRequestsService_List(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "state": "closed", - "head": "h", - "base": "b", - "sort": "created", - "direction": "desc", - "page": "2", - }) - fmt.Fprint(w, `[{"number":1}]`) - }) - - opt := &PullRequestListOptions{"closed", "h", "b", "created", "desc", ListOptions{Page: 2}} - pulls, _, err := client.PullRequests.List(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("PullRequests.List returned error: %v", err) - } - - want := []*PullRequest{{Number: Int(1)}} - if !reflect.DeepEqual(pulls, want) { - t.Errorf("PullRequests.List returned %+v, want %+v", pulls, want) - } -} - -func TestPullRequestsService_List_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.List(context.Background(), "%", "r", nil) - testURLParseError(t, err) -} - -func TestPullRequestsService_Get(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"number":1}`) - }) - - pull, _, err := client.PullRequests.Get(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("PullRequests.Get returned error: %v", err) - } - - want := &PullRequest{Number: Int(1)} - if !reflect.DeepEqual(pull, want) { - t.Errorf("PullRequests.Get returned %+v, want %+v", pull, want) - } -} - -func TestPullRequestsService_GetRawDiff(t *testing.T) { - setup() - defer teardown() - const rawStr = "@@diff content" - - mux.HandleFunc("/repos/o/r/pulls/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeV3Diff) - fmt.Fprint(w, rawStr) - }) - - ret, _, err := client.PullRequests.GetRaw(context.Background(), "o", "r", 1, RawOptions{Diff}) - if err != nil { - t.Fatalf("PullRequests.GetRaw returned error: %v", err) - } - - if ret != rawStr { - t.Errorf("PullRequests.GetRaw returned %s want %s", ret, rawStr) - } -} - -func TestPullRequestsService_GetRawPatch(t *testing.T) { - setup() - defer teardown() - const rawStr = "@@patch content" - - mux.HandleFunc("/repos/o/r/pulls/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeV3Patch) - fmt.Fprint(w, rawStr) - }) - - ret, _, err := client.PullRequests.GetRaw(context.Background(), "o", "r", 1, RawOptions{Patch}) - if err != nil { - t.Fatalf("PullRequests.GetRaw returned error: %v", err) - } - - if ret != rawStr { - t.Errorf("PullRequests.GetRaw returned %s want %s", ret, rawStr) - } -} - -func TestPullRequestsService_GetRawInvalid(t *testing.T) { - setup() - defer teardown() - - _, _, err := client.PullRequests.GetRaw(context.Background(), "o", "r", 1, RawOptions{100}) - if err == nil { - t.Fatal("PullRequests.GetRaw should return error") - } - if !strings.Contains(err.Error(), "unsupported raw type") { - t.Error("PullRequests.GetRaw should return unsupported raw type error") - } -} - -func TestPullRequestsService_Get_headAndBase(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"number":1,"head":{"ref":"r2","repo":{"id":2}},"base":{"ref":"r1","repo":{"id":1}}}`) - }) - - pull, _, err := client.PullRequests.Get(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("PullRequests.Get returned error: %v", err) - } - - want := &PullRequest{ - Number: Int(1), - Head: &PullRequestBranch{ - Ref: String("r2"), - Repo: &Repository{ID: Int(2)}, - }, - Base: &PullRequestBranch{ - Ref: String("r1"), - Repo: &Repository{ID: Int(1)}, - }, - } - if !reflect.DeepEqual(pull, want) { - t.Errorf("PullRequests.Get returned %+v, want %+v", pull, want) - } -} - -func TestPullRequestsService_Get_urlFields(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"number":1, - "url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347", - "html_url": "https://github.com/octocat/Hello-World/pull/1347", - "issue_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347", - "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", - "diff_url": "https://github.com/octocat/Hello-World/pull/1347.diff", - "patch_url": "https://github.com/octocat/Hello-World/pull/1347.patch", - "review_comments_url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments", - "review_comment_url": "https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number}"}`) - }) - - pull, _, err := client.PullRequests.Get(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("PullRequests.Get returned error: %v", err) - } - - want := &PullRequest{ - Number: Int(1), - URL: String("https://api.github.com/repos/octocat/Hello-World/pulls/1347"), - HTMLURL: String("https://github.com/octocat/Hello-World/pull/1347"), - IssueURL: String("https://api.github.com/repos/octocat/Hello-World/issues/1347"), - StatusesURL: String("https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e"), - DiffURL: String("https://github.com/octocat/Hello-World/pull/1347.diff"), - PatchURL: String("https://github.com/octocat/Hello-World/pull/1347.patch"), - ReviewCommentsURL: String("https://api.github.com/repos/octocat/Hello-World/pulls/1347/comments"), - ReviewCommentURL: String("https://api.github.com/repos/octocat/Hello-World/pulls/comments{/number}"), - } - - if !reflect.DeepEqual(pull, want) { - t.Errorf("PullRequests.Get returned %+v, want %+v", pull, want) - } -} - -func TestPullRequestsService_Get_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.Get(context.Background(), "%", "r", 1) - testURLParseError(t, err) -} - -func TestPullRequestsService_Create(t *testing.T) { - setup() - defer teardown() - - input := &NewPullRequest{Title: String("t")} - - mux.HandleFunc("/repos/o/r/pulls", func(w http.ResponseWriter, r *http.Request) { - v := new(NewPullRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"number":1}`) - }) - - pull, _, err := client.PullRequests.Create(context.Background(), "o", "r", input) - if err != nil { - t.Errorf("PullRequests.Create returned error: %v", err) - } - - want := &PullRequest{Number: Int(1)} - if !reflect.DeepEqual(pull, want) { - t.Errorf("PullRequests.Create returned %+v, want %+v", pull, want) - } -} - -func TestPullRequestsService_Create_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.Create(context.Background(), "%", "r", nil) - testURLParseError(t, err) -} - -func TestPullRequestsService_Edit(t *testing.T) { - setup() - defer teardown() - - tests := []struct { - input *PullRequest - sendResponse string - - wantUpdate string - want *PullRequest - }{ - { - input: &PullRequest{Title: String("t")}, - sendResponse: `{"number":1}`, - wantUpdate: `{"title":"t"}`, - want: &PullRequest{Number: Int(1)}, - }, - { - // base update - input: &PullRequest{Base: &PullRequestBranch{Ref: String("master")}}, - sendResponse: `{"number":1,"base":{"ref":"master"}}`, - wantUpdate: `{"base":"master"}`, - want: &PullRequest{ - Number: Int(1), - Base: &PullRequestBranch{Ref: String("master")}, - }, - }, - } - - for i, tt := range tests { - madeRequest := false - mux.HandleFunc(fmt.Sprintf("/repos/o/r/pulls/%v", i), func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PATCH") - testBody(t, r, tt.wantUpdate+"\n") - io.WriteString(w, tt.sendResponse) - madeRequest = true - }) - - pull, _, err := client.PullRequests.Edit(context.Background(), "o", "r", i, tt.input) - if err != nil { - t.Errorf("%d: PullRequests.Edit returned error: %v", i, err) - } - - if !reflect.DeepEqual(pull, tt.want) { - t.Errorf("%d: PullRequests.Edit returned %+v, want %+v", i, pull, tt.want) - } - - if !madeRequest { - t.Errorf("%d: PullRequest.Edit did not make the expected request", i) - } - } -} - -func TestPullRequestsService_Edit_invalidOwner(t *testing.T) { - _, _, err := client.PullRequests.Edit(context.Background(), "%", "r", 1, &PullRequest{}) - testURLParseError(t, err) -} - -func TestPullRequestsService_ListCommits(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1/commits", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, ` - [ - { - "sha": "3", - "parents": [ - { - "sha": "2" - } - ] - }, - { - "sha": "2", - "parents": [ - { - "sha": "1" - } - ] - } - ]`) - }) - - opt := &ListOptions{Page: 2} - commits, _, err := client.PullRequests.ListCommits(context.Background(), "o", "r", 1, opt) - if err != nil { - t.Errorf("PullRequests.ListCommits returned error: %v", err) - } - - want := []*RepositoryCommit{ - { - SHA: String("3"), - Parents: []Commit{ - { - SHA: String("2"), - }, - }, - }, - { - SHA: String("2"), - Parents: []Commit{ - { - SHA: String("1"), - }, - }, - }, - } - if !reflect.DeepEqual(commits, want) { - t.Errorf("PullRequests.ListCommits returned %+v, want %+v", commits, want) - } -} - -func TestPullRequestsService_ListFiles(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1/files", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, ` - [ - { - "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", - "filename": "file1.txt", - "status": "added", - "additions": 103, - "deletions": 21, - "changes": 124, - "patch": "@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test" - }, - { - "sha": "f61aebed695e2e4193db5e6dcb09b5b57875f334", - "filename": "file2.txt", - "status": "modified", - "additions": 5, - "deletions": 3, - "changes": 103, - "patch": "@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test" - } - ]`) - }) - - opt := &ListOptions{Page: 2} - commitFiles, _, err := client.PullRequests.ListFiles(context.Background(), "o", "r", 1, opt) - if err != nil { - t.Errorf("PullRequests.ListFiles returned error: %v", err) - } - - want := []*CommitFile{ - { - SHA: String("6dcb09b5b57875f334f61aebed695e2e4193db5e"), - Filename: String("file1.txt"), - Additions: Int(103), - Deletions: Int(21), - Changes: Int(124), - Status: String("added"), - Patch: String("@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test"), - }, - { - SHA: String("f61aebed695e2e4193db5e6dcb09b5b57875f334"), - Filename: String("file2.txt"), - Additions: Int(5), - Deletions: Int(3), - Changes: Int(103), - Status: String("modified"), - Patch: String("@@ -132,7 +132,7 @@ module Test @@ -1000,7 +1000,7 @@ module Test"), - }, - } - - if !reflect.DeepEqual(commitFiles, want) { - t.Errorf("PullRequests.ListFiles returned %+v, want %+v", commitFiles, want) - } -} - -func TestPullRequestsService_IsMerged(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1/merge", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNoContent) - }) - - isMerged, _, err := client.PullRequests.IsMerged(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("PullRequests.IsMerged returned error: %v", err) - } - - want := true - if !reflect.DeepEqual(isMerged, want) { - t.Errorf("PullRequests.IsMerged returned %+v, want %+v", isMerged, want) - } -} - -func TestPullRequestsService_Merge(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/1/merge", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - testHeader(t, r, "Accept", mediaTypeSquashPreview) - fmt.Fprint(w, ` - { - "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", - "merged": true, - "message": "Pull Request successfully merged" - }`) - }) - - options := &PullRequestOptions{MergeMethod: "rebase"} - merge, _, err := client.PullRequests.Merge(context.Background(), "o", "r", 1, "merging pull request", options) - if err != nil { - t.Errorf("PullRequests.Merge returned error: %v", err) - } - - want := &PullRequestMergeResult{ - SHA: String("6dcb09b5b57875f334f61aebed695e2e4193db5e"), - Merged: Bool(true), - Message: String("Pull Request successfully merged"), - } - if !reflect.DeepEqual(merge, want) { - t.Errorf("PullRequests.Merge returned %+v, want %+v", merge, want) - } -} - -// Test that different merge options produce expected PUT requests. See issue https://github.com/google/go-github/issues/500. -func TestPullRequestsService_Merge_options(t *testing.T) { - setup() - defer teardown() - - tests := []struct { - options *PullRequestOptions - wantBody string - }{ - { - options: nil, - wantBody: `{"commit_message":"merging pull request"}`, - }, - { - options: &PullRequestOptions{}, - wantBody: `{"commit_message":"merging pull request"}`, - }, - { - options: &PullRequestOptions{MergeMethod: "rebase"}, - wantBody: `{"commit_message":"merging pull request","merge_method":"rebase"}`, - }, - { - options: &PullRequestOptions{SHA: "6dcb09b5b57875f334f61aebed695e2e4193db5e"}, - wantBody: `{"commit_message":"merging pull request","sha":"6dcb09b5b57875f334f61aebed695e2e4193db5e"}`, - }, - { - options: &PullRequestOptions{ - CommitTitle: "Extra detail", - SHA: "6dcb09b5b57875f334f61aebed695e2e4193db5e", - MergeMethod: "squash", - }, - wantBody: `{"commit_message":"merging pull request","commit_title":"Extra detail","merge_method":"squash","sha":"6dcb09b5b57875f334f61aebed695e2e4193db5e"}`, - }, - } - - for i, test := range tests { - madeRequest := false - mux.HandleFunc(fmt.Sprintf("/repos/o/r/pulls/%d/merge", i), func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - testHeader(t, r, "Accept", mediaTypeSquashPreview) - testBody(t, r, test.wantBody+"\n") - madeRequest = true - }) - _, _, _ = client.PullRequests.Merge(context.Background(), "o", "r", i, "merging pull request", test.options) - if !madeRequest { - t.Errorf("%d: PullRequests.Merge(%#v): expected request was not made", i, test.options) - } - } -} diff --git a/vendor/github.com/google/go-github/github/reactions_test.go b/vendor/github.com/google/go-github/github/reactions_test.go deleted file mode 100644 index 2725298279ed..000000000000 --- a/vendor/github.com/google/go-github/github/reactions_test.go +++ /dev/null @@ -1,201 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "net/http" - "reflect" - "testing" -) - -func TestReactionsService_ListCommentReactions(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/comments/1/reactions", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - - w.WriteHeader(http.StatusOK) - w.Write([]byte(`[{"id":1,"user":{"login":"l","id":2},"content":"+1"}]`)) - }) - - got, _, err := client.Reactions.ListCommentReactions(context.Background(), "o", "r", 1, nil) - if err != nil { - t.Errorf("ListCommentReactions returned error: %v", err) - } - if want := []*Reaction{{ID: Int(1), User: &User{Login: String("l"), ID: Int(2)}, Content: String("+1")}}; !reflect.DeepEqual(got, want) { - t.Errorf("ListCommentReactions = %+v, want %+v", got, want) - } -} - -func TestReactionsService_CreateCommentReaction(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/comments/1/reactions", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - - w.WriteHeader(http.StatusCreated) - w.Write([]byte(`{"id":1,"user":{"login":"l","id":2},"content":"+1"}`)) - }) - - got, _, err := client.Reactions.CreateCommentReaction(context.Background(), "o", "r", 1, "+1") - if err != nil { - t.Errorf("CreateCommentReaction returned error: %v", err) - } - want := &Reaction{ID: Int(1), User: &User{Login: String("l"), ID: Int(2)}, Content: String("+1")} - if !reflect.DeepEqual(got, want) { - t.Errorf("CreateCommentReaction = %+v, want %+v", got, want) - } -} - -func TestReactionsService_ListIssueReactions(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/1/reactions", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - - w.WriteHeader(http.StatusOK) - w.Write([]byte(`[{"id":1,"user":{"login":"l","id":2},"content":"+1"}]`)) - }) - - got, _, err := client.Reactions.ListIssueReactions(context.Background(), "o", "r", 1, nil) - if err != nil { - t.Errorf("ListIssueReactions returned error: %v", err) - } - if want := []*Reaction{{ID: Int(1), User: &User{Login: String("l"), ID: Int(2)}, Content: String("+1")}}; !reflect.DeepEqual(got, want) { - t.Errorf("ListIssueReactions = %+v, want %+v", got, want) - } -} - -func TestReactionsService_CreateIssueReaction(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/1/reactions", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - - w.WriteHeader(http.StatusCreated) - w.Write([]byte(`{"id":1,"user":{"login":"l","id":2},"content":"+1"}`)) - }) - - got, _, err := client.Reactions.CreateIssueReaction(context.Background(), "o", "r", 1, "+1") - if err != nil { - t.Errorf("CreateIssueReaction returned error: %v", err) - } - want := &Reaction{ID: Int(1), User: &User{Login: String("l"), ID: Int(2)}, Content: String("+1")} - if !reflect.DeepEqual(got, want) { - t.Errorf("CreateIssueReaction = %+v, want %+v", got, want) - } -} - -func TestReactionsService_ListIssueCommentReactions(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/comments/1/reactions", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - - w.WriteHeader(http.StatusOK) - w.Write([]byte(`[{"id":1,"user":{"login":"l","id":2},"content":"+1"}]`)) - }) - - got, _, err := client.Reactions.ListIssueCommentReactions(context.Background(), "o", "r", 1, nil) - if err != nil { - t.Errorf("ListIssueCommentReactions returned error: %v", err) - } - if want := []*Reaction{{ID: Int(1), User: &User{Login: String("l"), ID: Int(2)}, Content: String("+1")}}; !reflect.DeepEqual(got, want) { - t.Errorf("ListIssueCommentReactions = %+v, want %+v", got, want) - } -} - -func TestReactionsService_CreateIssueCommentReaction(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/issues/comments/1/reactions", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - - w.WriteHeader(http.StatusCreated) - w.Write([]byte(`{"id":1,"user":{"login":"l","id":2},"content":"+1"}`)) - }) - - got, _, err := client.Reactions.CreateIssueCommentReaction(context.Background(), "o", "r", 1, "+1") - if err != nil { - t.Errorf("CreateIssueCommentReaction returned error: %v", err) - } - want := &Reaction{ID: Int(1), User: &User{Login: String("l"), ID: Int(2)}, Content: String("+1")} - if !reflect.DeepEqual(got, want) { - t.Errorf("CreateIssueCommentReaction = %+v, want %+v", got, want) - } -} - -func TestReactionsService_ListPullRequestCommentReactions(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/comments/1/reactions", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - - w.WriteHeader(http.StatusOK) - w.Write([]byte(`[{"id":1,"user":{"login":"l","id":2},"content":"+1"}]`)) - }) - - got, _, err := client.Reactions.ListPullRequestCommentReactions(context.Background(), "o", "r", 1, nil) - if err != nil { - t.Errorf("ListPullRequestCommentReactions returned error: %v", err) - } - if want := []*Reaction{{ID: Int(1), User: &User{Login: String("l"), ID: Int(2)}, Content: String("+1")}}; !reflect.DeepEqual(got, want) { - t.Errorf("ListPullRequestCommentReactions = %+v, want %+v", got, want) - } -} - -func TestReactionsService_CreatePullRequestCommentReaction(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pulls/comments/1/reactions", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - - w.WriteHeader(http.StatusCreated) - w.Write([]byte(`{"id":1,"user":{"login":"l","id":2},"content":"+1"}`)) - }) - - got, _, err := client.Reactions.CreatePullRequestCommentReaction(context.Background(), "o", "r", 1, "+1") - if err != nil { - t.Errorf("CreatePullRequestCommentReaction returned error: %v", err) - } - want := &Reaction{ID: Int(1), User: &User{Login: String("l"), ID: Int(2)}, Content: String("+1")} - if !reflect.DeepEqual(got, want) { - t.Errorf("CreatePullRequestCommentReaction = %+v, want %+v", got, want) - } -} - -func TestReactionsService_DeleteReaction(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/reactions/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - - w.WriteHeader(http.StatusNoContent) - }) - - if _, err := client.Reactions.DeleteReaction(context.Background(), 1); err != nil { - t.Errorf("DeleteReaction returned error: %v", err) - } -} diff --git a/vendor/github.com/google/go-github/github/repos_collaborators_test.go b/vendor/github.com/google/go-github/github/repos_collaborators_test.go deleted file mode 100644 index d2e125cb8bfe..000000000000 --- a/vendor/github.com/google/go-github/github/repos_collaborators_test.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_ListCollaborators(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/collaborators", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprintf(w, `[{"id":1}, {"id":2}]`) - }) - - opt := &ListOptions{Page: 2} - users, _, err := client.Repositories.ListCollaborators(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListCollaborators returned error: %v", err) - } - - want := []*User{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(users, want) { - t.Errorf("Repositories.ListCollaborators returned %+v, want %+v", users, want) - } -} - -func TestRepositoriesService_ListCollaborators_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.ListCollaborators(context.Background(), "%", "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_IsCollaborator_True(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/collaborators/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNoContent) - }) - - isCollab, _, err := client.Repositories.IsCollaborator(context.Background(), "o", "r", "u") - if err != nil { - t.Errorf("Repositories.IsCollaborator returned error: %v", err) - } - - if !isCollab { - t.Errorf("Repositories.IsCollaborator returned false, want true") - } -} - -func TestRepositoriesService_IsCollaborator_False(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/collaborators/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - isCollab, _, err := client.Repositories.IsCollaborator(context.Background(), "o", "r", "u") - if err != nil { - t.Errorf("Repositories.IsCollaborator returned error: %v", err) - } - - if isCollab { - t.Errorf("Repositories.IsCollaborator returned true, want false") - } -} - -func TestRepositoriesService_IsCollaborator_invalidUser(t *testing.T) { - _, _, err := client.Repositories.IsCollaborator(context.Background(), "%", "%", "%") - testURLParseError(t, err) -} - -func TestRepositoryService_GetPermissionLevel(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/collaborators/u/permission", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprintf(w, `{"permission":"admin","user":{"login":"u"}}`) - }) - - rpl, _, err := client.Repositories.GetPermissionLevel(context.Background(), "o", "r", "u") - if err != nil { - t.Errorf("Repositories.GetPermissionLevel returned error: %v", err) - } - - want := &RepositoryPermissionLevel{ - Permission: String("admin"), - User: &User{ - Login: String("u"), - }, - } - - if !reflect.DeepEqual(rpl, want) { - t.Errorf("Repositories.GetPermissionLevel returned %+v, want %+v", rpl, want) - } -} - -func TestRepositoriesService_AddCollaborator(t *testing.T) { - setup() - defer teardown() - - opt := &RepositoryAddCollaboratorOptions{Permission: "admin"} - - mux.HandleFunc("/repos/o/r/collaborators/u", func(w http.ResponseWriter, r *http.Request) { - v := new(RepositoryAddCollaboratorOptions) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PUT") - testHeader(t, r, "Accept", mediaTypeRepositoryInvitationsPreview) - if !reflect.DeepEqual(v, opt) { - t.Errorf("Request body = %+v, want %+v", v, opt) - } - - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Repositories.AddCollaborator(context.Background(), "o", "r", "u", opt) - if err != nil { - t.Errorf("Repositories.AddCollaborator returned error: %v", err) - } -} - -func TestRepositoriesService_AddCollaborator_invalidUser(t *testing.T) { - _, err := client.Repositories.AddCollaborator(context.Background(), "%", "%", "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_RemoveCollaborator(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/collaborators/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Repositories.RemoveCollaborator(context.Background(), "o", "r", "u") - if err != nil { - t.Errorf("Repositories.RemoveCollaborator returned error: %v", err) - } -} - -func TestRepositoriesService_RemoveCollaborator_invalidUser(t *testing.T) { - _, err := client.Repositories.RemoveCollaborator(context.Background(), "%", "%", "%") - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/repos_comments_test.go b/vendor/github.com/google/go-github/github/repos_comments_test.go deleted file mode 100644 index 249a37a36772..000000000000 --- a/vendor/github.com/google/go-github/github/repos_comments_test.go +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_ListComments(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/comments", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}, {"id":2}]`) - }) - - opt := &ListOptions{Page: 2} - comments, _, err := client.Repositories.ListComments(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListComments returned error: %v", err) - } - - want := []*RepositoryComment{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(comments, want) { - t.Errorf("Repositories.ListComments returned %+v, want %+v", comments, want) - } -} - -func TestRepositoriesService_ListComments_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.ListComments(context.Background(), "%", "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_ListCommitComments(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/commits/s/comments", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}, {"id":2}]`) - }) - - opt := &ListOptions{Page: 2} - comments, _, err := client.Repositories.ListCommitComments(context.Background(), "o", "r", "s", opt) - if err != nil { - t.Errorf("Repositories.ListCommitComments returned error: %v", err) - } - - want := []*RepositoryComment{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(comments, want) { - t.Errorf("Repositories.ListCommitComments returned %+v, want %+v", comments, want) - } -} - -func TestRepositoriesService_ListCommitComments_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.ListCommitComments(context.Background(), "%", "%", "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_CreateComment(t *testing.T) { - setup() - defer teardown() - - input := &RepositoryComment{Body: String("b")} - - mux.HandleFunc("/repos/o/r/commits/s/comments", func(w http.ResponseWriter, r *http.Request) { - v := new(RepositoryComment) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.Repositories.CreateComment(context.Background(), "o", "r", "s", input) - if err != nil { - t.Errorf("Repositories.CreateComment returned error: %v", err) - } - - want := &RepositoryComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("Repositories.CreateComment returned %+v, want %+v", comment, want) - } -} - -func TestRepositoriesService_CreateComment_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.CreateComment(context.Background(), "%", "%", "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_GetComment(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/comments/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeReactionsPreview) - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.Repositories.GetComment(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Repositories.GetComment returned error: %v", err) - } - - want := &RepositoryComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("Repositories.GetComment returned %+v, want %+v", comment, want) - } -} - -func TestRepositoriesService_GetComment_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.GetComment(context.Background(), "%", "%", 1) - testURLParseError(t, err) -} - -func TestRepositoriesService_UpdateComment(t *testing.T) { - setup() - defer teardown() - - input := &RepositoryComment{Body: String("b")} - - mux.HandleFunc("/repos/o/r/comments/1", func(w http.ResponseWriter, r *http.Request) { - v := new(RepositoryComment) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - comment, _, err := client.Repositories.UpdateComment(context.Background(), "o", "r", 1, input) - if err != nil { - t.Errorf("Repositories.UpdateComment returned error: %v", err) - } - - want := &RepositoryComment{ID: Int(1)} - if !reflect.DeepEqual(comment, want) { - t.Errorf("Repositories.UpdateComment returned %+v, want %+v", comment, want) - } -} - -func TestRepositoriesService_UpdateComment_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.UpdateComment(context.Background(), "%", "%", 1, nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_DeleteComment(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/comments/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Repositories.DeleteComment(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Repositories.DeleteComment returned error: %v", err) - } -} - -func TestRepositoriesService_DeleteComment_invalidOwner(t *testing.T) { - _, err := client.Repositories.DeleteComment(context.Background(), "%", "%", 1) - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/repos_commits_test.go b/vendor/github.com/google/go-github/github/repos_commits_test.go deleted file mode 100644 index 7790a334bf7c..000000000000 --- a/vendor/github.com/google/go-github/github/repos_commits_test.go +++ /dev/null @@ -1,266 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestRepositoriesService_ListCommits(t *testing.T) { - setup() - defer teardown() - - // given - mux.HandleFunc("/repos/o/r/commits", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, - values{ - "sha": "s", - "path": "p", - "author": "a", - "since": "2013-08-01T00:00:00Z", - "until": "2013-09-03T00:00:00Z", - }) - fmt.Fprintf(w, `[{"sha": "s"}]`) - }) - - opt := &CommitsListOptions{ - SHA: "s", - Path: "p", - Author: "a", - Since: time.Date(2013, time.August, 1, 0, 0, 0, 0, time.UTC), - Until: time.Date(2013, time.September, 3, 0, 0, 0, 0, time.UTC), - } - commits, _, err := client.Repositories.ListCommits(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListCommits returned error: %v", err) - } - - want := []*RepositoryCommit{{SHA: String("s")}} - if !reflect.DeepEqual(commits, want) { - t.Errorf("Repositories.ListCommits returned %+v, want %+v", commits, want) - } -} - -func TestRepositoriesService_GetCommit(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/commits/s", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeGitSigningPreview) - fmt.Fprintf(w, `{ - "sha": "s", - "commit": { "message": "m" }, - "author": { "login": "l" }, - "committer": { "login": "l" }, - "parents": [ { "sha": "s" } ], - "stats": { "additions": 104, "deletions": 4, "total": 108 }, - "files": [ - { - "filename": "f", - "additions": 10, - "deletions": 2, - "changes": 12, - "status": "s", - "patch": "p", - "blob_url": "b", - "raw_url": "r", - "contents_url": "c" - } - ] - }`) - }) - - commit, _, err := client.Repositories.GetCommit(context.Background(), "o", "r", "s") - if err != nil { - t.Errorf("Repositories.GetCommit returned error: %v", err) - } - - want := &RepositoryCommit{ - SHA: String("s"), - Commit: &Commit{ - Message: String("m"), - }, - Author: &User{ - Login: String("l"), - }, - Committer: &User{ - Login: String("l"), - }, - Parents: []Commit{ - { - SHA: String("s"), - }, - }, - Stats: &CommitStats{ - Additions: Int(104), - Deletions: Int(4), - Total: Int(108), - }, - Files: []CommitFile{ - { - Filename: String("f"), - Additions: Int(10), - Deletions: Int(2), - Changes: Int(12), - Status: String("s"), - Patch: String("p"), - BlobURL: String("b"), - RawURL: String("r"), - ContentsURL: String("c"), - }, - }, - } - if !reflect.DeepEqual(commit, want) { - t.Errorf("Repositories.GetCommit returned \n%+v, want \n%+v", commit, want) - } -} - -func TestRepositoriesService_GetCommitSHA1(t *testing.T) { - setup() - defer teardown() - const sha1 = "01234abcde" - - mux.HandleFunc("/repos/o/r/commits/master", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeV3SHA) - - fmt.Fprintf(w, sha1) - }) - - got, _, err := client.Repositories.GetCommitSHA1(context.Background(), "o", "r", "master", "") - if err != nil { - t.Errorf("Repositories.GetCommitSHA1 returned error: %v", err) - } - - want := sha1 - if got != want { - t.Errorf("Repositories.GetCommitSHA1 = %v, want %v", got, want) - } - - mux.HandleFunc("/repos/o/r/commits/tag", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeV3SHA) - testHeader(t, r, "If-None-Match", `"`+sha1+`"`) - - w.WriteHeader(http.StatusNotModified) - }) - - got, _, err = client.Repositories.GetCommitSHA1(context.Background(), "o", "r", "tag", sha1) - if err == nil { - t.Errorf("Expected HTTP 304 response") - } - - want = "" - if got != want { - t.Errorf("Repositories.GetCommitSHA1 = %v, want %v", got, want) - } -} - -func TestRepositoriesService_CompareCommits(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/compare/b...h", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprintf(w, `{ - "base_commit": { - "sha": "s", - "commit": { - "author": { "name": "n" }, - "committer": { "name": "n" }, - "message": "m", - "tree": { "sha": "t" } - }, - "author": { "login": "l" }, - "committer": { "login": "l" }, - "parents": [ { "sha": "s" } ] - }, - "status": "s", - "ahead_by": 1, - "behind_by": 2, - "total_commits": 1, - "commits": [ - { - "sha": "s", - "commit": { "author": { "name": "n" } }, - "author": { "login": "l" }, - "committer": { "login": "l" }, - "parents": [ { "sha": "s" } ] - } - ], - "files": [ { "filename": "f" } ], - "html_url": "https://github.com/o/r/compare/b...h", - "permalink_url": "https://github.com/o/r/compare/o:bbcd538c8e72b8c175046e27cc8f907076331401...o:0328041d1152db8ae77652d1618a02e57f745f17", - "diff_url": "https://github.com/o/r/compare/b...h.diff", - "patch_url": "https://github.com/o/r/compare/b...h.patch", - "url": "https://api.github.com/repos/o/r/compare/b...h" - }`) - }) - - got, _, err := client.Repositories.CompareCommits(context.Background(), "o", "r", "b", "h") - if err != nil { - t.Errorf("Repositories.CompareCommits returned error: %v", err) - } - - want := &CommitsComparison{ - BaseCommit: &RepositoryCommit{ - SHA: String("s"), - Commit: &Commit{ - Author: &CommitAuthor{Name: String("n")}, - Committer: &CommitAuthor{Name: String("n")}, - Message: String("m"), - Tree: &Tree{SHA: String("t")}, - }, - Author: &User{Login: String("l")}, - Committer: &User{Login: String("l")}, - Parents: []Commit{ - { - SHA: String("s"), - }, - }, - }, - Status: String("s"), - AheadBy: Int(1), - BehindBy: Int(2), - TotalCommits: Int(1), - Commits: []RepositoryCommit{ - { - SHA: String("s"), - Commit: &Commit{ - Author: &CommitAuthor{Name: String("n")}, - }, - Author: &User{Login: String("l")}, - Committer: &User{Login: String("l")}, - Parents: []Commit{ - { - SHA: String("s"), - }, - }, - }, - }, - Files: []CommitFile{ - { - Filename: String("f"), - }, - }, - HTMLURL: String("https://github.com/o/r/compare/b...h"), - PermalinkURL: String("https://github.com/o/r/compare/o:bbcd538c8e72b8c175046e27cc8f907076331401...o:0328041d1152db8ae77652d1618a02e57f745f17"), - DiffURL: String("https://github.com/o/r/compare/b...h.diff"), - PatchURL: String("https://github.com/o/r/compare/b...h.patch"), - URL: String("https://api.github.com/repos/o/r/compare/b...h"), - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("Repositories.CompareCommits returned \n%+v, want \n%+v", got, want) - } -} diff --git a/vendor/github.com/google/go-github/github/repos_community_health_test.go b/vendor/github.com/google/go-github/github/repos_community_health_test.go deleted file mode 100644 index a90c8c038027..000000000000 --- a/vendor/github.com/google/go-github/github/repos_community_health_test.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestRepositoriesService_GetCommunityHealthMetrics(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/community/profile", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeRepositoryCommunityHealthMetricsPreview) - fmt.Fprintf(w, `{ - "health_percentage": 100, - "files": { - "code_of_conduct": { - "name": "Contributor Covenant", - "key": "contributor_covenant", - "url": null, - "html_url": "https://github.com/octocat/Hello-World/blob/master/CODE_OF_CONDUCT.md" - }, - "contributing": { - "url": "https://api.github.com/repos/octocat/Hello-World/contents/CONTRIBUTING", - "html_url": "https://github.com/octocat/Hello-World/blob/master/CONTRIBUTING" - }, - "license": { - "name": "MIT License", - "key": "mit", - "url": "https://api.github.com/licenses/mit", - "html_url": "https://github.com/octocat/Hello-World/blob/master/LICENSE" - }, - "readme": { - "url": "https://api.github.com/repos/octocat/Hello-World/contents/README.md", - "html_url": "https://github.com/octocat/Hello-World/blob/master/README.md" - } - }, - "updated_at": "2017-02-28T00:00:00Z" - }`) - }) - - got, _, err := client.Repositories.GetCommunityHealthMetrics(context.Background(), "o", "r") - if err != nil { - t.Errorf("Repositories.GetCommunityHealthMetrics returned error: %v", err) - } - - updatedAt := time.Date(2017, 02, 28, 0, 0, 0, 0, time.UTC) - want := &CommunityHealthMetrics{ - HealthPercentage: Int(100), - UpdatedAt: &updatedAt, - Files: &CommunityHealthFiles{ - CodeOfConduct: &Metric{ - Name: String("Contributor Covenant"), - Key: String("contributor_covenant"), - HTMLURL: String("https://github.com/octocat/Hello-World/blob/master/CODE_OF_CONDUCT.md"), - }, - Contributing: &Metric{ - URL: String("https://api.github.com/repos/octocat/Hello-World/contents/CONTRIBUTING"), - HTMLURL: String("https://github.com/octocat/Hello-World/blob/master/CONTRIBUTING"), - }, - License: &Metric{ - Name: String("MIT License"), - Key: String("mit"), - URL: String("https://api.github.com/licenses/mit"), - HTMLURL: String("https://github.com/octocat/Hello-World/blob/master/LICENSE"), - }, - Readme: &Metric{ - URL: String("https://api.github.com/repos/octocat/Hello-World/contents/README.md"), - HTMLURL: String("https://github.com/octocat/Hello-World/blob/master/README.md"), - }, - }, - } - if !reflect.DeepEqual(got, want) { - t.Errorf("Repositories.GetCommunityHealthMetrics:\ngot:\n%v\nwant:\n%v", Stringify(got), Stringify(want)) - } -} diff --git a/vendor/github.com/google/go-github/github/repos_contents_test.go b/vendor/github.com/google/go-github/github/repos_contents_test.go deleted file mode 100644 index 498dfc810016..000000000000 --- a/vendor/github.com/google/go-github/github/repos_contents_test.go +++ /dev/null @@ -1,378 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "io/ioutil" - "net/http" - "reflect" - "testing" -) - -func TestRepositoryContent_GetContent(t *testing.T) { - tests := []struct { - encoding, content *string // input encoding and content - want string // desired output - wantErr bool // whether an error is expected - }{ - { - encoding: String(""), - content: String("hello"), - want: "hello", - wantErr: false, - }, - { - encoding: nil, - content: String("hello"), - want: "hello", - wantErr: false, - }, - { - encoding: nil, - content: nil, - want: "", - wantErr: false, - }, - { - encoding: String("base64"), - content: String("aGVsbG8="), - want: "hello", - wantErr: false, - }, - { - encoding: String("bad"), - content: String("aGVsbG8="), - want: "", - wantErr: true, - }, - } - - for _, tt := range tests { - r := RepositoryContent{Encoding: tt.encoding, Content: tt.content} - got, err := r.GetContent() - if err != nil && !tt.wantErr { - t.Errorf("RepositoryContent(%q, %q) returned unexpected error: %v", tt.encoding, tt.content, err) - } - if err == nil && tt.wantErr { - t.Errorf("RepositoryContent(%q, %q) did not return unexpected error", tt.encoding, tt.content) - } - if want := tt.want; got != want { - t.Errorf("RepositoryContent.GetContent returned %+v, want %+v", got, want) - } - } -} - -func TestRepositoriesService_GetReadme(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/readme", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{ - "type": "file", - "encoding": "base64", - "size": 5362, - "name": "README.md", - "path": "README.md" - }`) - }) - readme, _, err := client.Repositories.GetReadme(context.Background(), "o", "r", &RepositoryContentGetOptions{}) - if err != nil { - t.Errorf("Repositories.GetReadme returned error: %v", err) - } - want := &RepositoryContent{Type: String("file"), Name: String("README.md"), Size: Int(5362), Encoding: String("base64"), Path: String("README.md")} - if !reflect.DeepEqual(readme, want) { - t.Errorf("Repositories.GetReadme returned %+v, want %+v", readme, want) - } -} - -func TestRepositoriesService_DownloadContents_Success(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/contents/d", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{ - "type": "file", - "name": "f", - "download_url": "`+server.URL+`/download/f" - }]`) - }) - mux.HandleFunc("/download/f", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, "foo") - }) - - r, err := client.Repositories.DownloadContents(context.Background(), "o", "r", "d/f", nil) - if err != nil { - t.Errorf("Repositories.DownloadContents returned error: %v", err) - } - - bytes, err := ioutil.ReadAll(r) - if err != nil { - t.Errorf("Error reading response body: %v", err) - } - r.Close() - - if got, want := string(bytes), "foo"; got != want { - t.Errorf("Repositories.DownloadContents returned %v, want %v", got, want) - } -} - -func TestRepositoriesService_DownloadContents_NoDownloadURL(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/contents/d", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{ - "type": "file", - "name": "f", - }]`) - }) - - _, err := client.Repositories.DownloadContents(context.Background(), "o", "r", "d/f", nil) - if err == nil { - t.Errorf("Repositories.DownloadContents did not return expected error") - } -} - -func TestRepositoriesService_DownloadContents_NoFile(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/contents/d", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[]`) - }) - - _, err := client.Repositories.DownloadContents(context.Background(), "o", "r", "d/f", nil) - if err == nil { - t.Errorf("Repositories.DownloadContents did not return expected error") - } -} - -func TestRepositoriesService_GetContents_File(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/contents/p", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{ - "type": "file", - "encoding": "base64", - "size": 20678, - "name": "LICENSE", - "path": "LICENSE" - }`) - }) - fileContents, _, _, err := client.Repositories.GetContents(context.Background(), "o", "r", "p", &RepositoryContentGetOptions{}) - if err != nil { - t.Errorf("Repositories.GetContents returned error: %v", err) - } - want := &RepositoryContent{Type: String("file"), Name: String("LICENSE"), Size: Int(20678), Encoding: String("base64"), Path: String("LICENSE")} - if !reflect.DeepEqual(fileContents, want) { - t.Errorf("Repositories.GetContents returned %+v, want %+v", fileContents, want) - } -} - -func TestRepositoriesService_GetContents_FilenameNeedsEscape(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/contents/p#?%/中.go", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{}`) - }) - _, _, _, err := client.Repositories.GetContents(context.Background(), "o", "r", "p#?%/中.go", &RepositoryContentGetOptions{}) - if err != nil { - t.Fatalf("Repositories.GetContents returned error: %v", err) - } -} - -func TestRepositoriesService_GetContents_DirectoryWithSpaces(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/contents/some directory/file.go", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{}`) - }) - _, _, _, err := client.Repositories.GetContents(context.Background(), "o", "r", "some directory/file.go", &RepositoryContentGetOptions{}) - if err != nil { - t.Fatalf("Repositories.GetContents returned error: %v", err) - } -} - -func TestRepositoriesService_GetContents_DirectoryWithPlusChars(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/contents/some directory+name/file.go", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{}`) - }) - _, _, _, err := client.Repositories.GetContents(context.Background(), "o", "r", "some directory+name/file.go", &RepositoryContentGetOptions{}) - if err != nil { - t.Fatalf("Repositories.GetContents returned error: %v", err) - } -} - -func TestRepositoriesService_GetContents_Directory(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/contents/p", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{ - "type": "dir", - "name": "lib", - "path": "lib" - }, - { - "type": "file", - "size": 20678, - "name": "LICENSE", - "path": "LICENSE" - }]`) - }) - _, directoryContents, _, err := client.Repositories.GetContents(context.Background(), "o", "r", "p", &RepositoryContentGetOptions{}) - if err != nil { - t.Errorf("Repositories.GetContents returned error: %v", err) - } - want := []*RepositoryContent{{Type: String("dir"), Name: String("lib"), Path: String("lib")}, - {Type: String("file"), Name: String("LICENSE"), Size: Int(20678), Path: String("LICENSE")}} - if !reflect.DeepEqual(directoryContents, want) { - t.Errorf("Repositories.GetContents_Directory returned %+v, want %+v", directoryContents, want) - } -} - -func TestRepositoriesService_CreateFile(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/contents/p", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - fmt.Fprint(w, `{ - "content":{ - "name":"p" - }, - "commit":{ - "message":"m", - "sha":"f5f369044773ff9c6383c087466d12adb6fa0828" - } - }`) - }) - message := "m" - content := []byte("c") - repositoryContentsOptions := &RepositoryContentFileOptions{ - Message: &message, - Content: content, - Committer: &CommitAuthor{Name: String("n"), Email: String("e")}, - } - createResponse, _, err := client.Repositories.CreateFile(context.Background(), "o", "r", "p", repositoryContentsOptions) - if err != nil { - t.Errorf("Repositories.CreateFile returned error: %v", err) - } - want := &RepositoryContentResponse{ - Content: &RepositoryContent{Name: String("p")}, - Commit: Commit{ - Message: String("m"), - SHA: String("f5f369044773ff9c6383c087466d12adb6fa0828"), - }, - } - if !reflect.DeepEqual(createResponse, want) { - t.Errorf("Repositories.CreateFile returned %+v, want %+v", createResponse, want) - } -} - -func TestRepositoriesService_UpdateFile(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/contents/p", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - fmt.Fprint(w, `{ - "content":{ - "name":"p" - }, - "commit":{ - "message":"m", - "sha":"f5f369044773ff9c6383c087466d12adb6fa0828" - } - }`) - }) - message := "m" - content := []byte("c") - sha := "f5f369044773ff9c6383c087466d12adb6fa0828" - repositoryContentsOptions := &RepositoryContentFileOptions{ - Message: &message, - Content: content, - SHA: &sha, - Committer: &CommitAuthor{Name: String("n"), Email: String("e")}, - } - updateResponse, _, err := client.Repositories.UpdateFile(context.Background(), "o", "r", "p", repositoryContentsOptions) - if err != nil { - t.Errorf("Repositories.UpdateFile returned error: %v", err) - } - want := &RepositoryContentResponse{ - Content: &RepositoryContent{Name: String("p")}, - Commit: Commit{ - Message: String("m"), - SHA: String("f5f369044773ff9c6383c087466d12adb6fa0828"), - }, - } - if !reflect.DeepEqual(updateResponse, want) { - t.Errorf("Repositories.UpdateFile returned %+v, want %+v", updateResponse, want) - } -} - -func TestRepositoriesService_DeleteFile(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/contents/p", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - fmt.Fprint(w, `{ - "content": null, - "commit":{ - "message":"m", - "sha":"f5f369044773ff9c6383c087466d12adb6fa0828" - } - }`) - }) - message := "m" - sha := "f5f369044773ff9c6383c087466d12adb6fa0828" - repositoryContentsOptions := &RepositoryContentFileOptions{ - Message: &message, - SHA: &sha, - Committer: &CommitAuthor{Name: String("n"), Email: String("e")}, - } - deleteResponse, _, err := client.Repositories.DeleteFile(context.Background(), "o", "r", "p", repositoryContentsOptions) - if err != nil { - t.Errorf("Repositories.DeleteFile returned error: %v", err) - } - want := &RepositoryContentResponse{ - Content: nil, - Commit: Commit{ - Message: String("m"), - SHA: String("f5f369044773ff9c6383c087466d12adb6fa0828"), - }, - } - if !reflect.DeepEqual(deleteResponse, want) { - t.Errorf("Repositories.DeleteFile returned %+v, want %+v", deleteResponse, want) - } -} - -func TestRepositoriesService_GetArchiveLink(t *testing.T) { - setup() - defer teardown() - mux.HandleFunc("/repos/o/r/tarball", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - http.Redirect(w, r, "http://github.com/a", http.StatusFound) - }) - url, resp, err := client.Repositories.GetArchiveLink(context.Background(), "o", "r", Tarball, &RepositoryContentGetOptions{}) - if err != nil { - t.Errorf("Repositories.GetArchiveLink returned error: %v", err) - } - if resp.StatusCode != http.StatusFound { - t.Errorf("Repositories.GetArchiveLink returned status: %d, want %d", resp.StatusCode, http.StatusFound) - } - want := "http://github.com/a" - if url.String() != want { - t.Errorf("Repositories.GetArchiveLink returned %+v, want %+v", url.String(), want) - } -} diff --git a/vendor/github.com/google/go-github/github/repos_deployments_test.go b/vendor/github.com/google/go-github/github/repos_deployments_test.go deleted file mode 100644 index 9fa44b2ba4c7..000000000000 --- a/vendor/github.com/google/go-github/github/repos_deployments_test.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_ListDeployments(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/deployments", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"environment": "test"}) - fmt.Fprint(w, `[{"id":1}, {"id":2}]`) - }) - - opt := &DeploymentsListOptions{Environment: "test"} - deployments, _, err := client.Repositories.ListDeployments(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListDeployments returned error: %v", err) - } - - want := []*Deployment{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(deployments, want) { - t.Errorf("Repositories.ListDeployments returned %+v, want %+v", deployments, want) - } -} - -func TestRepositoriesService_GetDeployment(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/deployments/3", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":3}`) - }) - - deployment, _, err := client.Repositories.GetDeployment(context.Background(), "o", "r", 3) - if err != nil { - t.Errorf("Repositories.GetDeployment returned error: %v", err) - } - - want := &Deployment{ID: Int(3)} - - if !reflect.DeepEqual(deployment, want) { - t.Errorf("Repositories.GetDeployment returned %+v, want %+v", deployment, want) - } -} - -func TestRepositoriesService_CreateDeployment(t *testing.T) { - setup() - defer teardown() - - input := &DeploymentRequest{Ref: String("1111"), Task: String("deploy"), TransientEnvironment: Bool(true)} - - mux.HandleFunc("/repos/o/r/deployments", func(w http.ResponseWriter, r *http.Request) { - v := new(DeploymentRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - testHeader(t, r, "Accept", mediaTypeDeploymentStatusPreview) - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"ref": "1111", "task": "deploy"}`) - }) - - deployment, _, err := client.Repositories.CreateDeployment(context.Background(), "o", "r", input) - if err != nil { - t.Errorf("Repositories.CreateDeployment returned error: %v", err) - } - - want := &Deployment{Ref: String("1111"), Task: String("deploy")} - if !reflect.DeepEqual(deployment, want) { - t.Errorf("Repositories.CreateDeployment returned %+v, want %+v", deployment, want) - } -} - -func TestRepositoriesService_ListDeploymentStatuses(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/deployments/1/statuses", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}, {"id":2}]`) - }) - - opt := &ListOptions{Page: 2} - statutses, _, err := client.Repositories.ListDeploymentStatuses(context.Background(), "o", "r", 1, opt) - if err != nil { - t.Errorf("Repositories.ListDeploymentStatuses returned error: %v", err) - } - - want := []*DeploymentStatus{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(statutses, want) { - t.Errorf("Repositories.ListDeploymentStatuses returned %+v, want %+v", statutses, want) - } -} - -func TestRepositoriesService_GetDeploymentStatus(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/deployments/3/statuses/4", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeDeploymentStatusPreview) - fmt.Fprint(w, `{"id":4}`) - }) - - deploymentStatus, _, err := client.Repositories.GetDeploymentStatus(context.Background(), "o", "r", 3, 4) - if err != nil { - t.Errorf("Repositories.GetDeploymentStatus returned error: %v", err) - } - - want := &DeploymentStatus{ID: Int(4)} - if !reflect.DeepEqual(deploymentStatus, want) { - t.Errorf("Repositories.GetDeploymentStatus returned %+v, want %+v", deploymentStatus, want) - } -} - -func TestRepositoriesService_CreateDeploymentStatus(t *testing.T) { - setup() - defer teardown() - - input := &DeploymentStatusRequest{State: String("inactive"), Description: String("deploy"), AutoInactive: Bool(false)} - - mux.HandleFunc("/repos/o/r/deployments/1/statuses", func(w http.ResponseWriter, r *http.Request) { - v := new(DeploymentStatusRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - testHeader(t, r, "Accept", mediaTypeDeploymentStatusPreview) - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"state": "inactive", "description": "deploy"}`) - }) - - deploymentStatus, _, err := client.Repositories.CreateDeploymentStatus(context.Background(), "o", "r", 1, input) - if err != nil { - t.Errorf("Repositories.CreateDeploymentStatus returned error: %v", err) - } - - want := &DeploymentStatus{State: String("inactive"), Description: String("deploy")} - if !reflect.DeepEqual(deploymentStatus, want) { - t.Errorf("Repositories.CreateDeploymentStatus returned %+v, want %+v", deploymentStatus, want) - } -} diff --git a/vendor/github.com/google/go-github/github/repos_forks_test.go b/vendor/github.com/google/go-github/github/repos_forks_test.go deleted file mode 100644 index 40916ea4ea71..000000000000 --- a/vendor/github.com/google/go-github/github/repos_forks_test.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_ListForks(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/forks", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "sort": "newest", - "page": "3", - }) - fmt.Fprint(w, `[{"id":1},{"id":2}]`) - }) - - opt := &RepositoryListForksOptions{ - Sort: "newest", - ListOptions: ListOptions{Page: 3}, - } - repos, _, err := client.Repositories.ListForks(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListForks returned error: %v", err) - } - - want := []*Repository{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(repos, want) { - t.Errorf("Repositories.ListForks returned %+v, want %+v", repos, want) - } -} - -func TestRepositoriesService_ListForks_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.ListForks(context.Background(), "%", "r", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_CreateFork(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/forks", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testFormValues(t, r, values{"organization": "o"}) - fmt.Fprint(w, `{"id":1}`) - }) - - opt := &RepositoryCreateForkOptions{Organization: "o"} - repo, _, err := client.Repositories.CreateFork(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Repositories.CreateFork returned error: %v", err) - } - - want := &Repository{ID: Int(1)} - if !reflect.DeepEqual(repo, want) { - t.Errorf("Repositories.CreateFork returned %+v, want %+v", repo, want) - } -} - -func TestRepositoriesService_CreateFork_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.CreateFork(context.Background(), "%", "r", nil) - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/repos_hooks_test.go b/vendor/github.com/google/go-github/github/repos_hooks_test.go deleted file mode 100644 index 364f4583f08b..000000000000 --- a/vendor/github.com/google/go-github/github/repos_hooks_test.go +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_CreateHook(t *testing.T) { - setup() - defer teardown() - - input := &Hook{Name: String("t")} - - mux.HandleFunc("/repos/o/r/hooks", func(w http.ResponseWriter, r *http.Request) { - v := new(Hook) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - hook, _, err := client.Repositories.CreateHook(context.Background(), "o", "r", input) - if err != nil { - t.Errorf("Repositories.CreateHook returned error: %v", err) - } - - want := &Hook{ID: Int(1)} - if !reflect.DeepEqual(hook, want) { - t.Errorf("Repositories.CreateHook returned %+v, want %+v", hook, want) - } -} - -func TestRepositoriesService_CreateHook_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.CreateHook(context.Background(), "%", "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_ListHooks(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/hooks", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}, {"id":2}]`) - }) - - opt := &ListOptions{Page: 2} - - hooks, _, err := client.Repositories.ListHooks(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListHooks returned error: %v", err) - } - - want := []*Hook{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(hooks, want) { - t.Errorf("Repositories.ListHooks returned %+v, want %+v", hooks, want) - } -} - -func TestRepositoriesService_ListHooks_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.ListHooks(context.Background(), "%", "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_GetHook(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/hooks/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - hook, _, err := client.Repositories.GetHook(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Repositories.GetHook returned error: %v", err) - } - - want := &Hook{ID: Int(1)} - if !reflect.DeepEqual(hook, want) { - t.Errorf("Repositories.GetHook returned %+v, want %+v", hook, want) - } -} - -func TestRepositoriesService_GetHook_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.GetHook(context.Background(), "%", "%", 1) - testURLParseError(t, err) -} - -func TestRepositoriesService_EditHook(t *testing.T) { - setup() - defer teardown() - - input := &Hook{Name: String("t")} - - mux.HandleFunc("/repos/o/r/hooks/1", func(w http.ResponseWriter, r *http.Request) { - v := new(Hook) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - hook, _, err := client.Repositories.EditHook(context.Background(), "o", "r", 1, input) - if err != nil { - t.Errorf("Repositories.EditHook returned error: %v", err) - } - - want := &Hook{ID: Int(1)} - if !reflect.DeepEqual(hook, want) { - t.Errorf("Repositories.EditHook returned %+v, want %+v", hook, want) - } -} - -func TestRepositoriesService_EditHook_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.EditHook(context.Background(), "%", "%", 1, nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_DeleteHook(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/hooks/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Repositories.DeleteHook(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Repositories.DeleteHook returned error: %v", err) - } -} - -func TestRepositoriesService_DeleteHook_invalidOwner(t *testing.T) { - _, err := client.Repositories.DeleteHook(context.Background(), "%", "%", 1) - testURLParseError(t, err) -} - -func TestRepositoriesService_PingHook(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/hooks/1/pings", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - }) - - _, err := client.Repositories.PingHook(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Repositories.PingHook returned error: %v", err) - } -} - -func TestRepositoriesService_TestHook(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/hooks/1/tests", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - }) - - _, err := client.Repositories.TestHook(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Repositories.TestHook returned error: %v", err) - } -} - -func TestRepositoriesService_TestHook_invalidOwner(t *testing.T) { - _, err := client.Repositories.TestHook(context.Background(), "%", "%", 1) - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/repos_invitations_test.go b/vendor/github.com/google/go-github/github/repos_invitations_test.go deleted file mode 100644 index 01ac66657fca..000000000000 --- a/vendor/github.com/google/go-github/github/repos_invitations_test.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_ListInvitations(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/invitations", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeRepositoryInvitationsPreview) - testFormValues(t, r, values{"page": "2"}) - fmt.Fprintf(w, `[{"id":1}, {"id":2}]`) - }) - - opt := &ListOptions{Page: 2} - got, _, err := client.Repositories.ListInvitations(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListInvitations returned error: %v", err) - } - - want := []*RepositoryInvitation{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(got, want) { - t.Errorf("Repositories.ListInvitations = %+v, want %+v", got, want) - } -} - -func TestRepositoriesService_DeleteInvitation(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/invitations/2", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - testHeader(t, r, "Accept", mediaTypeRepositoryInvitationsPreview) - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Repositories.DeleteInvitation(context.Background(), "o", "r", 2) - if err != nil { - t.Errorf("Repositories.DeleteInvitation returned error: %v", err) - } -} - -func TestRepositoriesService_UpdateInvitation(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/invitations/2", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PATCH") - testHeader(t, r, "Accept", mediaTypeRepositoryInvitationsPreview) - fmt.Fprintf(w, `{"id":1}`) - }) - - got, _, err := client.Repositories.UpdateInvitation(context.Background(), "o", "r", 2, "write") - if err != nil { - t.Errorf("Repositories.UpdateInvitation returned error: %v", err) - } - - want := &RepositoryInvitation{ID: Int(1)} - if !reflect.DeepEqual(got, want) { - t.Errorf("Repositories.UpdateInvitation = %+v, want %+v", got, want) - } -} diff --git a/vendor/github.com/google/go-github/github/repos_keys_test.go b/vendor/github.com/google/go-github/github/repos_keys_test.go deleted file mode 100644 index 2ef04fdcb623..000000000000 --- a/vendor/github.com/google/go-github/github/repos_keys_test.go +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_ListKeys(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/keys", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - keys, _, err := client.Repositories.ListKeys(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListKeys returned error: %v", err) - } - - want := []*Key{{ID: Int(1)}} - if !reflect.DeepEqual(keys, want) { - t.Errorf("Repositories.ListKeys returned %+v, want %+v", keys, want) - } -} - -func TestRepositoriesService_ListKeys_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.ListKeys(context.Background(), "%", "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_GetKey(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/keys/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - key, _, err := client.Repositories.GetKey(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Repositories.GetKey returned error: %v", err) - } - - want := &Key{ID: Int(1)} - if !reflect.DeepEqual(key, want) { - t.Errorf("Repositories.GetKey returned %+v, want %+v", key, want) - } -} - -func TestRepositoriesService_GetKey_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.GetKey(context.Background(), "%", "%", 1) - testURLParseError(t, err) -} - -func TestRepositoriesService_CreateKey(t *testing.T) { - setup() - defer teardown() - - input := &Key{Key: String("k"), Title: String("t")} - - mux.HandleFunc("/repos/o/r/keys", func(w http.ResponseWriter, r *http.Request) { - v := new(Key) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - key, _, err := client.Repositories.CreateKey(context.Background(), "o", "r", input) - if err != nil { - t.Errorf("Repositories.GetKey returned error: %v", err) - } - - want := &Key{ID: Int(1)} - if !reflect.DeepEqual(key, want) { - t.Errorf("Repositories.GetKey returned %+v, want %+v", key, want) - } -} - -func TestRepositoriesService_CreateKey_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.CreateKey(context.Background(), "%", "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_EditKey(t *testing.T) { - setup() - defer teardown() - - input := &Key{Key: String("k"), Title: String("t")} - - mux.HandleFunc("/repos/o/r/keys/1", func(w http.ResponseWriter, r *http.Request) { - v := new(Key) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - key, _, err := client.Repositories.EditKey(context.Background(), "o", "r", 1, input) - if err != nil { - t.Errorf("Repositories.EditKey returned error: %v", err) - } - - want := &Key{ID: Int(1)} - if !reflect.DeepEqual(key, want) { - t.Errorf("Repositories.EditKey returned %+v, want %+v", key, want) - } -} - -func TestRepositoriesService_EditKey_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.EditKey(context.Background(), "%", "%", 1, nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_DeleteKey(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/keys/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Repositories.DeleteKey(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Repositories.DeleteKey returned error: %v", err) - } -} - -func TestRepositoriesService_DeleteKey_invalidOwner(t *testing.T) { - _, err := client.Repositories.DeleteKey(context.Background(), "%", "%", 1) - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/repos_merging_test.go b/vendor/github.com/google/go-github/github/repos_merging_test.go deleted file mode 100644 index e2e264fd6604..000000000000 --- a/vendor/github.com/google/go-github/github/repos_merging_test.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_Merge(t *testing.T) { - setup() - defer teardown() - - input := &RepositoryMergeRequest{ - Base: String("b"), - Head: String("h"), - CommitMessage: String("c"), - } - - mux.HandleFunc("/repos/o/r/merges", func(w http.ResponseWriter, r *http.Request) { - v := new(RepositoryMergeRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"sha":"s"}`) - }) - - commit, _, err := client.Repositories.Merge(context.Background(), "o", "r", input) - if err != nil { - t.Errorf("Repositories.Merge returned error: %v", err) - } - - want := &RepositoryCommit{SHA: String("s")} - if !reflect.DeepEqual(commit, want) { - t.Errorf("Repositories.Merge returned %+v, want %+v", commit, want) - } -} diff --git a/vendor/github.com/google/go-github/github/repos_pages_test.go b/vendor/github.com/google/go-github/github/repos_pages_test.go deleted file mode 100644 index c9e19a1f5a10..000000000000 --- a/vendor/github.com/google/go-github/github/repos_pages_test.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_GetPagesInfo(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pages", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypePagesPreview) - fmt.Fprint(w, `{"url":"u","status":"s","cname":"c","custom_404":false,"html_url":"h"}`) - }) - - page, _, err := client.Repositories.GetPagesInfo(context.Background(), "o", "r") - if err != nil { - t.Errorf("Repositories.GetPagesInfo returned error: %v", err) - } - - want := &Pages{URL: String("u"), Status: String("s"), CNAME: String("c"), Custom404: Bool(false), HTMLURL: String("h")} - if !reflect.DeepEqual(page, want) { - t.Errorf("Repositories.GetPagesInfo returned %+v, want %+v", page, want) - } -} - -func TestRepositoriesService_ListPagesBuilds(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pages/builds", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"url":"u","status":"s","commit":"c"}]`) - }) - - pages, _, err := client.Repositories.ListPagesBuilds(context.Background(), "o", "r", nil) - if err != nil { - t.Errorf("Repositories.ListPagesBuilds returned error: %v", err) - } - - want := []*PagesBuild{{URL: String("u"), Status: String("s"), Commit: String("c")}} - if !reflect.DeepEqual(pages, want) { - t.Errorf("Repositories.ListPagesBuilds returned %+v, want %+v", pages, want) - } -} - -func TestRepositoriesService_ListPagesBuilds_withOptions(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pages/builds", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - fmt.Fprint(w, `[]`) - }) - - _, _, err := client.Repositories.ListPagesBuilds(context.Background(), "o", "r", &ListOptions{Page: 2}) - if err != nil { - t.Errorf("Repositories.ListPagesBuilds returned error: %v", err) - } -} - -func TestRepositoriesService_GetLatestPagesBuild(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pages/builds/latest", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"url":"u","status":"s","commit":"c"}`) - }) - - build, _, err := client.Repositories.GetLatestPagesBuild(context.Background(), "o", "r") - if err != nil { - t.Errorf("Repositories.GetLatestPagesBuild returned error: %v", err) - } - - want := &PagesBuild{URL: String("u"), Status: String("s"), Commit: String("c")} - if !reflect.DeepEqual(build, want) { - t.Errorf("Repositories.GetLatestPagesBuild returned %+v, want %+v", build, want) - } -} - -func TestRepositoriesService_GetPageBuild(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pages/builds/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"url":"u","status":"s","commit":"c"}`) - }) - - build, _, err := client.Repositories.GetPageBuild(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Repositories.GetPageBuild returned error: %v", err) - } - - want := &PagesBuild{URL: String("u"), Status: String("s"), Commit: String("c")} - if !reflect.DeepEqual(build, want) { - t.Errorf("Repositories.GetPageBuild returned %+v, want %+v", build, want) - } -} - -func TestRepositoriesService_RequestPageBuild(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/pages/builds", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testHeader(t, r, "Accept", mediaTypePagesPreview) - fmt.Fprint(w, `{"url":"u","status":"s"}`) - }) - - build, _, err := client.Repositories.RequestPageBuild(context.Background(), "o", "r") - if err != nil { - t.Errorf("Repositories.RequestPageBuild returned error: %v", err) - } - - want := &PagesBuild{URL: String("u"), Status: String("s")} - if !reflect.DeepEqual(build, want) { - t.Errorf("Repositories.RequestPageBuild returned %+v, want %+v", build, want) - } -} diff --git a/vendor/github.com/google/go-github/github/repos_projects_test.go b/vendor/github.com/google/go-github/github/repos_projects_test.go deleted file mode 100644 index 57dbdd1b3fee..000000000000 --- a/vendor/github.com/google/go-github/github/repos_projects_test.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_ListProjects(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/projects", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeProjectsPreview) - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ProjectListOptions{ListOptions: ListOptions{Page: 2}} - projects, _, err := client.Repositories.ListProjects(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListProjects returned error: %v", err) - } - - want := []*Project{{ID: Int(1)}} - if !reflect.DeepEqual(projects, want) { - t.Errorf("Repositories.ListProjects returned %+v, want %+v", projects, want) - } -} - -func TestRepositoriesService_CreateProject(t *testing.T) { - setup() - defer teardown() - - input := &ProjectOptions{Name: "Project Name", Body: "Project body."} - - mux.HandleFunc("/repos/o/r/projects", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testHeader(t, r, "Accept", mediaTypeProjectsPreview) - - v := &ProjectOptions{} - json.NewDecoder(r.Body).Decode(v) - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - project, _, err := client.Repositories.CreateProject(context.Background(), "o", "r", input) - if err != nil { - t.Errorf("Repositories.CreateProject returned error: %v", err) - } - - want := &Project{ID: Int(1)} - if !reflect.DeepEqual(project, want) { - t.Errorf("Repositories.CreateProject returned %+v, want %+v", project, want) - } -} diff --git a/vendor/github.com/google/go-github/github/repos_releases_test.go b/vendor/github.com/google/go-github/github/repos_releases_test.go deleted file mode 100644 index 9a2c4c8afff2..000000000000 --- a/vendor/github.com/google/go-github/github/repos_releases_test.go +++ /dev/null @@ -1,353 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "os" - "reflect" - "strings" - "testing" -) - -func TestRepositoriesService_ListReleases(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - releases, _, err := client.Repositories.ListReleases(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListReleases returned error: %v", err) - } - want := []*RepositoryRelease{{ID: Int(1)}} - if !reflect.DeepEqual(releases, want) { - t.Errorf("Repositories.ListReleases returned %+v, want %+v", releases, want) - } -} - -func TestRepositoriesService_GetRelease(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1,"author":{"login":"l"}}`) - }) - - release, resp, err := client.Repositories.GetRelease(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Repositories.GetRelease returned error: %v\n%v", err, resp.Body) - } - - want := &RepositoryRelease{ID: Int(1), Author: &User{Login: String("l")}} - if !reflect.DeepEqual(release, want) { - t.Errorf("Repositories.GetRelease returned %+v, want %+v", release, want) - } -} - -func TestRepositoriesService_GetLatestRelease(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases/latest", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":3}`) - }) - - release, resp, err := client.Repositories.GetLatestRelease(context.Background(), "o", "r") - if err != nil { - t.Errorf("Repositories.GetLatestRelease returned error: %v\n%v", err, resp.Body) - } - - want := &RepositoryRelease{ID: Int(3)} - if !reflect.DeepEqual(release, want) { - t.Errorf("Repositories.GetLatestRelease returned %+v, want %+v", release, want) - } -} - -func TestRepositoriesService_GetReleaseByTag(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases/tags/foo", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":13}`) - }) - - release, resp, err := client.Repositories.GetReleaseByTag(context.Background(), "o", "r", "foo") - if err != nil { - t.Errorf("Repositories.GetReleaseByTag returned error: %v\n%v", err, resp.Body) - } - - want := &RepositoryRelease{ID: Int(13)} - if !reflect.DeepEqual(release, want) { - t.Errorf("Repositories.GetReleaseByTag returned %+v, want %+v", release, want) - } -} - -func TestRepositoriesService_CreateRelease(t *testing.T) { - setup() - defer teardown() - - input := &RepositoryRelease{Name: String("v1.0")} - - mux.HandleFunc("/repos/o/r/releases", func(w http.ResponseWriter, r *http.Request) { - v := new(RepositoryRelease) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - fmt.Fprint(w, `{"id":1}`) - }) - - release, _, err := client.Repositories.CreateRelease(context.Background(), "o", "r", input) - if err != nil { - t.Errorf("Repositories.CreateRelease returned error: %v", err) - } - - want := &RepositoryRelease{ID: Int(1)} - if !reflect.DeepEqual(release, want) { - t.Errorf("Repositories.CreateRelease returned %+v, want %+v", release, want) - } -} - -func TestRepositoriesService_EditRelease(t *testing.T) { - setup() - defer teardown() - - input := &RepositoryRelease{Name: String("n")} - - mux.HandleFunc("/repos/o/r/releases/1", func(w http.ResponseWriter, r *http.Request) { - v := new(RepositoryRelease) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - fmt.Fprint(w, `{"id":1}`) - }) - - release, _, err := client.Repositories.EditRelease(context.Background(), "o", "r", 1, input) - if err != nil { - t.Errorf("Repositories.EditRelease returned error: %v", err) - } - want := &RepositoryRelease{ID: Int(1)} - if !reflect.DeepEqual(release, want) { - t.Errorf("Repositories.EditRelease returned = %+v, want %+v", release, want) - } -} - -func TestRepositoriesService_DeleteRelease(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Repositories.DeleteRelease(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Repositories.DeleteRelease returned error: %v", err) - } -} - -func TestRepositoriesService_ListReleaseAssets(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases/1/assets", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - assets, _, err := client.Repositories.ListReleaseAssets(context.Background(), "o", "r", 1, opt) - if err != nil { - t.Errorf("Repositories.ListReleaseAssets returned error: %v", err) - } - want := []*ReleaseAsset{{ID: Int(1)}} - if !reflect.DeepEqual(assets, want) { - t.Errorf("Repositories.ListReleaseAssets returned %+v, want %+v", assets, want) - } -} - -func TestRepositoriesService_GetReleaseAsset(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases/assets/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - asset, _, err := client.Repositories.GetReleaseAsset(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Repositories.GetReleaseAsset returned error: %v", err) - } - want := &ReleaseAsset{ID: Int(1)} - if !reflect.DeepEqual(asset, want) { - t.Errorf("Repositories.GetReleaseAsset returned %+v, want %+v", asset, want) - } -} - -func TestRepositoriesService_DownloadReleaseAsset_Stream(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases/assets/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", defaultMediaType) - w.Header().Set("Content-Type", "application/octet-stream") - w.Header().Set("Content-Disposition", "attachment; filename=hello-world.txt") - fmt.Fprint(w, "Hello World") - }) - - reader, _, err := client.Repositories.DownloadReleaseAsset(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Repositories.DownloadReleaseAsset returned error: %v", err) - } - want := []byte("Hello World") - content, err := ioutil.ReadAll(reader) - if err != nil { - t.Errorf("Repositories.DownloadReleaseAsset returned bad reader: %v", err) - } - if !bytes.Equal(want, content) { - t.Errorf("Repositories.DownloadReleaseAsset returned %+v, want %+v", content, want) - } -} - -func TestRepositoriesService_DownloadReleaseAsset_Redirect(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases/assets/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", defaultMediaType) - http.Redirect(w, r, "/yo", http.StatusFound) - }) - - _, got, err := client.Repositories.DownloadReleaseAsset(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Repositories.DownloadReleaseAsset returned error: %v", err) - } - want := "/yo" - if !strings.HasSuffix(got, want) { - t.Errorf("Repositories.DownloadReleaseAsset returned %+v, want %+v", got, want) - } -} - -func TestRepositoriesService_DownloadReleaseAsset_APIError(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases/assets/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", defaultMediaType) - w.WriteHeader(http.StatusNotFound) - fmt.Fprint(w, `{"message":"Not Found","documentation_url":"https://developer.github.com/v3"}`) - }) - - resp, loc, err := client.Repositories.DownloadReleaseAsset(context.Background(), "o", "r", 1) - if err == nil { - t.Error("Repositories.DownloadReleaseAsset did not return an error") - } - - if resp != nil { - resp.Close() - t.Error("Repositories.DownloadReleaseAsset returned stream, want nil") - } - - if loc != "" { - t.Errorf(`Repositories.DownloadReleaseAsset returned "%s", want empty ""`, loc) - } -} - -func TestRepositoriesService_EditReleaseAsset(t *testing.T) { - setup() - defer teardown() - - input := &ReleaseAsset{Name: String("n")} - - mux.HandleFunc("/repos/o/r/releases/assets/1", func(w http.ResponseWriter, r *http.Request) { - v := new(ReleaseAsset) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - fmt.Fprint(w, `{"id":1}`) - }) - - asset, _, err := client.Repositories.EditReleaseAsset(context.Background(), "o", "r", 1, input) - if err != nil { - t.Errorf("Repositories.EditReleaseAsset returned error: %v", err) - } - want := &ReleaseAsset{ID: Int(1)} - if !reflect.DeepEqual(asset, want) { - t.Errorf("Repositories.EditReleaseAsset returned = %+v, want %+v", asset, want) - } -} - -func TestRepositoriesService_DeleteReleaseAsset(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases/assets/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Repositories.DeleteReleaseAsset(context.Background(), "o", "r", 1) - if err != nil { - t.Errorf("Repositories.DeleteReleaseAsset returned error: %v", err) - } -} - -func TestRepositoriesService_UploadReleaseAsset(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/releases/1/assets", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "POST") - testHeader(t, r, "Content-Type", "text/plain; charset=utf-8") - testHeader(t, r, "Content-Length", "12") - testFormValues(t, r, values{"name": "n"}) - testBody(t, r, "Upload me !\n") - - fmt.Fprintf(w, `{"id":1}`) - }) - - file, dir, err := openTestFile("upload.txt", "Upload me !\n") - if err != nil { - t.Fatalf("Unable to create temp file: %v", err) - } - defer os.RemoveAll(dir) - - opt := &UploadOptions{Name: "n"} - asset, _, err := client.Repositories.UploadReleaseAsset(context.Background(), "o", "r", 1, opt, file) - if err != nil { - t.Errorf("Repositories.UploadReleaseAssert returned error: %v", err) - } - want := &ReleaseAsset{ID: Int(1)} - if !reflect.DeepEqual(asset, want) { - t.Errorf("Repositories.UploadReleaseAssert returned %+v, want %+v", asset, want) - } -} diff --git a/vendor/github.com/google/go-github/github/repos_stats_test.go b/vendor/github.com/google/go-github/github/repos_stats_test.go deleted file mode 100644 index 1da94d013380..000000000000 --- a/vendor/github.com/google/go-github/github/repos_stats_test.go +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestRepositoriesService_ListContributorsStats(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/stats/contributors", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - - fmt.Fprint(w, ` -[ - { - "author": { - "id": 1 - }, - "total": 135, - "weeks": [ - { - "w": 1367712000, - "a": 6898, - "d": 77, - "c": 10 - } - ] - } -] -`) - }) - - stats, _, err := client.Repositories.ListContributorsStats(context.Background(), "o", "r") - if err != nil { - t.Errorf("RepositoriesService.ListContributorsStats returned error: %v", err) - } - - want := []*ContributorStats{ - { - Author: &Contributor{ - ID: Int(1), - }, - Total: Int(135), - Weeks: []WeeklyStats{ - { - Week: &Timestamp{time.Date(2013, 05, 05, 00, 00, 00, 0, time.UTC).Local()}, - Additions: Int(6898), - Deletions: Int(77), - Commits: Int(10), - }, - }, - }, - } - - if !reflect.DeepEqual(stats, want) { - t.Errorf("RepositoriesService.ListContributorsStats returned %+v, want %+v", stats, want) - } -} - -func TestRepositoriesService_ListCommitActivity(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/stats/commit_activity", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - - fmt.Fprint(w, ` -[ - { - "days": [0, 3, 26, 20, 39, 1, 0], - "total": 89, - "week": 1336280400 - } -] -`) - }) - - activity, _, err := client.Repositories.ListCommitActivity(context.Background(), "o", "r") - if err != nil { - t.Errorf("RepositoriesService.ListCommitActivity returned error: %v", err) - } - - want := []*WeeklyCommitActivity{ - { - Days: []int{0, 3, 26, 20, 39, 1, 0}, - Total: Int(89), - Week: &Timestamp{time.Date(2012, 05, 06, 05, 00, 00, 0, time.UTC).Local()}, - }, - } - - if !reflect.DeepEqual(activity, want) { - t.Errorf("RepositoriesService.ListCommitActivity returned %+v, want %+v", activity, want) - } -} - -func TestRepositoriesService_ListCodeFrequency(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/stats/code_frequency", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - - fmt.Fprint(w, `[[1302998400, 1124, -435]]`) - }) - - code, _, err := client.Repositories.ListCodeFrequency(context.Background(), "o", "r") - if err != nil { - t.Errorf("RepositoriesService.ListCodeFrequency returned error: %v", err) - } - - want := []*WeeklyStats{{ - Week: &Timestamp{time.Date(2011, 04, 17, 00, 00, 00, 0, time.UTC).Local()}, - Additions: Int(1124), - Deletions: Int(-435), - }} - - if !reflect.DeepEqual(code, want) { - t.Errorf("RepositoriesService.ListCodeFrequency returned %+v, want %+v", code, want) - } -} - -func TestRepositoriesService_Participation(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/stats/participation", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - - fmt.Fprint(w, ` -{ - "all": [ - 11,21,15,2,8,1,8,23,17,21,11,10,33, - 91,38,34,22,23,32,3,43,87,71,18,13,5, - 13,16,66,27,12,45,110,117,13,8,18,9,19, - 26,39,12,20,31,46,91,45,10,24,9,29,7 - ], - "owner": [ - 3,2,3,0,2,0,5,14,7,9,1,5,0, - 48,19,2,0,1,10,2,23,40,35,8,8,2, - 10,6,30,0,2,9,53,104,3,3,10,4,7, - 11,21,4,4,22,26,63,11,2,14,1,10,3 - ] -} -`) - }) - - participation, _, err := client.Repositories.ListParticipation(context.Background(), "o", "r") - if err != nil { - t.Errorf("RepositoriesService.ListParticipation returned error: %v", err) - } - - want := &RepositoryParticipation{ - All: []int{ - 11, 21, 15, 2, 8, 1, 8, 23, 17, 21, 11, 10, 33, - 91, 38, 34, 22, 23, 32, 3, 43, 87, 71, 18, 13, 5, - 13, 16, 66, 27, 12, 45, 110, 117, 13, 8, 18, 9, 19, - 26, 39, 12, 20, 31, 46, 91, 45, 10, 24, 9, 29, 7, - }, - Owner: []int{ - 3, 2, 3, 0, 2, 0, 5, 14, 7, 9, 1, 5, 0, - 48, 19, 2, 0, 1, 10, 2, 23, 40, 35, 8, 8, 2, - 10, 6, 30, 0, 2, 9, 53, 104, 3, 3, 10, 4, 7, - 11, 21, 4, 4, 22, 26, 63, 11, 2, 14, 1, 10, 3, - }, - } - - if !reflect.DeepEqual(participation, want) { - t.Errorf("RepositoriesService.ListParticipation returned %+v, want %+v", participation, want) - } -} - -func TestRepositoriesService_ListPunchCard(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/stats/punch_card", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - - fmt.Fprint(w, `[ - [0, 0, 5], - [0, 1, 43], - [0, 2, 21] - ]`) - }) - - card, _, err := client.Repositories.ListPunchCard(context.Background(), "o", "r") - if err != nil { - t.Errorf("RepositoriesService.ListPunchCard returned error: %v", err) - } - - want := []*PunchCard{ - {Day: Int(0), Hour: Int(0), Commits: Int(5)}, - {Day: Int(0), Hour: Int(1), Commits: Int(43)}, - {Day: Int(0), Hour: Int(2), Commits: Int(21)}, - } - - if !reflect.DeepEqual(card, want) { - t.Errorf("RepositoriesService.ListPunchCard returned %+v, want %+v", card, want) - } -} diff --git a/vendor/github.com/google/go-github/github/repos_statuses_test.go b/vendor/github.com/google/go-github/github/repos_statuses_test.go deleted file mode 100644 index 8e6c9378d272..000000000000 --- a/vendor/github.com/google/go-github/github/repos_statuses_test.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestRepositoriesService_ListStatuses(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/commits/r/statuses", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - statuses, _, err := client.Repositories.ListStatuses(context.Background(), "o", "r", "r", opt) - if err != nil { - t.Errorf("Repositories.ListStatuses returned error: %v", err) - } - - want := []*RepoStatus{{ID: Int(1)}} - if !reflect.DeepEqual(statuses, want) { - t.Errorf("Repositories.ListStatuses returned %+v, want %+v", statuses, want) - } -} - -func TestRepositoriesService_ListStatuses_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.ListStatuses(context.Background(), "%", "r", "r", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_CreateStatus(t *testing.T) { - setup() - defer teardown() - - input := &RepoStatus{State: String("s"), TargetURL: String("t"), Description: String("d")} - - mux.HandleFunc("/repos/o/r/statuses/r", func(w http.ResponseWriter, r *http.Request) { - v := new(RepoStatus) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - fmt.Fprint(w, `{"id":1}`) - }) - - status, _, err := client.Repositories.CreateStatus(context.Background(), "o", "r", "r", input) - if err != nil { - t.Errorf("Repositories.CreateStatus returned error: %v", err) - } - - want := &RepoStatus{ID: Int(1)} - if !reflect.DeepEqual(status, want) { - t.Errorf("Repositories.CreateStatus returned %+v, want %+v", status, want) - } -} - -func TestRepositoriesService_CreateStatus_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.CreateStatus(context.Background(), "%", "r", "r", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_GetCombinedStatus(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/commits/r/status", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `{"state":"success", "statuses":[{"id":1}]}`) - }) - - opt := &ListOptions{Page: 2} - status, _, err := client.Repositories.GetCombinedStatus(context.Background(), "o", "r", "r", opt) - if err != nil { - t.Errorf("Repositories.GetCombinedStatus returned error: %v", err) - } - - want := &CombinedStatus{State: String("success"), Statuses: []RepoStatus{{ID: Int(1)}}} - if !reflect.DeepEqual(status, want) { - t.Errorf("Repositories.GetCombinedStatus returned %+v, want %+v", status, want) - } -} diff --git a/vendor/github.com/google/go-github/github/repos_test.go b/vendor/github.com/google/go-github/github/repos_test.go deleted file mode 100644 index 21ce09b30332..000000000000 --- a/vendor/github.com/google/go-github/github/repos_test.go +++ /dev/null @@ -1,713 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "strings" - "testing" -) - -func TestRepositoriesService_List_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/repos", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeLicensesPreview) - fmt.Fprint(w, `[{"id":1},{"id":2}]`) - }) - - repos, _, err := client.Repositories.List(context.Background(), "", nil) - if err != nil { - t.Errorf("Repositories.List returned error: %v", err) - } - - want := []*Repository{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(repos, want) { - t.Errorf("Repositories.List returned %+v, want %+v", repos, want) - } -} - -func TestRepositoriesService_List_specifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/repos", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeLicensesPreview) - testFormValues(t, r, values{ - "visibility": "public", - "affiliation": "owner,collaborator", - "sort": "created", - "direction": "asc", - "page": "2", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &RepositoryListOptions{ - Visibility: "public", - Affiliation: "owner,collaborator", - Sort: "created", - Direction: "asc", - ListOptions: ListOptions{Page: 2}, - } - repos, _, err := client.Repositories.List(context.Background(), "u", opt) - if err != nil { - t.Errorf("Repositories.List returned error: %v", err) - } - - want := []*Repository{{ID: Int(1)}} - if !reflect.DeepEqual(repos, want) { - t.Errorf("Repositories.List returned %+v, want %+v", repos, want) - } -} - -func TestRepositoriesService_List_specifiedUser_type(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/repos", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeLicensesPreview) - testFormValues(t, r, values{ - "type": "owner", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &RepositoryListOptions{ - Type: "owner", - } - repos, _, err := client.Repositories.List(context.Background(), "u", opt) - if err != nil { - t.Errorf("Repositories.List returned error: %v", err) - } - - want := []*Repository{{ID: Int(1)}} - if !reflect.DeepEqual(repos, want) { - t.Errorf("Repositories.List returned %+v, want %+v", repos, want) - } -} - -func TestRepositoriesService_List_invalidUser(t *testing.T) { - _, _, err := client.Repositories.List(context.Background(), "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_ListByOrg(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/orgs/o/repos", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeLicensesPreview) - testFormValues(t, r, values{ - "type": "forks", - "page": "2", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &RepositoryListByOrgOptions{"forks", ListOptions{Page: 2}} - repos, _, err := client.Repositories.ListByOrg(context.Background(), "o", opt) - if err != nil { - t.Errorf("Repositories.ListByOrg returned error: %v", err) - } - - want := []*Repository{{ID: Int(1)}} - if !reflect.DeepEqual(repos, want) { - t.Errorf("Repositories.ListByOrg returned %+v, want %+v", repos, want) - } -} - -func TestRepositoriesService_ListByOrg_invalidOrg(t *testing.T) { - _, _, err := client.Repositories.ListByOrg(context.Background(), "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_ListAll(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repositories", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "since": "1", - "page": "2", - "per_page": "3", - }) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &RepositoryListAllOptions{1, ListOptions{2, 3}} - repos, _, err := client.Repositories.ListAll(context.Background(), opt) - if err != nil { - t.Errorf("Repositories.ListAll returned error: %v", err) - } - - want := []*Repository{{ID: Int(1)}} - if !reflect.DeepEqual(repos, want) { - t.Errorf("Repositories.ListAll returned %+v, want %+v", repos, want) - } -} - -func TestRepositoriesService_Create_user(t *testing.T) { - setup() - defer teardown() - - input := &Repository{Name: String("n")} - - mux.HandleFunc("/user/repos", func(w http.ResponseWriter, r *http.Request) { - v := new(Repository) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - repo, _, err := client.Repositories.Create(context.Background(), "", input) - if err != nil { - t.Errorf("Repositories.Create returned error: %v", err) - } - - want := &Repository{ID: Int(1)} - if !reflect.DeepEqual(repo, want) { - t.Errorf("Repositories.Create returned %+v, want %+v", repo, want) - } -} - -func TestRepositoriesService_Create_org(t *testing.T) { - setup() - defer teardown() - - input := &Repository{Name: String("n")} - - mux.HandleFunc("/orgs/o/repos", func(w http.ResponseWriter, r *http.Request) { - v := new(Repository) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - repo, _, err := client.Repositories.Create(context.Background(), "o", input) - if err != nil { - t.Errorf("Repositories.Create returned error: %v", err) - } - - want := &Repository{ID: Int(1)} - if !reflect.DeepEqual(repo, want) { - t.Errorf("Repositories.Create returned %+v, want %+v", repo, want) - } -} - -func TestRepositoriesService_Create_invalidOrg(t *testing.T) { - _, _, err := client.Repositories.Create(context.Background(), "%", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_Get(t *testing.T) { - setup() - defer teardown() - - acceptHeader := []string{mediaTypeLicensesPreview, mediaTypeSquashPreview, mediaTypeCodesOfConductPreview} - mux.HandleFunc("/repos/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", strings.Join(acceptHeader, ", ")) - fmt.Fprint(w, `{"id":1,"name":"n","description":"d","owner":{"login":"l"},"license":{"key":"mit"}}`) - }) - - repo, _, err := client.Repositories.Get(context.Background(), "o", "r") - if err != nil { - t.Errorf("Repositories.Get returned error: %v", err) - } - - want := &Repository{ID: Int(1), Name: String("n"), Description: String("d"), Owner: &User{Login: String("l")}, License: &License{Key: String("mit")}} - if !reflect.DeepEqual(repo, want) { - t.Errorf("Repositories.Get returned %+v, want %+v", repo, want) - } -} - -func TestRepositoriesService_GetCodeOfConduct(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/community/code_of_conduct", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeCodesOfConductPreview) - fmt.Fprint(w, `{ - "key": "key", - "name": "name", - "url": "url", - "body": "body"}`, - ) - }) - - coc, _, err := client.Repositories.GetCodeOfConduct(context.Background(), "o", "r") - if err != nil { - t.Errorf("Repositories.GetCodeOfConduct returned error: %v", err) - } - - want := &CodeOfConduct{ - Key: String("key"), - Name: String("name"), - URL: String("url"), - Body: String("body"), - } - - if !reflect.DeepEqual(coc, want) { - t.Errorf("Repositories.Get returned %+v, want %+v", coc, want) - } -} - -func TestRepositoriesService_GetByID(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repositories/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeLicensesPreview) - fmt.Fprint(w, `{"id":1,"name":"n","description":"d","owner":{"login":"l"},"license":{"key":"mit"}}`) - }) - - repo, _, err := client.Repositories.GetByID(context.Background(), 1) - if err != nil { - t.Errorf("Repositories.GetByID returned error: %v", err) - } - - want := &Repository{ID: Int(1), Name: String("n"), Description: String("d"), Owner: &User{Login: String("l")}, License: &License{Key: String("mit")}} - if !reflect.DeepEqual(repo, want) { - t.Errorf("Repositories.GetByID returned %+v, want %+v", repo, want) - } -} - -func TestRepositoriesService_Edit(t *testing.T) { - setup() - defer teardown() - - i := true - input := &Repository{HasIssues: &i} - - mux.HandleFunc("/repos/o/r", func(w http.ResponseWriter, r *http.Request) { - v := new(Repository) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - fmt.Fprint(w, `{"id":1}`) - }) - - repo, _, err := client.Repositories.Edit(context.Background(), "o", "r", input) - if err != nil { - t.Errorf("Repositories.Edit returned error: %v", err) - } - - want := &Repository{ID: Int(1)} - if !reflect.DeepEqual(repo, want) { - t.Errorf("Repositories.Edit returned %+v, want %+v", repo, want) - } -} - -func TestRepositoriesService_Delete(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Repositories.Delete(context.Background(), "o", "r") - if err != nil { - t.Errorf("Repositories.Delete returned error: %v", err) - } -} - -func TestRepositoriesService_Get_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.Get(context.Background(), "%", "r") - testURLParseError(t, err) -} - -func TestRepositoriesService_Edit_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.Edit(context.Background(), "%", "r", nil) - testURLParseError(t, err) -} - -func TestRepositoriesService_ListContributors(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/contributors", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "anon": "true", - "page": "2", - }) - fmt.Fprint(w, `[{"contributions":42}]`) - }) - - opts := &ListContributorsOptions{Anon: "true", ListOptions: ListOptions{Page: 2}} - contributors, _, err := client.Repositories.ListContributors(context.Background(), "o", "r", opts) - if err != nil { - t.Errorf("Repositories.ListContributors returned error: %v", err) - } - - want := []*Contributor{{Contributions: Int(42)}} - if !reflect.DeepEqual(contributors, want) { - t.Errorf("Repositories.ListContributors returned %+v, want %+v", contributors, want) - } -} - -func TestRepositoriesService_ListLanguages(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/languages", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"go":1}`) - }) - - languages, _, err := client.Repositories.ListLanguages(context.Background(), "o", "r") - if err != nil { - t.Errorf("Repositories.ListLanguages returned error: %v", err) - } - - want := map[string]int{"go": 1} - if !reflect.DeepEqual(languages, want) { - t.Errorf("Repositories.ListLanguages returned %+v, want %+v", languages, want) - } -} - -func TestRepositoriesService_ListTeams(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/teams", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - teams, _, err := client.Repositories.ListTeams(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListTeams returned error: %v", err) - } - - want := []*Team{{ID: Int(1)}} - if !reflect.DeepEqual(teams, want) { - t.Errorf("Repositories.ListTeams returned %+v, want %+v", teams, want) - } -} - -func TestRepositoriesService_ListTags(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/tags", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"name":"n", "commit" : {"sha" : "s", "url" : "u"}, "zipball_url": "z", "tarball_url": "t"}]`) - }) - - opt := &ListOptions{Page: 2} - tags, _, err := client.Repositories.ListTags(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListTags returned error: %v", err) - } - - want := []*RepositoryTag{ - { - Name: String("n"), - Commit: &Commit{ - SHA: String("s"), - URL: String("u"), - }, - ZipballURL: String("z"), - TarballURL: String("t"), - }, - } - if !reflect.DeepEqual(tags, want) { - t.Errorf("Repositories.ListTags returned %+v, want %+v", tags, want) - } -} - -func TestRepositoriesService_ListBranches(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/branches", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeProtectedBranchesPreview) - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"name":"master", "commit" : {"sha" : "a57781", "url" : "https://api.github.com/repos/o/r/commits/a57781"}}]`) - }) - - opt := &ListOptions{Page: 2} - branches, _, err := client.Repositories.ListBranches(context.Background(), "o", "r", opt) - if err != nil { - t.Errorf("Repositories.ListBranches returned error: %v", err) - } - - want := []*Branch{{Name: String("master"), Commit: &RepositoryCommit{SHA: String("a57781"), URL: String("https://api.github.com/repos/o/r/commits/a57781")}}} - if !reflect.DeepEqual(branches, want) { - t.Errorf("Repositories.ListBranches returned %+v, want %+v", branches, want) - } -} - -func TestRepositoriesService_GetBranch(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/branches/b", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeProtectedBranchesPreview) - fmt.Fprint(w, `{"name":"n", "commit":{"sha":"s","commit":{"message":"m"}}, "protected":true}`) - }) - - branch, _, err := client.Repositories.GetBranch(context.Background(), "o", "r", "b") - if err != nil { - t.Errorf("Repositories.GetBranch returned error: %v", err) - } - - want := &Branch{ - Name: String("n"), - Commit: &RepositoryCommit{ - SHA: String("s"), - Commit: &Commit{ - Message: String("m"), - }, - }, - Protected: Bool(true), - } - - if !reflect.DeepEqual(branch, want) { - t.Errorf("Repositories.GetBranch returned %+v, want %+v", branch, want) - } -} - -func TestRepositoriesService_GetBranchProtection(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/branches/b/protection", func(w http.ResponseWriter, r *http.Request) { - v := new(ProtectionRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeProtectedBranchesPreview) - fmt.Fprintf(w, `{"required_status_checks":{"include_admins":true,"strict":true,"contexts":["continuous-integration"]},"required_pull_request_reviews":{"include_admins":true},"enforce_admins":{"url":"/repos/o/r/branches/b/protection/enforce_admins","enabled":true},"restrictions":{"users":[{"id":1,"login":"u"}],"teams":[{"id":2,"slug":"t"}]}}`) - }) - - protection, _, err := client.Repositories.GetBranchProtection(context.Background(), "o", "r", "b") - if err != nil { - t.Errorf("Repositories.GetBranchProtection returned error: %v", err) - } - - want := &Protection{ - RequiredStatusChecks: &RequiredStatusChecks{ - IncludeAdmins: true, - Strict: true, - Contexts: []string{"continuous-integration"}, - }, - RequiredPullRequestReviews: &RequiredPullRequestReviews{ - IncludeAdmins: true, - }, - EnforceAdmins: &AdminEnforcement{ - URL: String("/repos/o/r/branches/b/protection/enforce_admins"), - Enabled: true, - }, - Restrictions: &BranchRestrictions{ - Users: []*User{ - {Login: String("u"), ID: Int(1)}, - }, - Teams: []*Team{ - {Slug: String("t"), ID: Int(2)}, - }, - }, - } - if !reflect.DeepEqual(protection, want) { - t.Errorf("Repositories.GetBranchProtection returned %+v, want %+v", protection, want) - } -} - -func TestRepositoriesService_UpdateBranchProtection(t *testing.T) { - setup() - defer teardown() - - input := &ProtectionRequest{ - RequiredStatusChecks: &RequiredStatusChecks{ - IncludeAdmins: true, - Strict: true, - Contexts: []string{"continuous-integration"}, - }, - RequiredPullRequestReviews: &RequiredPullRequestReviews{ - IncludeAdmins: true, - }, - Restrictions: &BranchRestrictionsRequest{ - Users: []string{"u"}, - Teams: []string{"t"}, - }, - } - - mux.HandleFunc("/repos/o/r/branches/b/protection", func(w http.ResponseWriter, r *http.Request) { - v := new(ProtectionRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PUT") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - testHeader(t, r, "Accept", mediaTypeProtectedBranchesPreview) - fmt.Fprintf(w, `{"required_status_checks":{"include_admins":true,"strict":true,"contexts":["continuous-integration"]},"required_pull_request_reviews":{"include_admins":true},"restrictions":{"users":[{"id":1,"login":"u"}],"teams":[{"id":2,"slug":"t"}]}}`) - }) - - protection, _, err := client.Repositories.UpdateBranchProtection(context.Background(), "o", "r", "b", input) - if err != nil { - t.Errorf("Repositories.UpdateBranchProtection returned error: %v", err) - } - - want := &Protection{ - RequiredStatusChecks: &RequiredStatusChecks{ - IncludeAdmins: true, - Strict: true, - Contexts: []string{"continuous-integration"}, - }, - RequiredPullRequestReviews: &RequiredPullRequestReviews{ - IncludeAdmins: true, - }, - Restrictions: &BranchRestrictions{ - Users: []*User{ - {Login: String("u"), ID: Int(1)}, - }, - Teams: []*Team{ - {Slug: String("t"), ID: Int(2)}, - }, - }, - } - if !reflect.DeepEqual(protection, want) { - t.Errorf("Repositories.UpdateBranchProtection returned %+v, want %+v", protection, want) - } -} - -func TestRepositoriesService_RemoveBranchProtection(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/branches/b/protection", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - testHeader(t, r, "Accept", mediaTypeProtectedBranchesPreview) - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Repositories.RemoveBranchProtection(context.Background(), "o", "r", "b") - if err != nil { - t.Errorf("Repositories.RemoveBranchProtection returned error: %v", err) - } -} - -func TestRepositoriesService_ListLanguages_invalidOwner(t *testing.T) { - _, _, err := client.Repositories.ListLanguages(context.Background(), "%", "%") - testURLParseError(t, err) -} - -func TestRepositoriesService_License(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/license", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"name": "LICENSE", "path": "LICENSE", "license":{"key":"mit","name":"MIT License","spdx_id":"MIT","url":"https://api.github.com/licenses/mit","featured":true}}`) - }) - - got, _, err := client.Repositories.License(context.Background(), "o", "r") - if err != nil { - t.Errorf("Repositories.License returned error: %v", err) - } - - want := &RepositoryLicense{ - Name: String("LICENSE"), - Path: String("LICENSE"), - License: &License{ - Name: String("MIT License"), - Key: String("mit"), - SPDXID: String("MIT"), - URL: String("https://api.github.com/licenses/mit"), - Featured: Bool(true), - }, - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("Repositories.License returned %+v, want %+v", got, want) - } -} - -func TestRepositoriesService_GetRequiredStatusChecks(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/branches/b/protection/required_status_checks", func(w http.ResponseWriter, r *http.Request) { - v := new(ProtectionRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeProtectedBranchesPreview) - fmt.Fprint(w, `{"include_admins": true,"strict": true,"contexts": ["x","y","z"]}`) - }) - - checks, _, err := client.Repositories.GetRequiredStatusChecks(context.Background(), "o", "r", "b") - if err != nil { - t.Errorf("Repositories.GetRequiredStatusChecks returned error: %v", err) - } - - want := &RequiredStatusChecks{ - IncludeAdmins: true, - Strict: true, - Contexts: []string{"x", "y", "z"}, - } - if !reflect.DeepEqual(checks, want) { - t.Errorf("Repositories.GetRequiredStatusChecks returned %+v, want %+v", checks, want) - } -} - -func TestRepositoriesService_ListRequiredStatusChecksContexts(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/branches/b/protection/required_status_checks/contexts", func(w http.ResponseWriter, r *http.Request) { - v := new(ProtectionRequest) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeProtectedBranchesPreview) - fmt.Fprint(w, `["x", "y", "z"]`) - }) - - contexts, _, err := client.Repositories.ListRequiredStatusChecksContexts(context.Background(), "o", "r", "b") - if err != nil { - t.Errorf("Repositories.ListRequiredStatusChecksContexts returned error: %v", err) - } - - want := []string{"x", "y", "z"} - if !reflect.DeepEqual(contexts, want) { - t.Errorf("Repositories.ListRequiredStatusChecksContexts returned %+v, want %+v", contexts, want) - } -} diff --git a/vendor/github.com/google/go-github/github/repos_traffic_test.go b/vendor/github.com/google/go-github/github/repos_traffic_test.go deleted file mode 100644 index c425f5cd5d14..000000000000 --- a/vendor/github.com/google/go-github/github/repos_traffic_test.go +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "testing" - "time" -) - -func TestRepositoriesService_ListTrafficReferrers(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/traffic/popular/referrers", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprintf(w, `[{ - "referrer": "Google", - "count": 4, - "uniques": 3 - }]`) - }) - referrers, _, err := client.Repositories.ListTrafficReferrers(context.Background(), "o", "r") - if err != nil { - t.Errorf("Repositories.ListPaths returned error: %+v", err) - } - - want := []*TrafficReferrer{{ - Referrer: String("Google"), - Count: Int(4), - Uniques: Int(3), - }} - if !reflect.DeepEqual(referrers, want) { - t.Errorf("Repositories.ListReferrers returned %+v, want %+v", referrers, want) - } - -} - -func TestRepositoriesService_ListTrafficPaths(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/traffic/popular/paths", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprintf(w, `[{ - "path": "/github/hubot", - "title": "github/hubot: A customizable life embetterment robot.", - "count": 3542, - "uniques": 2225 - }]`) - }) - paths, _, err := client.Repositories.ListTrafficPaths(context.Background(), "o", "r") - if err != nil { - t.Errorf("Repositories.ListPaths returned error: %+v", err) - } - - want := []*TrafficPath{{ - Path: String("/github/hubot"), - Title: String("github/hubot: A customizable life embetterment robot."), - Count: Int(3542), - Uniques: Int(2225), - }} - if !reflect.DeepEqual(paths, want) { - t.Errorf("Repositories.ListPaths returned %+v, want %+v", paths, want) - } - -} - -func TestRepositoriesService_ListTrafficViews(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/traffic/views", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprintf(w, `{"count": 7, - "uniques": 6, - "views": [{ - "timestamp": "2016-05-31T16:00:00.000Z", - "count": 7, - "uniques": 6 - }]}`) - }) - - views, _, err := client.Repositories.ListTrafficViews(context.Background(), "o", "r", nil) - if err != nil { - t.Errorf("Repositories.ListPaths returned error: %+v", err) - } - - want := &TrafficViews{ - Views: []*TrafficData{{ - Timestamp: &Timestamp{time.Date(2016, time.May, 31, 16, 0, 0, 0, time.UTC)}, - Count: Int(7), - Uniques: Int(6), - }}, - Count: Int(7), - Uniques: Int(6), - } - - if !reflect.DeepEqual(views, want) { - t.Errorf("Repositories.ListViews returned %+v, want %+v", views, want) - } - -} - -func TestRepositoriesService_ListTrafficClones(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/traffic/clones", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprintf(w, `{"count": 7, - "uniques": 6, - "clones": [{ - "timestamp": "2016-05-31T16:00:00.00Z", - "count": 7, - "uniques": 6 - }]}`) - }) - - clones, _, err := client.Repositories.ListTrafficClones(context.Background(), "o", "r", nil) - if err != nil { - t.Errorf("Repositories.ListPaths returned error: %+v", err) - } - - want := &TrafficClones{ - Clones: []*TrafficData{{ - Timestamp: &Timestamp{time.Date(2016, time.May, 31, 16, 0, 0, 0, time.UTC)}, - Count: Int(7), - Uniques: Int(6), - }}, - Count: Int(7), - Uniques: Int(6), - } - - if !reflect.DeepEqual(clones, want) { - t.Errorf("Repositories.ListViews returned %+v, want %+v", clones, want) - } - -} diff --git a/vendor/github.com/google/go-github/github/search_test.go b/vendor/github.com/google/go-github/github/search_test.go deleted file mode 100644 index ee2f69be2a33..000000000000 --- a/vendor/github.com/google/go-github/github/search_test.go +++ /dev/null @@ -1,239 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - - "testing" -) - -func TestSearchService_Repositories(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/search/repositories", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "q": "blah", - "sort": "forks", - "order": "desc", - "page": "2", - "per_page": "2", - }) - - fmt.Fprint(w, `{"total_count": 4, "incomplete_results": false, "items": [{"id":1},{"id":2}]}`) - }) - - opts := &SearchOptions{Sort: "forks", Order: "desc", ListOptions: ListOptions{Page: 2, PerPage: 2}} - result, _, err := client.Search.Repositories(context.Background(), "blah", opts) - if err != nil { - t.Errorf("Search.Repositories returned error: %v", err) - } - - want := &RepositoriesSearchResult{ - Total: Int(4), - IncompleteResults: Bool(false), - Repositories: []Repository{{ID: Int(1)}, {ID: Int(2)}}, - } - if !reflect.DeepEqual(result, want) { - t.Errorf("Search.Repositories returned %+v, want %+v", result, want) - } -} - -func TestSearchService_Commits(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/search/commits", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "q": "blah", - "sort": "author-date", - "order": "desc", - }) - - fmt.Fprint(w, `{"total_count": 4, "incomplete_results": false, "items": [{"sha":"random_hash1"},{"sha":"random_hash2"}]}`) - }) - - opts := &SearchOptions{Sort: "author-date", Order: "desc"} - result, _, err := client.Search.Commits(context.Background(), "blah", opts) - if err != nil { - t.Errorf("Search.Commits returned error: %v", err) - } - - want := &CommitsSearchResult{ - Total: Int(4), - IncompleteResults: Bool(false), - Commits: []*CommitResult{{SHA: String("random_hash1")}, {SHA: String("random_hash2")}}, - } - if !reflect.DeepEqual(result, want) { - t.Errorf("Search.Commits returned %+v, want %+v", result, want) - } -} - -func TestSearchService_Issues(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/search/issues", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "q": "blah", - "sort": "forks", - "order": "desc", - "page": "2", - "per_page": "2", - }) - - fmt.Fprint(w, `{"total_count": 4, "incomplete_results": true, "items": [{"number":1},{"number":2}]}`) - }) - - opts := &SearchOptions{Sort: "forks", Order: "desc", ListOptions: ListOptions{Page: 2, PerPage: 2}} - result, _, err := client.Search.Issues(context.Background(), "blah", opts) - if err != nil { - t.Errorf("Search.Issues returned error: %v", err) - } - - want := &IssuesSearchResult{ - Total: Int(4), - IncompleteResults: Bool(true), - Issues: []Issue{{Number: Int(1)}, {Number: Int(2)}}, - } - if !reflect.DeepEqual(result, want) { - t.Errorf("Search.Issues returned %+v, want %+v", result, want) - } -} - -func TestSearchService_Users(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/search/users", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "q": "blah", - "sort": "forks", - "order": "desc", - "page": "2", - "per_page": "2", - }) - - fmt.Fprint(w, `{"total_count": 4, "incomplete_results": false, "items": [{"id":1},{"id":2}]}`) - }) - - opts := &SearchOptions{Sort: "forks", Order: "desc", ListOptions: ListOptions{Page: 2, PerPage: 2}} - result, _, err := client.Search.Users(context.Background(), "blah", opts) - if err != nil { - t.Errorf("Search.Issues returned error: %v", err) - } - - want := &UsersSearchResult{ - Total: Int(4), - IncompleteResults: Bool(false), - Users: []User{{ID: Int(1)}, {ID: Int(2)}}, - } - if !reflect.DeepEqual(result, want) { - t.Errorf("Search.Users returned %+v, want %+v", result, want) - } -} - -func TestSearchService_Code(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/search/code", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "q": "blah", - "sort": "forks", - "order": "desc", - "page": "2", - "per_page": "2", - }) - - fmt.Fprint(w, `{"total_count": 4, "incomplete_results": false, "items": [{"name":"1"},{"name":"2"}]}`) - }) - - opts := &SearchOptions{Sort: "forks", Order: "desc", ListOptions: ListOptions{Page: 2, PerPage: 2}} - result, _, err := client.Search.Code(context.Background(), "blah", opts) - if err != nil { - t.Errorf("Search.Code returned error: %v", err) - } - - want := &CodeSearchResult{ - Total: Int(4), - IncompleteResults: Bool(false), - CodeResults: []CodeResult{{Name: String("1")}, {Name: String("2")}}, - } - if !reflect.DeepEqual(result, want) { - t.Errorf("Search.Code returned %+v, want %+v", result, want) - } -} - -func TestSearchService_CodeTextMatch(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/search/code", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - - textMatchResponse := ` - { - "total_count": 1, - "incomplete_results": false, - "items": [ - { - "name":"gopher1", - "text_matches": [ - { - "fragment": "I'm afraid my friend what you have found\nIs a gopher who lives to feed", - "matches": [ - { - "text": "gopher", - "indices": [ - 14, - 21 - ] - } - ] - } - ] - } - ] - } - ` - - fmt.Fprint(w, textMatchResponse) - }) - - opts := &SearchOptions{Sort: "forks", Order: "desc", ListOptions: ListOptions{Page: 2, PerPage: 2}, TextMatch: true} - result, _, err := client.Search.Code(context.Background(), "blah", opts) - if err != nil { - t.Errorf("Search.Code returned error: %v", err) - } - - wantedCodeResult := CodeResult{ - Name: String("gopher1"), - TextMatches: []TextMatch{{ - Fragment: String("I'm afraid my friend what you have found\nIs a gopher who lives to feed"), - Matches: []Match{{Text: String("gopher"), Indices: []int{14, 21}}}, - }, - }, - } - - want := &CodeSearchResult{ - Total: Int(1), - IncompleteResults: Bool(false), - CodeResults: []CodeResult{wantedCodeResult}, - } - if !reflect.DeepEqual(result, want) { - t.Errorf("Search.Code returned %+v, want %+v", result, want) - } -} diff --git a/vendor/github.com/google/go-github/github/strings_test.go b/vendor/github.com/google/go-github/github/strings_test.go deleted file mode 100644 index 6af88acd390a..000000000000 --- a/vendor/github.com/google/go-github/github/strings_test.go +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "fmt" - "testing" - "time" -) - -func TestStringify(t *testing.T) { - var nilPointer *string - - var tests = []struct { - in interface{} - out string - }{ - // basic types - {"foo", `"foo"`}, - {123, `123`}, - {1.5, `1.5`}, - {false, `false`}, - { - []string{"a", "b"}, - `["a" "b"]`, - }, - { - struct { - A []string - }{nil}, - // nil slice is skipped - `{}`, - }, - { - struct { - A string - }{"foo"}, - // structs not of a named type get no prefix - `{A:"foo"}`, - }, - - // pointers - {nilPointer, ``}, - {String("foo"), `"foo"`}, - {Int(123), `123`}, - {Bool(false), `false`}, - { - []*string{String("a"), String("b")}, - `["a" "b"]`, - }, - - // actual GitHub structs - { - Timestamp{time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC)}, - `github.Timestamp{2006-01-02 15:04:05 +0000 UTC}`, - }, - { - &Timestamp{time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC)}, - `github.Timestamp{2006-01-02 15:04:05 +0000 UTC}`, - }, - { - User{ID: Int(123), Name: String("n")}, - `github.User{ID:123, Name:"n"}`, - }, - { - Repository{Owner: &User{ID: Int(123)}}, - `github.Repository{Owner:github.User{ID:123}}`, - }, - } - - for i, tt := range tests { - s := Stringify(tt.in) - if s != tt.out { - t.Errorf("%d. Stringify(%q) => %q, want %q", i, tt.in, s, tt.out) - } - } -} - -// Directly test the String() methods on various GitHub types. We don't do an -// exaustive test of all the various field types, since TestStringify() above -// takes care of that. Rather, we just make sure that Stringify() is being -// used to build the strings, which we do by verifying that pointers are -// stringified as their underlying value. -func TestString(t *testing.T) { - var tests = []struct { - in interface{} - out string - }{ - {CodeResult{Name: String("n")}, `github.CodeResult{Name:"n"}`}, - {CommitAuthor{Name: String("n")}, `github.CommitAuthor{Name:"n"}`}, - {CommitFile{SHA: String("s")}, `github.CommitFile{SHA:"s"}`}, - {CommitStats{Total: Int(1)}, `github.CommitStats{Total:1}`}, - {CommitsComparison{TotalCommits: Int(1)}, `github.CommitsComparison{TotalCommits:1}`}, - {Commit{SHA: String("s")}, `github.Commit{SHA:"s"}`}, - {Event{ID: String("1")}, `github.Event{ID:"1"}`}, - {GistComment{ID: Int(1)}, `github.GistComment{ID:1}`}, - {GistFile{Size: Int(1)}, `github.GistFile{Size:1}`}, - {Gist{ID: String("1")}, `github.Gist{ID:"1", Files:map[]}`}, - {GitObject{SHA: String("s")}, `github.GitObject{SHA:"s"}`}, - {Gitignore{Name: String("n")}, `github.Gitignore{Name:"n"}`}, - {Hook{ID: Int(1)}, `github.Hook{Config:map[], ID:1}`}, - {IssueComment{ID: Int(1)}, `github.IssueComment{ID:1}`}, - {Issue{Number: Int(1)}, `github.Issue{Number:1}`}, - {Key{ID: Int(1)}, `github.Key{ID:1}`}, - {Label{ID: Int(1), Name: String("l")}, `github.Label{ID:1, Name:"l"}`}, - {Organization{ID: Int(1)}, `github.Organization{ID:1}`}, - {PullRequestComment{ID: Int(1)}, `github.PullRequestComment{ID:1}`}, - {PullRequest{Number: Int(1)}, `github.PullRequest{Number:1}`}, - {PullRequestReview{ID: Int(1)}, `github.PullRequestReview{ID:1}`}, - {DraftReviewComment{Position: Int(1)}, `github.DraftReviewComment{Position:1}`}, - {PullRequestReviewRequest{Body: String("r")}, `github.PullRequestReviewRequest{Body:"r"}`}, - {PullRequestReviewDismissalRequest{Message: String("r")}, `github.PullRequestReviewDismissalRequest{Message:"r"}`}, - {PushEventCommit{SHA: String("s")}, `github.PushEventCommit{SHA:"s"}`}, - {PushEvent{PushID: Int(1)}, `github.PushEvent{PushID:1}`}, - {Reference{Ref: String("r")}, `github.Reference{Ref:"r"}`}, - {ReleaseAsset{ID: Int(1)}, `github.ReleaseAsset{ID:1}`}, - {RepoStatus{ID: Int(1)}, `github.RepoStatus{ID:1}`}, - {RepositoryComment{ID: Int(1)}, `github.RepositoryComment{ID:1}`}, - {RepositoryCommit{SHA: String("s")}, `github.RepositoryCommit{SHA:"s"}`}, - {RepositoryContent{Name: String("n")}, `github.RepositoryContent{Name:"n"}`}, - {RepositoryRelease{ID: Int(1)}, `github.RepositoryRelease{ID:1}`}, - {Repository{ID: Int(1)}, `github.Repository{ID:1}`}, - {Team{ID: Int(1)}, `github.Team{ID:1}`}, - {TreeEntry{SHA: String("s")}, `github.TreeEntry{SHA:"s"}`}, - {Tree{SHA: String("s")}, `github.Tree{SHA:"s"}`}, - {User{ID: Int(1)}, `github.User{ID:1}`}, - {WebHookAuthor{Name: String("n")}, `github.WebHookAuthor{Name:"n"}`}, - {WebHookCommit{ID: String("1")}, `github.WebHookCommit{ID:"1"}`}, - {WebHookPayload{Ref: String("r")}, `github.WebHookPayload{Ref:"r"}`}, - } - - for i, tt := range tests { - s := tt.in.(fmt.Stringer).String() - if s != tt.out { - t.Errorf("%d. String() => %q, want %q", i, tt.in, tt.out) - } - } -} diff --git a/vendor/github.com/google/go-github/github/timestamp_test.go b/vendor/github.com/google/go-github/github/timestamp_test.go deleted file mode 100644 index 997b43db899c..000000000000 --- a/vendor/github.com/google/go-github/github/timestamp_test.go +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "encoding/json" - "fmt" - "testing" - "time" -) - -const ( - emptyTimeStr = `"0001-01-01T00:00:00Z"` - referenceTimeStr = `"2006-01-02T15:04:05Z"` - referenceUnixTimeStr = `1136214245` -) - -var ( - referenceTime = time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC) - unixOrigin = time.Unix(0, 0).In(time.UTC) -) - -func TestTimestamp_Marshal(t *testing.T) { - testCases := []struct { - desc string - data Timestamp - want string - wantErr bool - equal bool - }{ - {"Reference", Timestamp{referenceTime}, referenceTimeStr, false, true}, - {"Empty", Timestamp{}, emptyTimeStr, false, true}, - {"Mismatch", Timestamp{}, referenceTimeStr, false, false}, - } - for _, tc := range testCases { - out, err := json.Marshal(tc.data) - if gotErr := err != nil; gotErr != tc.wantErr { - t.Errorf("%s: gotErr=%v, wantErr=%v, err=%v", tc.desc, gotErr, tc.wantErr, err) - } - got := string(out) - equal := got == tc.want - if (got == tc.want) != tc.equal { - t.Errorf("%s: got=%s, want=%s, equal=%v, want=%v", tc.desc, got, tc.want, equal, tc.equal) - } - } -} - -func TestTimestamp_Unmarshal(t *testing.T) { - testCases := []struct { - desc string - data string - want Timestamp - wantErr bool - equal bool - }{ - {"Reference", referenceTimeStr, Timestamp{referenceTime}, false, true}, - {"ReferenceUnix", `1136214245`, Timestamp{referenceTime}, false, true}, - {"Empty", emptyTimeStr, Timestamp{}, false, true}, - {"UnixStart", `0`, Timestamp{unixOrigin}, false, true}, - {"Mismatch", referenceTimeStr, Timestamp{}, false, false}, - {"MismatchUnix", `0`, Timestamp{}, false, false}, - {"Invalid", `"asdf"`, Timestamp{referenceTime}, true, false}, - } - for _, tc := range testCases { - var got Timestamp - err := json.Unmarshal([]byte(tc.data), &got) - if gotErr := err != nil; gotErr != tc.wantErr { - t.Errorf("%s: gotErr=%v, wantErr=%v, err=%v", tc.desc, gotErr, tc.wantErr, err) - continue - } - equal := got.Equal(tc.want) - if equal != tc.equal { - t.Errorf("%s: got=%#v, want=%#v, equal=%v, want=%v", tc.desc, got, tc.want, equal, tc.equal) - } - } -} - -func TestTimstamp_MarshalReflexivity(t *testing.T) { - testCases := []struct { - desc string - data Timestamp - }{ - {"Reference", Timestamp{referenceTime}}, - {"Empty", Timestamp{}}, - } - for _, tc := range testCases { - data, err := json.Marshal(tc.data) - if err != nil { - t.Errorf("%s: Marshal err=%v", tc.desc, err) - } - var got Timestamp - err = json.Unmarshal(data, &got) - if err != nil { - t.Errorf("%s: Unmarshal err=%v", tc.desc, err) - } - if !got.Equal(tc.data) { - t.Errorf("%s: %+v != %+v", tc.desc, got, data) - } - } -} - -type WrappedTimestamp struct { - A int - Time Timestamp -} - -func TestWrappedTimstamp_Marshal(t *testing.T) { - testCases := []struct { - desc string - data WrappedTimestamp - want string - wantErr bool - equal bool - }{ - {"Reference", WrappedTimestamp{0, Timestamp{referenceTime}}, fmt.Sprintf(`{"A":0,"Time":%s}`, referenceTimeStr), false, true}, - {"Empty", WrappedTimestamp{}, fmt.Sprintf(`{"A":0,"Time":%s}`, emptyTimeStr), false, true}, - {"Mismatch", WrappedTimestamp{}, fmt.Sprintf(`{"A":0,"Time":%s}`, referenceTimeStr), false, false}, - } - for _, tc := range testCases { - out, err := json.Marshal(tc.data) - if gotErr := err != nil; gotErr != tc.wantErr { - t.Errorf("%s: gotErr=%v, wantErr=%v, err=%v", tc.desc, gotErr, tc.wantErr, err) - } - got := string(out) - equal := got == tc.want - if equal != tc.equal { - t.Errorf("%s: got=%s, want=%s, equal=%v, want=%v", tc.desc, got, tc.want, equal, tc.equal) - } - } -} - -func TestWrappedTimstamp_Unmarshal(t *testing.T) { - testCases := []struct { - desc string - data string - want WrappedTimestamp - wantErr bool - equal bool - }{ - {"Reference", referenceTimeStr, WrappedTimestamp{0, Timestamp{referenceTime}}, false, true}, - {"ReferenceUnix", referenceUnixTimeStr, WrappedTimestamp{0, Timestamp{referenceTime}}, false, true}, - {"Empty", emptyTimeStr, WrappedTimestamp{0, Timestamp{}}, false, true}, - {"UnixStart", `0`, WrappedTimestamp{0, Timestamp{unixOrigin}}, false, true}, - {"Mismatch", referenceTimeStr, WrappedTimestamp{0, Timestamp{}}, false, false}, - {"MismatchUnix", `0`, WrappedTimestamp{0, Timestamp{}}, false, false}, - {"Invalid", `"asdf"`, WrappedTimestamp{0, Timestamp{referenceTime}}, true, false}, - } - for _, tc := range testCases { - var got Timestamp - err := json.Unmarshal([]byte(tc.data), &got) - if gotErr := err != nil; gotErr != tc.wantErr { - t.Errorf("%s: gotErr=%v, wantErr=%v, err=%v", tc.desc, gotErr, tc.wantErr, err) - continue - } - equal := got.Time.Equal(tc.want.Time.Time) - if equal != tc.equal { - t.Errorf("%s: got=%#v, want=%#v, equal=%v, want=%v", tc.desc, got, tc.want, equal, tc.equal) - } - } -} - -func TestWrappedTimstamp_MarshalReflexivity(t *testing.T) { - testCases := []struct { - desc string - data WrappedTimestamp - }{ - {"Reference", WrappedTimestamp{0, Timestamp{referenceTime}}}, - {"Empty", WrappedTimestamp{0, Timestamp{}}}, - } - for _, tc := range testCases { - bytes, err := json.Marshal(tc.data) - if err != nil { - t.Errorf("%s: Marshal err=%v", tc.desc, err) - } - var got WrappedTimestamp - err = json.Unmarshal(bytes, &got) - if err != nil { - t.Errorf("%s: Unmarshal err=%v", tc.desc, err) - } - if !got.Time.Equal(tc.data.Time) { - t.Errorf("%s: %+v != %+v", tc.desc, got, tc.data) - } - } -} diff --git a/vendor/github.com/google/go-github/github/users_administration_test.go b/vendor/github.com/google/go-github/github/users_administration_test.go deleted file mode 100644 index 8f02b88cea77..000000000000 --- a/vendor/github.com/google/go-github/github/users_administration_test.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "net/http" - "testing" -) - -func TestUsersService_PromoteSiteAdmin(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/site_admin", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Users.PromoteSiteAdmin(context.Background(), "u") - if err != nil { - t.Errorf("Users.PromoteSiteAdmin returned error: %v", err) - } -} - -func TestUsersService_DemoteSiteAdmin(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/site_admin", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Users.DemoteSiteAdmin(context.Background(), "u") - if err != nil { - t.Errorf("Users.DemoteSiteAdmin returned error: %v", err) - } -} - -func TestUsersService_Suspend(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/suspended", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Users.Suspend(context.Background(), "u") - if err != nil { - t.Errorf("Users.Suspend returned error: %v", err) - } -} - -func TestUsersService_Unsuspend(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/suspended", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Users.Unsuspend(context.Background(), "u") - if err != nil { - t.Errorf("Users.Unsuspend returned error: %v", err) - } -} diff --git a/vendor/github.com/google/go-github/github/users_blocking_test.go b/vendor/github.com/google/go-github/github/users_blocking_test.go deleted file mode 100644 index ea7a8abdc23a..000000000000 --- a/vendor/github.com/google/go-github/github/users_blocking_test.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestUsersService_ListBlockedUsers(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/blocks", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeBlockUsersPreview) - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{ - "login": "octocat" - }]`) - }) - - opt := &ListOptions{Page: 2} - blockedUsers, _, err := client.Users.ListBlockedUsers(context.Background(), opt) - if err != nil { - t.Errorf("Users.ListBlockedUsers returned error: %v", err) - } - - want := []*User{{Login: String("octocat")}} - if !reflect.DeepEqual(blockedUsers, want) { - t.Errorf("Users.ListBlockedUsers returned %+v, want %+v", blockedUsers, want) - } -} - -func TestUsersService_IsBlocked(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/blocks/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeBlockUsersPreview) - w.WriteHeader(http.StatusNoContent) - }) - - isBlocked, _, err := client.Users.IsBlocked(context.Background(), "u") - if err != nil { - t.Errorf("Users.IsBlocked returned error: %v", err) - } - if want := true; isBlocked != want { - t.Errorf("Users.IsBlocked returned %+v, want %+v", isBlocked, want) - } -} - -func TestUsersService_BlockUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/blocks/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - testHeader(t, r, "Accept", mediaTypeBlockUsersPreview) - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Users.BlockUser(context.Background(), "u") - if err != nil { - t.Errorf("Users.BlockUser returned error: %v", err) - } -} - -func TestUsersService_UnblockUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/blocks/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - testHeader(t, r, "Accept", mediaTypeBlockUsersPreview) - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Users.UnblockUser(context.Background(), "u") - if err != nil { - t.Errorf("Users.UnblockUser returned error: %v", err) - } -} diff --git a/vendor/github.com/google/go-github/github/users_emails_test.go b/vendor/github.com/google/go-github/github/users_emails_test.go deleted file mode 100644 index 3f8176a00788..000000000000 --- a/vendor/github.com/google/go-github/github/users_emails_test.go +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestUsersService_ListEmails(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/emails", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{ - "email": "user@example.com", - "verified": false, - "primary": true - }]`) - }) - - opt := &ListOptions{Page: 2} - emails, _, err := client.Users.ListEmails(context.Background(), opt) - if err != nil { - t.Errorf("Users.ListEmails returned error: %v", err) - } - - want := []*UserEmail{{Email: String("user@example.com"), Verified: Bool(false), Primary: Bool(true)}} - if !reflect.DeepEqual(emails, want) { - t.Errorf("Users.ListEmails returned %+v, want %+v", emails, want) - } -} - -func TestUsersService_AddEmails(t *testing.T) { - setup() - defer teardown() - - input := []string{"new@example.com"} - - mux.HandleFunc("/user/emails", func(w http.ResponseWriter, r *http.Request) { - var v []string - json.NewDecoder(r.Body).Decode(&v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `[{"email":"old@example.com"}, {"email":"new@example.com"}]`) - }) - - emails, _, err := client.Users.AddEmails(context.Background(), input) - if err != nil { - t.Errorf("Users.AddEmails returned error: %v", err) - } - - want := []*UserEmail{ - {Email: String("old@example.com")}, - {Email: String("new@example.com")}, - } - if !reflect.DeepEqual(emails, want) { - t.Errorf("Users.AddEmails returned %+v, want %+v", emails, want) - } -} - -func TestUsersService_DeleteEmails(t *testing.T) { - setup() - defer teardown() - - input := []string{"user@example.com"} - - mux.HandleFunc("/user/emails", func(w http.ResponseWriter, r *http.Request) { - var v []string - json.NewDecoder(r.Body).Decode(&v) - - testMethod(t, r, "DELETE") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - }) - - _, err := client.Users.DeleteEmails(context.Background(), input) - if err != nil { - t.Errorf("Users.DeleteEmails returned error: %v", err) - } -} diff --git a/vendor/github.com/google/go-github/github/users_followers_test.go b/vendor/github.com/google/go-github/github/users_followers_test.go deleted file mode 100644 index 688af2c4450c..000000000000 --- a/vendor/github.com/google/go-github/github/users_followers_test.go +++ /dev/null @@ -1,223 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestUsersService_ListFollowers_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/followers", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - users, _, err := client.Users.ListFollowers(context.Background(), "", opt) - if err != nil { - t.Errorf("Users.ListFollowers returned error: %v", err) - } - - want := []*User{{ID: Int(1)}} - if !reflect.DeepEqual(users, want) { - t.Errorf("Users.ListFollowers returned %+v, want %+v", users, want) - } -} - -func TestUsersService_ListFollowers_specifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/followers", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":1}]`) - }) - - users, _, err := client.Users.ListFollowers(context.Background(), "u", nil) - if err != nil { - t.Errorf("Users.ListFollowers returned error: %v", err) - } - - want := []*User{{ID: Int(1)}} - if !reflect.DeepEqual(users, want) { - t.Errorf("Users.ListFollowers returned %+v, want %+v", users, want) - } -} - -func TestUsersService_ListFollowers_invalidUser(t *testing.T) { - _, _, err := client.Users.ListFollowers(context.Background(), "%", nil) - testURLParseError(t, err) -} - -func TestUsersService_ListFollowing_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/following", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opts := &ListOptions{Page: 2} - users, _, err := client.Users.ListFollowing(context.Background(), "", opts) - if err != nil { - t.Errorf("Users.ListFollowing returned error: %v", err) - } - - want := []*User{{ID: Int(1)}} - if !reflect.DeepEqual(users, want) { - t.Errorf("Users.ListFollowing returned %+v, want %+v", users, want) - } -} - -func TestUsersService_ListFollowing_specifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/following", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":1}]`) - }) - - users, _, err := client.Users.ListFollowing(context.Background(), "u", nil) - if err != nil { - t.Errorf("Users.ListFollowing returned error: %v", err) - } - - want := []*User{{ID: Int(1)}} - if !reflect.DeepEqual(users, want) { - t.Errorf("Users.ListFollowing returned %+v, want %+v", users, want) - } -} - -func TestUsersService_ListFollowing_invalidUser(t *testing.T) { - _, _, err := client.Users.ListFollowing(context.Background(), "%", nil) - testURLParseError(t, err) -} - -func TestUsersService_IsFollowing_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/following/t", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNoContent) - }) - - following, _, err := client.Users.IsFollowing(context.Background(), "", "t") - if err != nil { - t.Errorf("Users.IsFollowing returned error: %v", err) - } - if want := true; following != want { - t.Errorf("Users.IsFollowing returned %+v, want %+v", following, want) - } -} - -func TestUsersService_IsFollowing_specifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/following/t", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNoContent) - }) - - following, _, err := client.Users.IsFollowing(context.Background(), "u", "t") - if err != nil { - t.Errorf("Users.IsFollowing returned error: %v", err) - } - if want := true; following != want { - t.Errorf("Users.IsFollowing returned %+v, want %+v", following, want) - } -} - -func TestUsersService_IsFollowing_false(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/following/t", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - w.WriteHeader(http.StatusNotFound) - }) - - following, _, err := client.Users.IsFollowing(context.Background(), "u", "t") - if err != nil { - t.Errorf("Users.IsFollowing returned error: %v", err) - } - if want := false; following != want { - t.Errorf("Users.IsFollowing returned %+v, want %+v", following, want) - } -} - -func TestUsersService_IsFollowing_error(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/following/t", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - http.Error(w, "BadRequest", http.StatusBadRequest) - }) - - following, _, err := client.Users.IsFollowing(context.Background(), "u", "t") - if err == nil { - t.Errorf("Expected HTTP 400 response") - } - if want := false; following != want { - t.Errorf("Users.IsFollowing returned %+v, want %+v", following, want) - } -} - -func TestUsersService_IsFollowing_invalidUser(t *testing.T) { - _, _, err := client.Users.IsFollowing(context.Background(), "%", "%") - testURLParseError(t, err) -} - -func TestUsersService_Follow(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/following/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - }) - - _, err := client.Users.Follow(context.Background(), "u") - if err != nil { - t.Errorf("Users.Follow returned error: %v", err) - } -} - -func TestUsersService_Follow_invalidUser(t *testing.T) { - _, err := client.Users.Follow(context.Background(), "%") - testURLParseError(t, err) -} - -func TestUsersService_Unfollow(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/following/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Users.Unfollow(context.Background(), "u") - if err != nil { - t.Errorf("Users.Follow returned error: %v", err) - } -} - -func TestUsersService_Unfollow_invalidUser(t *testing.T) { - _, err := client.Users.Unfollow(context.Background(), "%") - testURLParseError(t, err) -} diff --git a/vendor/github.com/google/go-github/github/users_gpg_keys_test.go b/vendor/github.com/google/go-github/github/users_gpg_keys_test.go deleted file mode 100644 index f4180df98816..000000000000 --- a/vendor/github.com/google/go-github/github/users_gpg_keys_test.go +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestUsersService_ListGPGKeys_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/gpg_keys", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeGitSigningPreview) - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1,"primary_key_id":2}]`) - }) - - opt := &ListOptions{Page: 2} - keys, _, err := client.Users.ListGPGKeys(context.Background(), "", opt) - if err != nil { - t.Errorf("Users.ListGPGKeys returned error: %v", err) - } - - want := []*GPGKey{{ID: Int(1), PrimaryKeyID: Int(2)}} - if !reflect.DeepEqual(keys, want) { - t.Errorf("Users.ListGPGKeys = %+v, want %+v", keys, want) - } -} - -func TestUsersService_ListGPGKeys_specifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/gpg_keys", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeGitSigningPreview) - fmt.Fprint(w, `[{"id":1,"primary_key_id":2}]`) - }) - - keys, _, err := client.Users.ListGPGKeys(context.Background(), "u", nil) - if err != nil { - t.Errorf("Users.ListGPGKeys returned error: %v", err) - } - - want := []*GPGKey{{ID: Int(1), PrimaryKeyID: Int(2)}} - if !reflect.DeepEqual(keys, want) { - t.Errorf("Users.ListGPGKeys = %+v, want %+v", keys, want) - } -} - -func TestUsersService_ListGPGKeys_invalidUser(t *testing.T) { - _, _, err := client.Users.ListGPGKeys(context.Background(), "%", nil) - testURLParseError(t, err) -} - -func TestUsersService_GetGPGKey(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/gpg_keys/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeGitSigningPreview) - fmt.Fprint(w, `{"id":1}`) - }) - - key, _, err := client.Users.GetGPGKey(context.Background(), 1) - if err != nil { - t.Errorf("Users.GetGPGKey returned error: %v", err) - } - - want := &GPGKey{ID: Int(1)} - if !reflect.DeepEqual(key, want) { - t.Errorf("Users.GetGPGKey = %+v, want %+v", key, want) - } -} - -func TestUsersService_CreateGPGKey(t *testing.T) { - setup() - defer teardown() - - input := ` ------BEGIN PGP PUBLIC KEY BLOCK----- -Comment: GPGTools - https://gpgtools.org - -mQINBFcEd9kBEACo54TDbGhKlXKWMvJgecEUKPPcv7XdnpKdGb3LRw5MvFwT0V0f -... -=tqfb ------END PGP PUBLIC KEY BLOCK-----` - - mux.HandleFunc("/user/gpg_keys", func(w http.ResponseWriter, r *http.Request) { - var gpgKey struct { - ArmoredPublicKey *string `json:"armored_public_key,omitempty"` - } - json.NewDecoder(r.Body).Decode(&gpgKey) - - testMethod(t, r, "POST") - testHeader(t, r, "Accept", mediaTypeGitSigningPreview) - if gpgKey.ArmoredPublicKey == nil || *gpgKey.ArmoredPublicKey != input { - t.Errorf("gpgKey = %+v, want %q", gpgKey, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - gpgKey, _, err := client.Users.CreateGPGKey(context.Background(), input) - if err != nil { - t.Errorf("Users.GetGPGKey returned error: %v", err) - } - - want := &GPGKey{ID: Int(1)} - if !reflect.DeepEqual(gpgKey, want) { - t.Errorf("Users.GetGPGKey = %+v, want %+v", gpgKey, want) - } -} - -func TestUsersService_DeleteGPGKey(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/gpg_keys/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - testHeader(t, r, "Accept", mediaTypeGitSigningPreview) - }) - - _, err := client.Users.DeleteGPGKey(context.Background(), 1) - if err != nil { - t.Errorf("Users.DeleteGPGKey returned error: %v", err) - } -} diff --git a/vendor/github.com/google/go-github/github/users_keys_test.go b/vendor/github.com/google/go-github/github/users_keys_test.go deleted file mode 100644 index 8554c50cd924..000000000000 --- a/vendor/github.com/google/go-github/github/users_keys_test.go +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestUsersService_ListKeys_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/keys", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"page": "2"}) - fmt.Fprint(w, `[{"id":1}]`) - }) - - opt := &ListOptions{Page: 2} - keys, _, err := client.Users.ListKeys(context.Background(), "", opt) - if err != nil { - t.Errorf("Users.ListKeys returned error: %v", err) - } - - want := []*Key{{ID: Int(1)}} - if !reflect.DeepEqual(keys, want) { - t.Errorf("Users.ListKeys returned %+v, want %+v", keys, want) - } -} - -func TestUsersService_ListKeys_specifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u/keys", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":1}]`) - }) - - keys, _, err := client.Users.ListKeys(context.Background(), "u", nil) - if err != nil { - t.Errorf("Users.ListKeys returned error: %v", err) - } - - want := []*Key{{ID: Int(1)}} - if !reflect.DeepEqual(keys, want) { - t.Errorf("Users.ListKeys returned %+v, want %+v", keys, want) - } -} - -func TestUsersService_ListKeys_invalidUser(t *testing.T) { - _, _, err := client.Users.ListKeys(context.Background(), "%", nil) - testURLParseError(t, err) -} - -func TestUsersService_GetKey(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/keys/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - key, _, err := client.Users.GetKey(context.Background(), 1) - if err != nil { - t.Errorf("Users.GetKey returned error: %v", err) - } - - want := &Key{ID: Int(1)} - if !reflect.DeepEqual(key, want) { - t.Errorf("Users.GetKey returned %+v, want %+v", key, want) - } -} - -func TestUsersService_CreateKey(t *testing.T) { - setup() - defer teardown() - - input := &Key{Key: String("k"), Title: String("t")} - - mux.HandleFunc("/user/keys", func(w http.ResponseWriter, r *http.Request) { - v := new(Key) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "POST") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - key, _, err := client.Users.CreateKey(context.Background(), input) - if err != nil { - t.Errorf("Users.GetKey returned error: %v", err) - } - - want := &Key{ID: Int(1)} - if !reflect.DeepEqual(key, want) { - t.Errorf("Users.GetKey returned %+v, want %+v", key, want) - } -} - -func TestUsersService_DeleteKey(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/keys/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - }) - - _, err := client.Users.DeleteKey(context.Background(), 1) - if err != nil { - t.Errorf("Users.DeleteKey returned error: %v", err) - } -} diff --git a/vendor/github.com/google/go-github/github/users_test.go b/vendor/github.com/google/go-github/github/users_test.go deleted file mode 100644 index c2776a30d236..000000000000 --- a/vendor/github.com/google/go-github/github/users_test.go +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" -) - -func TestUser_marshall(t *testing.T) { - testJSONMarshal(t, &User{}, "{}") - - u := &User{ - Login: String("l"), - ID: Int(1), - URL: String("u"), - AvatarURL: String("a"), - GravatarID: String("g"), - Name: String("n"), - Company: String("c"), - Blog: String("b"), - Location: String("l"), - Email: String("e"), - Hireable: Bool(true), - PublicRepos: Int(1), - Followers: Int(1), - Following: Int(1), - CreatedAt: &Timestamp{referenceTime}, - SuspendedAt: &Timestamp{referenceTime}, - } - want := `{ - "login": "l", - "id": 1, - "avatar_url": "a", - "gravatar_id": "g", - "name": "n", - "company": "c", - "blog": "b", - "location": "l", - "email": "e", - "hireable": true, - "public_repos": 1, - "followers": 1, - "following": 1, - "created_at": ` + referenceTimeStr + `, - "suspended_at": ` + referenceTimeStr + `, - "url": "u" - }` - testJSONMarshal(t, u, want) -} - -func TestUsersService_Get_authenticatedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - user, _, err := client.Users.Get(context.Background(), "") - if err != nil { - t.Errorf("Users.Get returned error: %v", err) - } - - want := &User{ID: Int(1)} - if !reflect.DeepEqual(user, want) { - t.Errorf("Users.Get returned %+v, want %+v", user, want) - } -} - -func TestUsersService_Get_specifiedUser(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - user, _, err := client.Users.Get(context.Background(), "u") - if err != nil { - t.Errorf("Users.Get returned error: %v", err) - } - - want := &User{ID: Int(1)} - if !reflect.DeepEqual(user, want) { - t.Errorf("Users.Get returned %+v, want %+v", user, want) - } -} - -func TestUsersService_Get_invalidUser(t *testing.T) { - _, _, err := client.Users.Get(context.Background(), "%") - testURLParseError(t, err) -} - -func TestUsersService_GetByID(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1}`) - }) - - user, _, err := client.Users.GetByID(context.Background(), 1) - if err != nil { - t.Errorf("Users.GetByID returned error: %v", err) - } - - want := &User{ID: Int(1)} - if !reflect.DeepEqual(user, want) { - t.Errorf("Users.GetByID returned %+v, want %+v", user, want) - } -} - -func TestUsersService_Edit(t *testing.T) { - setup() - defer teardown() - - input := &User{Name: String("n")} - - mux.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) { - v := new(User) - json.NewDecoder(r.Body).Decode(v) - - testMethod(t, r, "PATCH") - if !reflect.DeepEqual(v, input) { - t.Errorf("Request body = %+v, want %+v", v, input) - } - - fmt.Fprint(w, `{"id":1}`) - }) - - user, _, err := client.Users.Edit(context.Background(), input) - if err != nil { - t.Errorf("Users.Edit returned error: %v", err) - } - - want := &User{ID: Int(1)} - if !reflect.DeepEqual(user, want) { - t.Errorf("Users.Edit returned %+v, want %+v", user, want) - } -} - -func TestUsersService_ListAll(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{"since": "1", "page": "2"}) - fmt.Fprint(w, `[{"id":2}]`) - }) - - opt := &UserListOptions{1, ListOptions{Page: 2}} - users, _, err := client.Users.ListAll(context.Background(), opt) - if err != nil { - t.Errorf("Users.Get returned error: %v", err) - } - - want := []*User{{ID: Int(2)}} - if !reflect.DeepEqual(users, want) { - t.Errorf("Users.ListAll returned %+v, want %+v", users, want) - } -} - -func TestUsersService_ListInvitations(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/repository_invitations", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeRepositoryInvitationsPreview) - fmt.Fprintf(w, `[{"id":1}, {"id":2}]`) - }) - - got, _, err := client.Users.ListInvitations(context.Background(), nil) - if err != nil { - t.Errorf("Users.ListInvitations returned error: %v", err) - } - - want := []*RepositoryInvitation{{ID: Int(1)}, {ID: Int(2)}} - if !reflect.DeepEqual(got, want) { - t.Errorf("Users.ListInvitations = %+v, want %+v", got, want) - } -} - -func TestUsersService_ListInvitations_withOptions(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/repository_invitations", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - testFormValues(t, r, values{ - "page": "2", - }) - testHeader(t, r, "Accept", mediaTypeRepositoryInvitationsPreview) - fmt.Fprintf(w, `[{"id":1}, {"id":2}]`) - }) - - _, _, err := client.Users.ListInvitations(context.Background(), &ListOptions{Page: 2}) - if err != nil { - t.Errorf("Users.ListInvitations returned error: %v", err) - } -} -func TestUsersService_AcceptInvitation(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/repository_invitations/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PATCH") - testHeader(t, r, "Accept", mediaTypeRepositoryInvitationsPreview) - w.WriteHeader(http.StatusNoContent) - }) - - if _, err := client.Users.AcceptInvitation(context.Background(), 1); err != nil { - t.Errorf("Users.AcceptInvitation returned error: %v", err) - } -} - -func TestUsersService_DeclineInvitation(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/user/repository_invitations/1", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - testHeader(t, r, "Accept", mediaTypeRepositoryInvitationsPreview) - w.WriteHeader(http.StatusNoContent) - }) - - if _, err := client.Users.DeclineInvitation(context.Background(), 1); err != nil { - t.Errorf("Users.DeclineInvitation returned error: %v", err) - } -} diff --git a/vendor/github.com/google/go-querystring/query/BUILD b/vendor/github.com/google/go-querystring/query/BUILD index 1d7c92465122..e0f6ff8ac2a6 100644 --- a/vendor/github.com/google/go-querystring/query/BUILD +++ b/vendor/github.com/google/go-querystring/query/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -7,13 +7,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = ["encode_test.go"], - importpath = "github.com/google/go-querystring/query", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/google/go-querystring/query/encode_test.go b/vendor/github.com/google/go-querystring/query/encode_test.go deleted file mode 100644 index 09efb0f5b14c..000000000000 --- a/vendor/github.com/google/go-querystring/query/encode_test.go +++ /dev/null @@ -1,286 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package query - -import ( - "fmt" - "net/url" - "reflect" - "testing" - "time" -) - -type Nested struct { - A SubNested `url:"a"` - B *SubNested `url:"b"` - Ptr *SubNested `url:"ptr,omitempty"` -} - -type SubNested struct { - Value string `url:"value"` -} - -func TestValues_types(t *testing.T) { - str := "string" - strPtr := &str - - tests := []struct { - in interface{} - want url.Values - }{ - { - // basic primitives - struct { - A string - B int - C uint - D float32 - E bool - }{}, - url.Values{ - "A": {""}, - "B": {"0"}, - "C": {"0"}, - "D": {"0"}, - "E": {"false"}, - }, - }, - { - // pointers - struct { - A *string - B *int - C **string - }{A: strPtr, C: &strPtr}, - url.Values{ - "A": {str}, - "B": {""}, - "C": {str}, - }, - }, - { - // slices and arrays - struct { - A []string - B []string `url:",comma"` - C []string `url:",space"` - D [2]string - E [2]string `url:",comma"` - F [2]string `url:",space"` - G []*string `url:",space"` - H []bool `url:",int,space"` - I []string `url:",brackets"` - }{ - A: []string{"a", "b"}, - B: []string{"a", "b"}, - C: []string{"a", "b"}, - D: [2]string{"a", "b"}, - E: [2]string{"a", "b"}, - F: [2]string{"a", "b"}, - G: []*string{&str, &str}, - H: []bool{true, false}, - I: []string{"a", "b"}, - }, - url.Values{ - "A": {"a", "b"}, - "B": {"a,b"}, - "C": {"a b"}, - "D": {"a", "b"}, - "E": {"a,b"}, - "F": {"a b"}, - "G": {"string string"}, - "H": {"1 0"}, - "I[]": {"a", "b"}, - }, - }, - { - // other types - struct { - A time.Time - B time.Time `url:",unix"` - C bool `url:",int"` - D bool `url:",int"` - }{ - A: time.Date(2000, 1, 1, 12, 34, 56, 0, time.UTC), - B: time.Date(2000, 1, 1, 12, 34, 56, 0, time.UTC), - C: true, - D: false, - }, - url.Values{ - "A": {"2000-01-01T12:34:56Z"}, - "B": {"946730096"}, - "C": {"1"}, - "D": {"0"}, - }, - }, - { - struct { - Nest Nested `url:"nest"` - }{ - Nested{ - A: SubNested{ - Value: "that", - }, - }, - }, - url.Values{ - "nest[a][value]": {"that"}, - "nest[b]": {""}, - }, - }, - { - struct { - Nest Nested `url:"nest"` - }{ - Nested{ - Ptr: &SubNested{ - Value: "that", - }, - }, - }, - url.Values{ - "nest[a][value]": {""}, - "nest[b]": {""}, - "nest[ptr][value]": {"that"}, - }, - }, - { - nil, - url.Values{}, - }, - } - - for i, tt := range tests { - v, err := Values(tt.in) - if err != nil { - t.Errorf("%d. Values(%q) returned error: %v", i, tt.in, err) - } - - if !reflect.DeepEqual(tt.want, v) { - t.Errorf("%d. Values(%q) returned %v, want %v", i, tt.in, v, tt.want) - } - } -} - -func TestValues_omitEmpty(t *testing.T) { - str := "" - s := struct { - a string - A string - B string `url:",omitempty"` - C string `url:"-"` - D string `url:"omitempty"` // actually named omitempty, not an option - E *string `url:",omitempty"` - }{E: &str} - - v, err := Values(s) - if err != nil { - t.Errorf("Values(%q) returned error: %v", s, err) - } - - want := url.Values{ - "A": {""}, - "omitempty": {""}, - "E": {""}, // E is included because the pointer is not empty, even though the string being pointed to is - } - if !reflect.DeepEqual(want, v) { - t.Errorf("Values(%q) returned %v, want %v", s, v, want) - } -} - -type A struct { - B -} - -type B struct { - C string -} - -type D struct { - B - C string -} - -func TestValues_embeddedStructs(t *testing.T) { - tests := []struct { - in interface{} - want url.Values - }{ - { - A{B{C: "foo"}}, - url.Values{"C": {"foo"}}, - }, - { - D{B: B{C: "bar"}, C: "foo"}, - url.Values{"C": {"foo", "bar"}}, - }, - } - - for i, tt := range tests { - v, err := Values(tt.in) - if err != nil { - t.Errorf("%d. Values(%q) returned error: %v", i, tt.in, err) - } - - if !reflect.DeepEqual(tt.want, v) { - t.Errorf("%d. Values(%q) returned %v, want %v", i, tt.in, v, tt.want) - } - } -} - -func TestValues_invalidInput(t *testing.T) { - _, err := Values("") - if err == nil { - t.Errorf("expected Values() to return an error on invalid input") - } -} - -type EncodedArgs []string - -func (m EncodedArgs) EncodeValues(key string, v *url.Values) error { - for i, arg := range m { - v.Set(fmt.Sprintf("%s.%d", key, i), arg) - } - return nil -} - -func TestValues_Marshaler(t *testing.T) { - s := struct { - Args EncodedArgs `url:"arg"` - }{[]string{"a", "b", "c"}} - v, err := Values(s) - if err != nil { - t.Errorf("Values(%q) returned error: %v", s, err) - } - - want := url.Values{ - "arg.0": {"a"}, - "arg.1": {"b"}, - "arg.2": {"c"}, - } - if !reflect.DeepEqual(want, v) { - t.Errorf("Values(%q) returned %v, want %v", s, v, want) - } -} - -func TestTagParsing(t *testing.T) { - name, opts := parseTag("field,foobar,foo") - if name != "field" { - t.Fatalf("name = %q, want field", name) - } - for _, tt := range []struct { - opt string - want bool - }{ - {"foobar", true}, - {"foo", true}, - {"bar", false}, - {"field", false}, - } { - if opts.Contains(tt.opt) != tt.want { - t.Errorf("Contains(%q) = %v", tt.opt, !tt.want) - } - } -} diff --git a/vendor/github.com/google/gofuzz/BUILD b/vendor/github.com/google/gofuzz/BUILD index a7aa0ee94ec3..52f70af03b1f 100644 --- a/vendor/github.com/google/gofuzz/BUILD +++ b/vendor/github.com/google/gofuzz/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -10,20 +10,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = ["fuzz_test.go"], - importpath = "github.com/google/gofuzz", - library = ":go_default_library", -) - -go_test( - name = "go_default_xtest", - srcs = ["example_test.go"], - importpath = "github.com/google/gofuzz_test", - deps = [":go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/google/gofuzz/example_test.go b/vendor/github.com/google/gofuzz/example_test.go deleted file mode 100644 index 792707a3a154..000000000000 --- a/vendor/github.com/google/gofuzz/example_test.go +++ /dev/null @@ -1,225 +0,0 @@ -/* -Copyright 2014 Google Inc. All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package fuzz_test - -import ( - "encoding/json" - "fmt" - "math/rand" - - "github.com/google/gofuzz" -) - -func ExampleSimple() { - type MyType struct { - A string - B string - C int - D struct { - E float64 - } - } - - f := fuzz.New() - object := MyType{} - - uniqueObjects := map[MyType]int{} - - for i := 0; i < 1000; i++ { - f.Fuzz(&object) - uniqueObjects[object]++ - } - fmt.Printf("Got %v unique objects.\n", len(uniqueObjects)) - // Output: - // Got 1000 unique objects. -} - -func ExampleCustom() { - type MyType struct { - A int - B string - } - - counter := 0 - f := fuzz.New().Funcs( - func(i *int, c fuzz.Continue) { - *i = counter - counter++ - }, - ) - object := MyType{} - - uniqueObjects := map[MyType]int{} - - for i := 0; i < 100; i++ { - f.Fuzz(&object) - if object.A != i { - fmt.Printf("Unexpected value: %#v\n", object) - } - uniqueObjects[object]++ - } - fmt.Printf("Got %v unique objects.\n", len(uniqueObjects)) - // Output: - // Got 100 unique objects. -} - -func ExampleComplex() { - type OtherType struct { - A string - B string - } - type MyType struct { - Pointer *OtherType - Map map[string]OtherType - PointerMap *map[string]OtherType - Slice []OtherType - SlicePointer []*OtherType - PointerSlicePointer *[]*OtherType - } - - f := fuzz.New().RandSource(rand.NewSource(0)).NilChance(0).NumElements(1, 1).Funcs( - func(o *OtherType, c fuzz.Continue) { - o.A = "Foo" - o.B = "Bar" - }, - func(op **OtherType, c fuzz.Continue) { - *op = &OtherType{"A", "B"} - }, - func(m map[string]OtherType, c fuzz.Continue) { - m["Works Because"] = OtherType{ - "Fuzzer", - "Preallocated", - } - }, - ) - object := MyType{} - f.Fuzz(&object) - bytes, err := json.MarshalIndent(&object, "", " ") - if err != nil { - fmt.Printf("error: %v\n", err) - } - fmt.Printf("%s\n", string(bytes)) - // Output: - // { - // "Pointer": { - // "A": "A", - // "B": "B" - // }, - // "Map": { - // "Works Because": { - // "A": "Fuzzer", - // "B": "Preallocated" - // } - // }, - // "PointerMap": { - // "Works Because": { - // "A": "Fuzzer", - // "B": "Preallocated" - // } - // }, - // "Slice": [ - // { - // "A": "Foo", - // "B": "Bar" - // } - // ], - // "SlicePointer": [ - // { - // "A": "A", - // "B": "B" - // } - // ], - // "PointerSlicePointer": [ - // { - // "A": "A", - // "B": "B" - // } - // ] - // } -} - -func ExampleMap() { - f := fuzz.New().NilChance(0).NumElements(1, 1) - var myMap map[struct{ A, B, C int }]string - f.Fuzz(&myMap) - fmt.Printf("myMap has %v element(s).\n", len(myMap)) - // Output: - // myMap has 1 element(s). -} - -func ExampleSingle() { - f := fuzz.New() - var i int - f.Fuzz(&i) - - // Technically, we'd expect this to fail one out of 2 billion attempts... - fmt.Printf("(i == 0) == %v", i == 0) - // Output: - // (i == 0) == false -} - -func ExampleEnum() { - type MyEnum string - const ( - A MyEnum = "A" - B MyEnum = "B" - ) - type MyInfo struct { - Type MyEnum - AInfo *string - BInfo *string - } - - f := fuzz.New().NilChance(0).Funcs( - func(e *MyInfo, c fuzz.Continue) { - // Note c's embedded Rand allows for direct use. - // We could also use c.RandBool() here. - switch c.Intn(2) { - case 0: - e.Type = A - c.Fuzz(&e.AInfo) - case 1: - e.Type = B - c.Fuzz(&e.BInfo) - } - }, - ) - - for i := 0; i < 100; i++ { - var myObject MyInfo - f.Fuzz(&myObject) - switch myObject.Type { - case A: - if myObject.AInfo == nil { - fmt.Println("AInfo should have been set!") - } - if myObject.BInfo != nil { - fmt.Println("BInfo should NOT have been set!") - } - case B: - if myObject.BInfo == nil { - fmt.Println("BInfo should have been set!") - } - if myObject.AInfo != nil { - fmt.Println("AInfo should NOT have been set!") - } - default: - fmt.Println("Invalid enum value!") - } - } - // Output: -} diff --git a/vendor/github.com/google/gofuzz/fuzz_test.go b/vendor/github.com/google/gofuzz/fuzz_test.go deleted file mode 100644 index 12abc8f6598b..000000000000 --- a/vendor/github.com/google/gofuzz/fuzz_test.go +++ /dev/null @@ -1,384 +0,0 @@ -/* -Copyright 2014 Google Inc. All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package fuzz - -import ( - "reflect" - "testing" - "time" -) - -func TestFuzz_basic(t *testing.T) { - obj := &struct { - I int - I8 int8 - I16 int16 - I32 int32 - I64 int64 - U uint - U8 uint8 - U16 uint16 - U32 uint32 - U64 uint64 - Uptr uintptr - S string - B bool - T time.Time - }{} - - failed := map[string]int{} - for i := 0; i < 10; i++ { - New().Fuzz(obj) - - if n, v := "i", obj.I; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i8", obj.I8; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i16", obj.I16; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i32", obj.I32; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i64", obj.I64; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u", obj.U; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u8", obj.U8; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u16", obj.U16; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u32", obj.U32; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u64", obj.U64; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "uptr", obj.Uptr; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "s", obj.S; v == "" { - failed[n] = failed[n] + 1 - } - if n, v := "b", obj.B; v == false { - failed[n] = failed[n] + 1 - } - if n, v := "t", obj.T; v.IsZero() { - failed[n] = failed[n] + 1 - } - } - checkFailed(t, failed) -} - -func checkFailed(t *testing.T, failed map[string]int) { - for k, v := range failed { - if v > 8 { - t.Errorf("%v seems to not be getting set, was zero value %v times", k, v) - } - } -} - -func TestFuzz_structptr(t *testing.T) { - obj := &struct { - A *struct { - S string - } - }{} - - f := New().NilChance(.5) - failed := map[string]int{} - for i := 0; i < 10; i++ { - f.Fuzz(obj) - - if n, v := "a not nil", obj.A; v == nil { - failed[n] = failed[n] + 1 - } - if n, v := "a nil", obj.A; v != nil { - failed[n] = failed[n] + 1 - } - if n, v := "as", obj.A; v == nil || v.S == "" { - failed[n] = failed[n] + 1 - } - } - checkFailed(t, failed) -} - -// tryFuzz tries fuzzing up to 20 times. Fail if check() never passes, report the highest -// stage it ever got to. -func tryFuzz(t *testing.T, f *Fuzzer, obj interface{}, check func() (stage int, passed bool)) { - maxStage := 0 - for i := 0; i < 20; i++ { - f.Fuzz(obj) - stage, passed := check() - if stage > maxStage { - maxStage = stage - } - if passed { - return - } - } - t.Errorf("Only ever got to stage %v", maxStage) -} - -func TestFuzz_structmap(t *testing.T) { - obj := &struct { - A map[struct { - S string - }]struct { - S2 string - } - B map[string]string - }{} - - tryFuzz(t, New(), obj, func() (int, bool) { - if obj.A == nil { - return 1, false - } - if len(obj.A) == 0 { - return 2, false - } - for k, v := range obj.A { - if k.S == "" { - return 3, false - } - if v.S2 == "" { - return 4, false - } - } - - if obj.B == nil { - return 5, false - } - if len(obj.B) == 0 { - return 6, false - } - for k, v := range obj.B { - if k == "" { - return 7, false - } - if v == "" { - return 8, false - } - } - return 9, true - }) -} - -func TestFuzz_structslice(t *testing.T) { - obj := &struct { - A []struct { - S string - } - B []string - }{} - - tryFuzz(t, New(), obj, func() (int, bool) { - if obj.A == nil { - return 1, false - } - if len(obj.A) == 0 { - return 2, false - } - for _, v := range obj.A { - if v.S == "" { - return 3, false - } - } - - if obj.B == nil { - return 4, false - } - if len(obj.B) == 0 { - return 5, false - } - for _, v := range obj.B { - if v == "" { - return 6, false - } - } - return 7, true - }) -} - -func TestFuzz_custom(t *testing.T) { - obj := &struct { - A string - B *string - C map[string]string - D *map[string]string - }{} - - testPhrase := "gotcalled" - testMap := map[string]string{"C": "D"} - f := New().Funcs( - func(s *string, c Continue) { - *s = testPhrase - }, - func(m map[string]string, c Continue) { - m["C"] = "D" - }, - ) - - tryFuzz(t, f, obj, func() (int, bool) { - if obj.A != testPhrase { - return 1, false - } - if obj.B == nil { - return 2, false - } - if *obj.B != testPhrase { - return 3, false - } - if e, a := testMap, obj.C; !reflect.DeepEqual(e, a) { - return 4, false - } - if obj.D == nil { - return 5, false - } - if e, a := testMap, *obj.D; !reflect.DeepEqual(e, a) { - return 6, false - } - return 7, true - }) -} - -type SelfFuzzer string - -// Implement fuzz.Interface. -func (sf *SelfFuzzer) Fuzz(c Continue) { - *sf = selfFuzzerTestPhrase -} - -const selfFuzzerTestPhrase = "was fuzzed" - -func TestFuzz_interface(t *testing.T) { - f := New() - - var obj1 SelfFuzzer - tryFuzz(t, f, &obj1, func() (int, bool) { - if obj1 != selfFuzzerTestPhrase { - return 1, false - } - return 1, true - }) - - var obj2 map[int]SelfFuzzer - tryFuzz(t, f, &obj2, func() (int, bool) { - for _, v := range obj2 { - if v != selfFuzzerTestPhrase { - return 1, false - } - } - return 1, true - }) -} - -func TestFuzz_interfaceAndFunc(t *testing.T) { - const privateTestPhrase = "private phrase" - f := New().Funcs( - // This should take precedence over SelfFuzzer.Fuzz(). - func(s *SelfFuzzer, c Continue) { - *s = privateTestPhrase - }, - ) - - var obj1 SelfFuzzer - tryFuzz(t, f, &obj1, func() (int, bool) { - if obj1 != privateTestPhrase { - return 1, false - } - return 1, true - }) - - var obj2 map[int]SelfFuzzer - tryFuzz(t, f, &obj2, func() (int, bool) { - for _, v := range obj2 { - if v != privateTestPhrase { - return 1, false - } - } - return 1, true - }) -} - -func TestFuzz_noCustom(t *testing.T) { - type Inner struct { - Str string - } - type Outer struct { - Str string - In Inner - } - - testPhrase := "gotcalled" - f := New().Funcs( - func(outer *Outer, c Continue) { - outer.Str = testPhrase - c.Fuzz(&outer.In) - }, - func(inner *Inner, c Continue) { - inner.Str = testPhrase - }, - ) - c := Continue{f: f, Rand: f.r} - - // Fuzzer.Fuzz() - obj1 := Outer{} - f.Fuzz(&obj1) - if obj1.Str != testPhrase { - t.Errorf("expected Outer custom function to have been called") - } - if obj1.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } - - // Continue.Fuzz() - obj2 := Outer{} - c.Fuzz(&obj2) - if obj2.Str != testPhrase { - t.Errorf("expected Outer custom function to have been called") - } - if obj2.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } - - // Fuzzer.FuzzNoCustom() - obj3 := Outer{} - f.FuzzNoCustom(&obj3) - if obj3.Str == testPhrase { - t.Errorf("expected Outer custom function to not have been called") - } - if obj3.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } - - // Continue.FuzzNoCustom() - obj4 := Outer{} - c.FuzzNoCustom(&obj4) - if obj4.Str == testPhrase { - t.Errorf("expected Outer custom function to not have been called") - } - if obj4.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } -} diff --git a/vendor/github.com/gregjones/httpcache/BUILD b/vendor/github.com/gregjones/httpcache/BUILD index ea6243e0bce2..e9353e3467b6 100644 --- a/vendor/github.com/gregjones/httpcache/BUILD +++ b/vendor/github.com/gregjones/httpcache/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -7,13 +7,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = ["httpcache_test.go"], - importpath = "github.com/gregjones/httpcache", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/gregjones/httpcache/diskcache/BUILD b/vendor/github.com/gregjones/httpcache/diskcache/BUILD index d4ba1c7882bd..b1c8f26ceff0 100644 --- a/vendor/github.com/gregjones/httpcache/diskcache/BUILD +++ b/vendor/github.com/gregjones/httpcache/diskcache/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -8,13 +8,6 @@ go_library( deps = ["//vendor/github.com/peterbourgon/diskv:go_default_library"], ) -go_test( - name = "go_default_test", - srcs = ["diskcache_test.go"], - importpath = "github.com/gregjones/httpcache/diskcache", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/gregjones/httpcache/diskcache/diskcache_test.go b/vendor/github.com/gregjones/httpcache/diskcache/diskcache_test.go deleted file mode 100644 index 35c76cbd1cdb..000000000000 --- a/vendor/github.com/gregjones/httpcache/diskcache/diskcache_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package diskcache - -import ( - "bytes" - "io/ioutil" - "os" - "testing" -) - -func TestDiskCache(t *testing.T) { - tempDir, err := ioutil.TempDir("", "httpcache") - if err != nil { - t.Fatalf("TempDir: %v", err) - } - defer os.RemoveAll(tempDir) - - cache := New(tempDir) - - key := "testKey" - _, ok := cache.Get(key) - if ok { - t.Fatal("retrieved key before adding it") - } - - val := []byte("some bytes") - cache.Set(key, val) - - retVal, ok := cache.Get(key) - if !ok { - t.Fatal("could not retrieve an element we just added") - } - if !bytes.Equal(retVal, val) { - t.Fatal("retrieved a different value than what we put in") - } - - cache.Delete(key) - - _, ok = cache.Get(key) - if ok { - t.Fatal("deleted key still present") - } -} diff --git a/vendor/github.com/gregjones/httpcache/httpcache_test.go b/vendor/github.com/gregjones/httpcache/httpcache_test.go deleted file mode 100644 index 3fbe5c85d174..000000000000 --- a/vendor/github.com/gregjones/httpcache/httpcache_test.go +++ /dev/null @@ -1,1208 +0,0 @@ -package httpcache - -import ( - "bytes" - "errors" - "flag" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "os" - "strconv" - "testing" - "time" -) - -var s struct { - server *httptest.Server - client http.Client - transport *Transport -} - -type fakeClock struct { - elapsed time.Duration -} - -func (c *fakeClock) since(t time.Time) time.Duration { - return c.elapsed -} - -func TestMain(m *testing.M) { - flag.Parse() - setup() - code := m.Run() - teardown() - os.Exit(code) -} - -func setup() { - tp := NewMemoryCacheTransport() - client := http.Client{Transport: tp} - s.transport = tp - s.client = client - - mux := http.NewServeMux() - s.server = httptest.NewServer(mux) - - mux.HandleFunc("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Cache-Control", "max-age=3600") - })) - - mux.HandleFunc("/method", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Cache-Control", "max-age=3600") - w.Write([]byte(r.Method)) - })) - - mux.HandleFunc("/range", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - lm := "Fri, 14 Dec 2010 01:01:50 GMT" - if r.Header.Get("if-modified-since") == lm { - w.WriteHeader(http.StatusNotModified) - return - } - w.Header().Set("last-modified", lm) - if r.Header.Get("range") == "bytes=4-9" { - w.WriteHeader(http.StatusPartialContent) - w.Write([]byte(" text ")) - return - } - w.Write([]byte("Some text content")) - })) - - mux.HandleFunc("/nostore", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Cache-Control", "no-store") - })) - - mux.HandleFunc("/etag", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - etag := "124567" - if r.Header.Get("if-none-match") == etag { - w.WriteHeader(http.StatusNotModified) - return - } - w.Header().Set("etag", etag) - })) - - mux.HandleFunc("/lastmodified", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - lm := "Fri, 14 Dec 2010 01:01:50 GMT" - if r.Header.Get("if-modified-since") == lm { - w.WriteHeader(http.StatusNotModified) - return - } - w.Header().Set("last-modified", lm) - })) - - mux.HandleFunc("/varyaccept", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Cache-Control", "max-age=3600") - w.Header().Set("Content-Type", "text/plain") - w.Header().Set("Vary", "Accept") - w.Write([]byte("Some text content")) - })) - - mux.HandleFunc("/doublevary", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Cache-Control", "max-age=3600") - w.Header().Set("Content-Type", "text/plain") - w.Header().Set("Vary", "Accept, Accept-Language") - w.Write([]byte("Some text content")) - })) - mux.HandleFunc("/2varyheaders", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Cache-Control", "max-age=3600") - w.Header().Set("Content-Type", "text/plain") - w.Header().Add("Vary", "Accept") - w.Header().Add("Vary", "Accept-Language") - w.Write([]byte("Some text content")) - })) - mux.HandleFunc("/varyunused", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Cache-Control", "max-age=3600") - w.Header().Set("Content-Type", "text/plain") - w.Header().Set("Vary", "X-Madeup-Header") - w.Write([]byte("Some text content")) - })) - - updateFieldsCounter := 0 - mux.HandleFunc("/updatefields", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("X-Counter", strconv.Itoa(updateFieldsCounter)) - w.Header().Set("Etag", `"e"`) - updateFieldsCounter++ - if r.Header.Get("if-none-match") != "" { - w.WriteHeader(http.StatusNotModified) - return - } - w.Write([]byte("Some text content")) - })) -} - -func teardown() { - s.server.Close() -} - -func resetTest() { - s.transport.Cache = NewMemoryCache() - clock = &realClock{} -} - -// TestCacheableMethod ensures that uncacheable method does not get stored -// in cache and get incorrectly used for a following cacheable method request. -func TestCacheableMethod(t *testing.T) { - resetTest() - { - req, err := http.NewRequest("POST", s.server.URL+"/method", nil) - if err != nil { - t.Fatal(err) - } - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - var buf bytes.Buffer - _, err = io.Copy(&buf, resp.Body) - if err != nil { - t.Fatal(err) - } - err = resp.Body.Close() - if err != nil { - t.Fatal(err) - } - if got, want := buf.String(), "POST"; got != want { - t.Errorf("got %q, want %q", got, want) - } - if resp.StatusCode != http.StatusOK { - t.Errorf("response status code isn't 200 OK: %v", resp.StatusCode) - } - } - { - req, err := http.NewRequest("GET", s.server.URL+"/method", nil) - if err != nil { - t.Fatal(err) - } - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - var buf bytes.Buffer - _, err = io.Copy(&buf, resp.Body) - if err != nil { - t.Fatal(err) - } - err = resp.Body.Close() - if err != nil { - t.Fatal(err) - } - if got, want := buf.String(), "GET"; got != want { - t.Errorf("got wrong body %q, want %q", got, want) - } - if resp.StatusCode != http.StatusOK { - t.Errorf("response status code isn't 200 OK: %v", resp.StatusCode) - } - if resp.Header.Get(XFromCache) != "" { - t.Errorf("XFromCache header isn't blank") - } - } -} - -func TestDontStorePartialRangeInCache(t *testing.T) { - resetTest() - { - req, err := http.NewRequest("GET", s.server.URL+"/range", nil) - if err != nil { - t.Fatal(err) - } - req.Header.Set("range", "bytes=4-9") - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - var buf bytes.Buffer - _, err = io.Copy(&buf, resp.Body) - if err != nil { - t.Fatal(err) - } - err = resp.Body.Close() - if err != nil { - t.Fatal(err) - } - if got, want := buf.String(), " text "; got != want { - t.Errorf("got %q, want %q", got, want) - } - if resp.StatusCode != http.StatusPartialContent { - t.Errorf("response status code isn't 206 Partial Content: %v", resp.StatusCode) - } - } - { - req, err := http.NewRequest("GET", s.server.URL+"/range", nil) - if err != nil { - t.Fatal(err) - } - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - var buf bytes.Buffer - _, err = io.Copy(&buf, resp.Body) - if err != nil { - t.Fatal(err) - } - err = resp.Body.Close() - if err != nil { - t.Fatal(err) - } - if got, want := buf.String(), "Some text content"; got != want { - t.Errorf("got %q, want %q", got, want) - } - if resp.StatusCode != http.StatusOK { - t.Errorf("response status code isn't 200 OK: %v", resp.StatusCode) - } - if resp.Header.Get(XFromCache) != "" { - t.Error("XFromCache header isn't blank") - } - } - { - req, err := http.NewRequest("GET", s.server.URL+"/range", nil) - if err != nil { - t.Fatal(err) - } - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - var buf bytes.Buffer - _, err = io.Copy(&buf, resp.Body) - if err != nil { - t.Fatal(err) - } - err = resp.Body.Close() - if err != nil { - t.Fatal(err) - } - if got, want := buf.String(), "Some text content"; got != want { - t.Errorf("got %q, want %q", got, want) - } - if resp.StatusCode != http.StatusOK { - t.Errorf("response status code isn't 200 OK: %v", resp.StatusCode) - } - if resp.Header.Get(XFromCache) != "1" { - t.Errorf(`XFromCache header isn't "1": %v`, resp.Header.Get(XFromCache)) - } - } - { - req, err := http.NewRequest("GET", s.server.URL+"/range", nil) - if err != nil { - t.Fatal(err) - } - req.Header.Set("range", "bytes=4-9") - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - var buf bytes.Buffer - _, err = io.Copy(&buf, resp.Body) - if err != nil { - t.Fatal(err) - } - err = resp.Body.Close() - if err != nil { - t.Fatal(err) - } - if got, want := buf.String(), " text "; got != want { - t.Errorf("got %q, want %q", got, want) - } - if resp.StatusCode != http.StatusPartialContent { - t.Errorf("response status code isn't 206 Partial Content: %v", resp.StatusCode) - } - } -} - -func TestGetOnlyIfCachedHit(t *testing.T) { - resetTest() - { - req, err := http.NewRequest("GET", s.server.URL, nil) - if err != nil { - t.Fatal(err) - } - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "" { - t.Fatal("XFromCache header isn't blank") - } - } - { - req, err := http.NewRequest("GET", s.server.URL, nil) - if err != nil { - t.Fatal(err) - } - req.Header.Add("cache-control", "only-if-cached") - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "1" { - t.Fatalf(`XFromCache header isn't "1": %v`, resp.Header.Get(XFromCache)) - } - if resp.StatusCode != http.StatusOK { - t.Fatalf("response status code isn't 200 OK: %v", resp.StatusCode) - } - } -} - -func TestGetOnlyIfCachedMiss(t *testing.T) { - resetTest() - req, err := http.NewRequest("GET", s.server.URL, nil) - if err != nil { - t.Fatal(err) - } - req.Header.Add("cache-control", "only-if-cached") - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "" { - t.Fatal("XFromCache header isn't blank") - } - if resp.StatusCode != http.StatusGatewayTimeout { - t.Fatalf("response status code isn't 504 GatewayTimeout: %v", resp.StatusCode) - } -} - -func TestGetNoStoreRequest(t *testing.T) { - resetTest() - req, err := http.NewRequest("GET", s.server.URL, nil) - if err != nil { - t.Fatal(err) - } - req.Header.Add("Cache-Control", "no-store") - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "" { - t.Fatal("XFromCache header isn't blank") - } - } - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "" { - t.Fatal("XFromCache header isn't blank") - } - } -} - -func TestGetNoStoreResponse(t *testing.T) { - resetTest() - req, err := http.NewRequest("GET", s.server.URL+"/nostore", nil) - if err != nil { - t.Fatal(err) - } - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "" { - t.Fatal("XFromCache header isn't blank") - } - } - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "" { - t.Fatal("XFromCache header isn't blank") - } - } -} - -func TestGetWithEtag(t *testing.T) { - resetTest() - req, err := http.NewRequest("GET", s.server.URL+"/etag", nil) - if err != nil { - t.Fatal(err) - } - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "" { - t.Fatal("XFromCache header isn't blank") - } - } - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "1" { - t.Fatalf(`XFromCache header isn't "1": %v`, resp.Header.Get(XFromCache)) - } - // additional assertions to verify that 304 response is converted properly - if resp.StatusCode != http.StatusOK { - t.Fatalf("response status code isn't 200 OK: %v", resp.StatusCode) - } - if _, ok := resp.Header["Connection"]; ok { - t.Fatalf("Connection header isn't absent") - } - } -} - -func TestGetWithLastModified(t *testing.T) { - resetTest() - req, err := http.NewRequest("GET", s.server.URL+"/lastmodified", nil) - if err != nil { - t.Fatal(err) - } - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "" { - t.Fatal("XFromCache header isn't blank") - } - } - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "1" { - t.Fatalf(`XFromCache header isn't "1": %v`, resp.Header.Get(XFromCache)) - } - } -} - -func TestGetWithVary(t *testing.T) { - resetTest() - req, err := http.NewRequest("GET", s.server.URL+"/varyaccept", nil) - if err != nil { - t.Fatal(err) - } - req.Header.Set("Accept", "text/plain") - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get("Vary") != "Accept" { - t.Fatalf(`Vary header isn't "Accept": %v`, resp.Header.Get("Vary")) - } - } - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "1" { - t.Fatalf(`XFromCache header isn't "1": %v`, resp.Header.Get(XFromCache)) - } - } - req.Header.Set("Accept", "text/html") - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "" { - t.Fatal("XFromCache header isn't blank") - } - } - req.Header.Set("Accept", "") - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "" { - t.Fatal("XFromCache header isn't blank") - } - } -} - -func TestGetWithDoubleVary(t *testing.T) { - resetTest() - req, err := http.NewRequest("GET", s.server.URL+"/doublevary", nil) - if err != nil { - t.Fatal(err) - } - req.Header.Set("Accept", "text/plain") - req.Header.Set("Accept-Language", "da, en-gb;q=0.8, en;q=0.7") - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get("Vary") == "" { - t.Fatalf(`Vary header is blank`) - } - } - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "1" { - t.Fatalf(`XFromCache header isn't "1": %v`, resp.Header.Get(XFromCache)) - } - } - req.Header.Set("Accept-Language", "") - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "" { - t.Fatal("XFromCache header isn't blank") - } - } - req.Header.Set("Accept-Language", "da") - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "" { - t.Fatal("XFromCache header isn't blank") - } - } -} - -func TestGetWith2VaryHeaders(t *testing.T) { - resetTest() - // Tests that multiple Vary headers' comma-separated lists are - // merged. See https://github.com/gregjones/httpcache/issues/27. - const ( - accept = "text/plain" - acceptLanguage = "da, en-gb;q=0.8, en;q=0.7" - ) - req, err := http.NewRequest("GET", s.server.URL+"/2varyheaders", nil) - if err != nil { - t.Fatal(err) - } - req.Header.Set("Accept", accept) - req.Header.Set("Accept-Language", acceptLanguage) - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get("Vary") == "" { - t.Fatalf(`Vary header is blank`) - } - } - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "1" { - t.Fatalf(`XFromCache header isn't "1": %v`, resp.Header.Get(XFromCache)) - } - } - req.Header.Set("Accept-Language", "") - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "" { - t.Fatal("XFromCache header isn't blank") - } - } - req.Header.Set("Accept-Language", "da") - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "" { - t.Fatal("XFromCache header isn't blank") - } - } - req.Header.Set("Accept-Language", acceptLanguage) - req.Header.Set("Accept", "") - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "" { - t.Fatal("XFromCache header isn't blank") - } - } - req.Header.Set("Accept", "image/png") - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "" { - t.Fatal("XFromCache header isn't blank") - } - } - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "1" { - t.Fatalf(`XFromCache header isn't "1": %v`, resp.Header.Get(XFromCache)) - } - } -} - -func TestGetVaryUnused(t *testing.T) { - resetTest() - req, err := http.NewRequest("GET", s.server.URL+"/varyunused", nil) - if err != nil { - t.Fatal(err) - } - req.Header.Set("Accept", "text/plain") - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get("Vary") == "" { - t.Fatalf(`Vary header is blank`) - } - } - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "1" { - t.Fatalf(`XFromCache header isn't "1": %v`, resp.Header.Get(XFromCache)) - } - } -} - -func TestUpdateFields(t *testing.T) { - resetTest() - req, err := http.NewRequest("GET", s.server.URL+"/updatefields", nil) - if err != nil { - t.Fatal(err) - } - var counter, counter2 string - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - counter = resp.Header.Get("x-counter") - } - { - resp, err := s.client.Do(req) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.Header.Get(XFromCache) != "1" { - t.Fatalf(`XFromCache header isn't "1": %v`, resp.Header.Get(XFromCache)) - } - counter2 = resp.Header.Get("x-counter") - } - if counter == counter2 { - t.Fatalf(`both "x-counter" values are equal: %v %v`, counter, counter2) - } -} - -func TestParseCacheControl(t *testing.T) { - resetTest() - h := http.Header{} - for range parseCacheControl(h) { - t.Fatal("cacheControl should be empty") - } - - h.Set("cache-control", "no-cache") - { - cc := parseCacheControl(h) - if _, ok := cc["foo"]; ok { - t.Error(`Value "foo" shouldn't exist`) - } - noCache, ok := cc["no-cache"] - if !ok { - t.Fatalf(`"no-cache" value isn't set`) - } - if noCache != "" { - t.Fatalf(`"no-cache" value isn't blank: %v`, noCache) - } - } - h.Set("cache-control", "no-cache, max-age=3600") - { - cc := parseCacheControl(h) - noCache, ok := cc["no-cache"] - if !ok { - t.Fatalf(`"no-cache" value isn't set`) - } - if noCache != "" { - t.Fatalf(`"no-cache" value isn't blank: %v`, noCache) - } - if cc["max-age"] != "3600" { - t.Fatalf(`"max-age" value isn't "3600": %v`, cc["max-age"]) - } - } -} - -func TestNoCacheRequestExpiration(t *testing.T) { - resetTest() - respHeaders := http.Header{} - respHeaders.Set("Cache-Control", "max-age=7200") - - reqHeaders := http.Header{} - reqHeaders.Set("Cache-Control", "no-cache") - if getFreshness(respHeaders, reqHeaders) != transparent { - t.Fatal("freshness isn't transparent") - } -} - -func TestNoCacheResponseExpiration(t *testing.T) { - resetTest() - respHeaders := http.Header{} - respHeaders.Set("Cache-Control", "no-cache") - respHeaders.Set("Expires", "Wed, 19 Apr 3000 11:43:00 GMT") - - reqHeaders := http.Header{} - if getFreshness(respHeaders, reqHeaders) != stale { - t.Fatal("freshness isn't stale") - } -} - -func TestReqMustRevalidate(t *testing.T) { - resetTest() - // not paying attention to request setting max-stale means never returning stale - // responses, so always acting as if must-revalidate is set - respHeaders := http.Header{} - - reqHeaders := http.Header{} - reqHeaders.Set("Cache-Control", "must-revalidate") - if getFreshness(respHeaders, reqHeaders) != stale { - t.Fatal("freshness isn't stale") - } -} - -func TestRespMustRevalidate(t *testing.T) { - resetTest() - respHeaders := http.Header{} - respHeaders.Set("Cache-Control", "must-revalidate") - - reqHeaders := http.Header{} - if getFreshness(respHeaders, reqHeaders) != stale { - t.Fatal("freshness isn't stale") - } -} - -func TestFreshExpiration(t *testing.T) { - resetTest() - now := time.Now() - respHeaders := http.Header{} - respHeaders.Set("date", now.Format(time.RFC1123)) - respHeaders.Set("expires", now.Add(time.Duration(2)*time.Second).Format(time.RFC1123)) - - reqHeaders := http.Header{} - if getFreshness(respHeaders, reqHeaders) != fresh { - t.Fatal("freshness isn't fresh") - } - - clock = &fakeClock{elapsed: 3 * time.Second} - if getFreshness(respHeaders, reqHeaders) != stale { - t.Fatal("freshness isn't stale") - } -} - -func TestMaxAge(t *testing.T) { - resetTest() - now := time.Now() - respHeaders := http.Header{} - respHeaders.Set("date", now.Format(time.RFC1123)) - respHeaders.Set("cache-control", "max-age=2") - - reqHeaders := http.Header{} - if getFreshness(respHeaders, reqHeaders) != fresh { - t.Fatal("freshness isn't fresh") - } - - clock = &fakeClock{elapsed: 3 * time.Second} - if getFreshness(respHeaders, reqHeaders) != stale { - t.Fatal("freshness isn't stale") - } -} - -func TestMaxAgeZero(t *testing.T) { - resetTest() - now := time.Now() - respHeaders := http.Header{} - respHeaders.Set("date", now.Format(time.RFC1123)) - respHeaders.Set("cache-control", "max-age=0") - - reqHeaders := http.Header{} - if getFreshness(respHeaders, reqHeaders) != stale { - t.Fatal("freshness isn't stale") - } -} - -func TestBothMaxAge(t *testing.T) { - resetTest() - now := time.Now() - respHeaders := http.Header{} - respHeaders.Set("date", now.Format(time.RFC1123)) - respHeaders.Set("cache-control", "max-age=2") - - reqHeaders := http.Header{} - reqHeaders.Set("cache-control", "max-age=0") - if getFreshness(respHeaders, reqHeaders) != stale { - t.Fatal("freshness isn't stale") - } -} - -func TestMinFreshWithExpires(t *testing.T) { - resetTest() - now := time.Now() - respHeaders := http.Header{} - respHeaders.Set("date", now.Format(time.RFC1123)) - respHeaders.Set("expires", now.Add(time.Duration(2)*time.Second).Format(time.RFC1123)) - - reqHeaders := http.Header{} - reqHeaders.Set("cache-control", "min-fresh=1") - if getFreshness(respHeaders, reqHeaders) != fresh { - t.Fatal("freshness isn't fresh") - } - - reqHeaders = http.Header{} - reqHeaders.Set("cache-control", "min-fresh=2") - if getFreshness(respHeaders, reqHeaders) != stale { - t.Fatal("freshness isn't stale") - } -} - -func TestEmptyMaxStale(t *testing.T) { - resetTest() - now := time.Now() - respHeaders := http.Header{} - respHeaders.Set("date", now.Format(time.RFC1123)) - respHeaders.Set("cache-control", "max-age=20") - - reqHeaders := http.Header{} - reqHeaders.Set("cache-control", "max-stale") - clock = &fakeClock{elapsed: 10 * time.Second} - if getFreshness(respHeaders, reqHeaders) != fresh { - t.Fatal("freshness isn't fresh") - } - - clock = &fakeClock{elapsed: 60 * time.Second} - if getFreshness(respHeaders, reqHeaders) != fresh { - t.Fatal("freshness isn't fresh") - } -} - -func TestMaxStaleValue(t *testing.T) { - resetTest() - now := time.Now() - respHeaders := http.Header{} - respHeaders.Set("date", now.Format(time.RFC1123)) - respHeaders.Set("cache-control", "max-age=10") - - reqHeaders := http.Header{} - reqHeaders.Set("cache-control", "max-stale=20") - clock = &fakeClock{elapsed: 5 * time.Second} - if getFreshness(respHeaders, reqHeaders) != fresh { - t.Fatal("freshness isn't fresh") - } - - clock = &fakeClock{elapsed: 15 * time.Second} - if getFreshness(respHeaders, reqHeaders) != fresh { - t.Fatal("freshness isn't fresh") - } - - clock = &fakeClock{elapsed: 30 * time.Second} - if getFreshness(respHeaders, reqHeaders) != stale { - t.Fatal("freshness isn't stale") - } -} - -func containsHeader(headers []string, header string) bool { - for _, v := range headers { - if http.CanonicalHeaderKey(v) == http.CanonicalHeaderKey(header) { - return true - } - } - return false -} - -func TestGetEndToEndHeaders(t *testing.T) { - resetTest() - var ( - headers http.Header - end2end []string - ) - - headers = http.Header{} - headers.Set("content-type", "text/html") - headers.Set("te", "deflate") - - end2end = getEndToEndHeaders(headers) - if !containsHeader(end2end, "content-type") { - t.Fatal(`doesn't contain "content-type" header`) - } - if containsHeader(end2end, "te") { - t.Fatal(`doesn't contain "te" header`) - } - - headers = http.Header{} - headers.Set("connection", "content-type") - headers.Set("content-type", "text/csv") - headers.Set("te", "deflate") - end2end = getEndToEndHeaders(headers) - if containsHeader(end2end, "connection") { - t.Fatal(`doesn't contain "connection" header`) - } - if containsHeader(end2end, "content-type") { - t.Fatal(`doesn't contain "content-type" header`) - } - if containsHeader(end2end, "te") { - t.Fatal(`doesn't contain "te" header`) - } - - headers = http.Header{} - end2end = getEndToEndHeaders(headers) - if len(end2end) != 0 { - t.Fatal(`non-zero end2end headers`) - } - - headers = http.Header{} - headers.Set("connection", "content-type") - end2end = getEndToEndHeaders(headers) - if len(end2end) != 0 { - t.Fatal(`non-zero end2end headers`) - } -} - -type transportMock struct { - response *http.Response - err error -} - -func (t transportMock) RoundTrip(req *http.Request) (resp *http.Response, err error) { - return t.response, t.err -} - -func TestStaleIfErrorRequest(t *testing.T) { - resetTest() - now := time.Now() - tmock := transportMock{ - response: &http.Response{ - Status: http.StatusText(http.StatusOK), - StatusCode: http.StatusOK, - Header: http.Header{ - "Date": []string{now.Format(time.RFC1123)}, - "Cache-Control": []string{"no-cache"}, - }, - Body: ioutil.NopCloser(bytes.NewBuffer([]byte("some data"))), - }, - err: nil, - } - tp := NewMemoryCacheTransport() - tp.Transport = &tmock - - // First time, response is cached on success - r, _ := http.NewRequest("GET", "http://somewhere.com/", nil) - r.Header.Set("Cache-Control", "stale-if-error") - resp, err := tp.RoundTrip(r) - if err != nil { - t.Fatal(err) - } - if resp == nil { - t.Fatal("resp is nil") - } - - // On failure, response is returned from the cache - tmock.response = nil - tmock.err = errors.New("some error") - resp, err = tp.RoundTrip(r) - if err != nil { - t.Fatal(err) - } - if resp == nil { - t.Fatal("resp is nil") - } -} - -func TestStaleIfErrorRequestLifetime(t *testing.T) { - resetTest() - now := time.Now() - tmock := transportMock{ - response: &http.Response{ - Status: http.StatusText(http.StatusOK), - StatusCode: http.StatusOK, - Header: http.Header{ - "Date": []string{now.Format(time.RFC1123)}, - "Cache-Control": []string{"no-cache"}, - }, - Body: ioutil.NopCloser(bytes.NewBuffer([]byte("some data"))), - }, - err: nil, - } - tp := NewMemoryCacheTransport() - tp.Transport = &tmock - - // First time, response is cached on success - r, _ := http.NewRequest("GET", "http://somewhere.com/", nil) - r.Header.Set("Cache-Control", "stale-if-error=100") - resp, err := tp.RoundTrip(r) - if err != nil { - t.Fatal(err) - } - if resp == nil { - t.Fatal("resp is nil") - } - - // On failure, response is returned from the cache - tmock.response = nil - tmock.err = errors.New("some error") - resp, err = tp.RoundTrip(r) - if err != nil { - t.Fatal(err) - } - if resp == nil { - t.Fatal("resp is nil") - } - - // Same for http errors - tmock.response = &http.Response{StatusCode: http.StatusInternalServerError} - tmock.err = nil - resp, err = tp.RoundTrip(r) - if err != nil { - t.Fatal(err) - } - if resp == nil { - t.Fatal("resp is nil") - } - - // If failure last more than max stale, error is returned - clock = &fakeClock{elapsed: 200 * time.Second} - resp, err = tp.RoundTrip(r) - if err != tmock.err { - t.Fatalf("got err %v, want %v", err, tmock.err) - } -} - -func TestStaleIfErrorResponse(t *testing.T) { - resetTest() - now := time.Now() - tmock := transportMock{ - response: &http.Response{ - Status: http.StatusText(http.StatusOK), - StatusCode: http.StatusOK, - Header: http.Header{ - "Date": []string{now.Format(time.RFC1123)}, - "Cache-Control": []string{"no-cache, stale-if-error"}, - }, - Body: ioutil.NopCloser(bytes.NewBuffer([]byte("some data"))), - }, - err: nil, - } - tp := NewMemoryCacheTransport() - tp.Transport = &tmock - - // First time, response is cached on success - r, _ := http.NewRequest("GET", "http://somewhere.com/", nil) - resp, err := tp.RoundTrip(r) - if err != nil { - t.Fatal(err) - } - if resp == nil { - t.Fatal("resp is nil") - } - - // On failure, response is returned from the cache - tmock.response = nil - tmock.err = errors.New("some error") - resp, err = tp.RoundTrip(r) - if err != nil { - t.Fatal(err) - } - if resp == nil { - t.Fatal("resp is nil") - } -} - -func TestStaleIfErrorResponseLifetime(t *testing.T) { - resetTest() - now := time.Now() - tmock := transportMock{ - response: &http.Response{ - Status: http.StatusText(http.StatusOK), - StatusCode: http.StatusOK, - Header: http.Header{ - "Date": []string{now.Format(time.RFC1123)}, - "Cache-Control": []string{"no-cache, stale-if-error=100"}, - }, - Body: ioutil.NopCloser(bytes.NewBuffer([]byte("some data"))), - }, - err: nil, - } - tp := NewMemoryCacheTransport() - tp.Transport = &tmock - - // First time, response is cached on success - r, _ := http.NewRequest("GET", "http://somewhere.com/", nil) - resp, err := tp.RoundTrip(r) - if err != nil { - t.Fatal(err) - } - if resp == nil { - t.Fatal("resp is nil") - } - - // On failure, response is returned from the cache - tmock.response = nil - tmock.err = errors.New("some error") - resp, err = tp.RoundTrip(r) - if err != nil { - t.Fatal(err) - } - if resp == nil { - t.Fatal("resp is nil") - } - - // If failure last more than max stale, error is returned - clock = &fakeClock{elapsed: 200 * time.Second} - resp, err = tp.RoundTrip(r) - if err != tmock.err { - t.Fatalf("got err %v, want %v", err, tmock.err) - } -} diff --git a/vendor/github.com/influxdata/influxdb/client/BUILD b/vendor/github.com/influxdata/influxdb/client/BUILD index 68b6ea841579..169f49a2f4a5 100644 --- a/vendor/github.com/influxdata/influxdb/client/BUILD +++ b/vendor/github.com/influxdata/influxdb/client/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -8,16 +8,6 @@ go_library( deps = ["//vendor/github.com/influxdata/influxdb/models:go_default_library"], ) -go_test( - name = "go_default_xtest", - srcs = [ - "example_test.go", - "influxdb_test.go", - ], - importpath = "github.com/influxdata/influxdb/client_test", - deps = [":go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/influxdata/influxdb/client/example_test.go b/vendor/github.com/influxdata/influxdb/client/example_test.go deleted file mode 100644 index f3753834a97d..000000000000 --- a/vendor/github.com/influxdata/influxdb/client/example_test.go +++ /dev/null @@ -1,113 +0,0 @@ -package client_test - -import ( - "fmt" - "log" - "math/rand" - "net/url" - "os" - "strconv" - "time" - - "github.com/influxdata/influxdb/client" -) - -func ExampleNewClient() { - host, err := url.Parse(fmt.Sprintf("http://%s:%d", "localhost", 8086)) - if err != nil { - log.Fatal(err) - } - - // NOTE: this assumes you've setup a user and have setup shell env variables, - // namely INFLUX_USER/INFLUX_PWD. If not just omit Username/Password below. - conf := client.Config{ - URL: *host, - Username: os.Getenv("INFLUX_USER"), - Password: os.Getenv("INFLUX_PWD"), - } - con, err := client.NewClient(conf) - if err != nil { - log.Fatal(err) - } - log.Println("Connection", con) -} - -func ExampleClient_Ping() { - host, err := url.Parse(fmt.Sprintf("http://%s:%d", "localhost", 8086)) - if err != nil { - log.Fatal(err) - } - con, err := client.NewClient(client.Config{URL: *host}) - if err != nil { - log.Fatal(err) - } - - dur, ver, err := con.Ping() - if err != nil { - log.Fatal(err) - } - log.Printf("Happy as a hippo! %v, %s", dur, ver) -} - -func ExampleClient_Query() { - host, err := url.Parse(fmt.Sprintf("http://%s:%d", "localhost", 8086)) - if err != nil { - log.Fatal(err) - } - con, err := client.NewClient(client.Config{URL: *host}) - if err != nil { - log.Fatal(err) - } - - q := client.Query{ - Command: "select count(value) from shapes", - Database: "square_holes", - } - if response, err := con.Query(q); err == nil && response.Error() == nil { - log.Println(response.Results) - } -} - -func ExampleClient_Write() { - host, err := url.Parse(fmt.Sprintf("http://%s:%d", "localhost", 8086)) - if err != nil { - log.Fatal(err) - } - con, err := client.NewClient(client.Config{URL: *host}) - if err != nil { - log.Fatal(err) - } - - var ( - shapes = []string{"circle", "rectangle", "square", "triangle"} - colors = []string{"red", "blue", "green"} - sampleSize = 1000 - pts = make([]client.Point, sampleSize) - ) - - rand.Seed(42) - for i := 0; i < sampleSize; i++ { - pts[i] = client.Point{ - Measurement: "shapes", - Tags: map[string]string{ - "color": strconv.Itoa(rand.Intn(len(colors))), - "shape": strconv.Itoa(rand.Intn(len(shapes))), - }, - Fields: map[string]interface{}{ - "value": rand.Intn(sampleSize), - }, - Time: time.Now(), - Precision: "s", - } - } - - bps := client.BatchPoints{ - Points: pts, - Database: "BumbeBeeTuna", - RetentionPolicy: "default", - } - _, err = con.Write(bps) - if err != nil { - log.Fatal(err) - } -} diff --git a/vendor/github.com/influxdata/influxdb/client/influxdb_test.go b/vendor/github.com/influxdata/influxdb/client/influxdb_test.go deleted file mode 100644 index 39349c19ee33..000000000000 --- a/vendor/github.com/influxdata/influxdb/client/influxdb_test.go +++ /dev/null @@ -1,831 +0,0 @@ -package client_test - -import ( - "crypto/tls" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "net/url" - "os" - "strings" - "testing" - "time" - - "github.com/influxdata/influxdb/client" -) - -func BenchmarkWrite(b *testing.B) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var data client.Response - w.WriteHeader(http.StatusNoContent) - _ = json.NewEncoder(w).Encode(data) - })) - defer ts.Close() - - u, _ := url.Parse(ts.URL) - config := client.Config{URL: *u} - c, err := client.NewClient(config) - if err != nil { - b.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - - bp := client.BatchPoints{ - Points: []client.Point{ - {Fields: map[string]interface{}{"value": 101}}}, - } - for i := 0; i < b.N; i++ { - r, err := c.Write(bp) - if err != nil { - b.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - if r != nil { - b.Fatalf("unexpected response. expected %v, actual %v", nil, r) - } - } -} - -func BenchmarkUnmarshalJSON2Tags(b *testing.B) { - var bp client.BatchPoints - data := []byte(` -{ - "database": "foo", - "retentionPolicy": "bar", - "points": [ - { - "name": "cpu", - "tags": { - "host": "server01", - "region": "us-east1" - }, - "time": 14244733039069373, - "precision": "n", - "fields": { - "value": 4541770385657154000 - } - } - ] -} -`) - - for i := 0; i < b.N; i++ { - if err := json.Unmarshal(data, &bp); err != nil { - b.Errorf("unable to unmarshal nanosecond data: %s", err.Error()) - } - b.SetBytes(int64(len(data))) - } -} - -func BenchmarkUnmarshalJSON10Tags(b *testing.B) { - var bp client.BatchPoints - data := []byte(` -{ - "database": "foo", - "retentionPolicy": "bar", - "points": [ - { - "name": "cpu", - "tags": { - "host": "server01", - "region": "us-east1", - "tag1": "value1", - "tag2": "value2", - "tag2": "value3", - "tag4": "value4", - "tag5": "value5", - "tag6": "value6", - "tag7": "value7", - "tag8": "value8" - }, - "time": 14244733039069373, - "precision": "n", - "fields": { - "value": 4541770385657154000 - } - } - ] -} -`) - - for i := 0; i < b.N; i++ { - if err := json.Unmarshal(data, &bp); err != nil { - b.Errorf("unable to unmarshal nanosecond data: %s", err.Error()) - } - b.SetBytes(int64(len(data))) - } -} - -func TestNewClient(t *testing.T) { - config := client.Config{} - _, err := client.NewClient(config) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } -} - -func TestClient_Ping(t *testing.T) { - ts := emptyTestServer() - defer ts.Close() - - u, _ := url.Parse(ts.URL) - config := client.Config{URL: *u} - c, err := client.NewClient(config) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - d, version, err := c.Ping() - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - if d.Nanoseconds() == 0 { - t.Fatalf("expected a duration greater than zero. actual %v", d.Nanoseconds()) - } - if version != "x.x" { - t.Fatalf("unexpected version. expected %s, actual %v", "x.x", version) - } -} - -func TestClient_Query(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var data client.Response - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(data) - })) - defer ts.Close() - - u, _ := url.Parse(ts.URL) - config := client.Config{URL: *u} - c, err := client.NewClient(config) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - - query := client.Query{} - _, err = c.Query(query) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } -} - -func TestClient_ChunkedQuery(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var data client.Response - w.WriteHeader(http.StatusOK) - enc := json.NewEncoder(w) - _ = enc.Encode(data) - _ = enc.Encode(data) - })) - defer ts.Close() - - u, _ := url.Parse(ts.URL) - config := client.Config{URL: *u} - c, err := client.NewClient(config) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - - query := client.Query{Chunked: true} - _, err = c.Query(query) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } -} - -func TestClient_BasicAuth(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - u, p, ok := r.BasicAuth() - - if !ok { - t.Errorf("basic auth error") - } - if u != "username" { - t.Errorf("unexpected username, expected %q, actual %q", "username", u) - } - if p != "password" { - t.Errorf("unexpected password, expected %q, actual %q", "password", p) - } - w.WriteHeader(http.StatusNoContent) - })) - defer ts.Close() - - u, _ := url.Parse(ts.URL) - u.User = url.UserPassword("username", "password") - config := client.Config{URL: *u, Username: "username", Password: "password"} - c, err := client.NewClient(config) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - - _, _, err = c.Ping() - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } -} - -func TestClient_Write(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var data client.Response - w.WriteHeader(http.StatusNoContent) - _ = json.NewEncoder(w).Encode(data) - })) - defer ts.Close() - - u, _ := url.Parse(ts.URL) - config := client.Config{URL: *u} - c, err := client.NewClient(config) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - - bp := client.BatchPoints{} - r, err := c.Write(bp) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - if r != nil { - t.Fatalf("unexpected response. expected %v, actual %v", nil, r) - } -} - -func TestClient_UserAgent(t *testing.T) { - receivedUserAgent := "" - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - receivedUserAgent = r.UserAgent() - - var data client.Response - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(data) - })) - defer ts.Close() - - _, err := http.Get(ts.URL) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - - tests := []struct { - name string - userAgent string - expected string - }{ - { - name: "Empty user agent", - userAgent: "", - expected: "InfluxDBClient", - }, - { - name: "Custom user agent", - userAgent: "Test Influx Client", - expected: "Test Influx Client", - }, - } - - for _, test := range tests { - u, _ := url.Parse(ts.URL) - config := client.Config{URL: *u, UserAgent: test.userAgent} - c, err := client.NewClient(config) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - - receivedUserAgent = "" - query := client.Query{} - _, err = c.Query(query) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - if !strings.HasPrefix(receivedUserAgent, test.expected) { - t.Fatalf("Unexpected user agent. expected %v, actual %v", test.expected, receivedUserAgent) - } - - receivedUserAgent = "" - bp := client.BatchPoints{} - _, err = c.Write(bp) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - if !strings.HasPrefix(receivedUserAgent, test.expected) { - t.Fatalf("Unexpected user agent. expected %v, actual %v", test.expected, receivedUserAgent) - } - - receivedUserAgent = "" - _, _, err = c.Ping() - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - if receivedUserAgent != test.expected { - t.Fatalf("Unexpected user agent. expected %v, actual %v", test.expected, receivedUserAgent) - } - } -} - -func TestClient_Messages(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - w.Write([]byte(`{"results":[{"messages":[{"level":"warning","text":"deprecation test"}]}]}`)) - })) - defer ts.Close() - - u, _ := url.Parse(ts.URL) - config := client.Config{URL: *u} - c, err := client.NewClient(config) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - - query := client.Query{} - resp, err := c.Query(query) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - - if got, exp := len(resp.Results), 1; got != exp { - t.Fatalf("unexpected number of results. expected %v, actual %v", exp, got) - } - - r := resp.Results[0] - if got, exp := len(r.Messages), 1; got != exp { - t.Fatalf("unexpected number of messages. expected %v, actual %v", exp, got) - } - - m := r.Messages[0] - if got, exp := m.Level, "warning"; got != exp { - t.Errorf("unexpected message level. expected %v, actual %v", exp, got) - } - if got, exp := m.Text, "deprecation test"; got != exp { - t.Errorf("unexpected message text. expected %v, actual %v", exp, got) - } -} - -func TestPoint_UnmarshalEpoch(t *testing.T) { - now := time.Now() - tests := []struct { - name string - epoch int64 - precision string - expected time.Time - }{ - { - name: "nanoseconds", - epoch: now.UnixNano(), - precision: "n", - expected: now, - }, - { - name: "microseconds", - epoch: now.Round(time.Microsecond).UnixNano() / int64(time.Microsecond), - precision: "u", - expected: now.Round(time.Microsecond), - }, - { - name: "milliseconds", - epoch: now.Round(time.Millisecond).UnixNano() / int64(time.Millisecond), - precision: "ms", - expected: now.Round(time.Millisecond), - }, - { - name: "seconds", - epoch: now.Round(time.Second).UnixNano() / int64(time.Second), - precision: "s", - expected: now.Round(time.Second), - }, - { - name: "minutes", - epoch: now.Round(time.Minute).UnixNano() / int64(time.Minute), - precision: "m", - expected: now.Round(time.Minute), - }, - { - name: "hours", - epoch: now.Round(time.Hour).UnixNano() / int64(time.Hour), - precision: "h", - expected: now.Round(time.Hour), - }, - { - name: "max int64", - epoch: 9223372036854775807, - precision: "n", - expected: time.Unix(0, 9223372036854775807), - }, - { - name: "100 years from now", - epoch: now.Add(time.Hour * 24 * 365 * 100).UnixNano(), - precision: "n", - expected: now.Add(time.Hour * 24 * 365 * 100), - }, - } - - for _, test := range tests { - t.Logf("testing %q\n", test.name) - data := []byte(fmt.Sprintf(`{"time": %d, "precision":"%s"}`, test.epoch, test.precision)) - t.Logf("json: %s", string(data)) - var p client.Point - err := json.Unmarshal(data, &p) - if err != nil { - t.Fatalf("unexpected error. exptected: %v, actual: %v", nil, err) - } - if !p.Time.Equal(test.expected) { - t.Fatalf("Unexpected time. expected: %v, actual: %v", test.expected, p.Time) - } - } -} - -func TestPoint_UnmarshalRFC(t *testing.T) { - now := time.Now().UTC() - tests := []struct { - name string - rfc string - now time.Time - expected time.Time - }{ - { - name: "RFC3339Nano", - rfc: time.RFC3339Nano, - now: now, - expected: now, - }, - { - name: "RFC3339", - rfc: time.RFC3339, - now: now.Round(time.Second), - expected: now.Round(time.Second), - }, - } - - for _, test := range tests { - t.Logf("testing %q\n", test.name) - ts := test.now.Format(test.rfc) - data := []byte(fmt.Sprintf(`{"time": %q}`, ts)) - t.Logf("json: %s", string(data)) - var p client.Point - err := json.Unmarshal(data, &p) - if err != nil { - t.Fatalf("unexpected error. exptected: %v, actual: %v", nil, err) - } - if !p.Time.Equal(test.expected) { - t.Fatalf("Unexpected time. expected: %v, actual: %v", test.expected, p.Time) - } - } -} - -func TestPoint_MarshalOmitempty(t *testing.T) { - now := time.Now().UTC() - tests := []struct { - name string - point client.Point - now time.Time - expected string - }{ - { - name: "all empty", - point: client.Point{Measurement: "cpu", Fields: map[string]interface{}{"value": 1.1}}, - now: now, - expected: `{"measurement":"cpu","fields":{"value":1.1}}`, - }, - { - name: "with time", - point: client.Point{Measurement: "cpu", Fields: map[string]interface{}{"value": 1.1}, Time: now}, - now: now, - expected: fmt.Sprintf(`{"measurement":"cpu","time":"%s","fields":{"value":1.1}}`, now.Format(time.RFC3339Nano)), - }, - { - name: "with tags", - point: client.Point{Measurement: "cpu", Fields: map[string]interface{}{"value": 1.1}, Tags: map[string]string{"foo": "bar"}}, - now: now, - expected: `{"measurement":"cpu","tags":{"foo":"bar"},"fields":{"value":1.1}}`, - }, - { - name: "with precision", - point: client.Point{Measurement: "cpu", Fields: map[string]interface{}{"value": 1.1}, Precision: "ms"}, - now: now, - expected: `{"measurement":"cpu","fields":{"value":1.1},"precision":"ms"}`, - }, - } - - for _, test := range tests { - t.Logf("testing %q\n", test.name) - b, err := json.Marshal(&test.point) - if err != nil { - t.Fatalf("unexpected error. exptected: %v, actual: %v", nil, err) - } - if test.expected != string(b) { - t.Fatalf("Unexpected result. expected: %v, actual: %v", test.expected, string(b)) - } - } -} - -func TestEpochToTime(t *testing.T) { - now := time.Now() - - tests := []struct { - name string - epoch int64 - precision string - expected time.Time - }{ - {name: "nanoseconds", epoch: now.UnixNano(), precision: "n", expected: now}, - {name: "microseconds", epoch: now.Round(time.Microsecond).UnixNano() / int64(time.Microsecond), precision: "u", expected: now.Round(time.Microsecond)}, - {name: "milliseconds", epoch: now.Round(time.Millisecond).UnixNano() / int64(time.Millisecond), precision: "ms", expected: now.Round(time.Millisecond)}, - {name: "seconds", epoch: now.Round(time.Second).UnixNano() / int64(time.Second), precision: "s", expected: now.Round(time.Second)}, - {name: "minutes", epoch: now.Round(time.Minute).UnixNano() / int64(time.Minute), precision: "m", expected: now.Round(time.Minute)}, - {name: "hours", epoch: now.Round(time.Hour).UnixNano() / int64(time.Hour), precision: "h", expected: now.Round(time.Hour)}, - } - - for _, test := range tests { - t.Logf("testing %q\n", test.name) - tm, e := client.EpochToTime(test.epoch, test.precision) - if e != nil { - t.Fatalf("unexpected error: expected %v, actual: %v", nil, e) - } - if tm != test.expected { - t.Fatalf("unexpected time: expected %v, actual %v", test.expected, tm) - } - } -} - -// helper functions - -func emptyTestServer() *httptest.Server { - return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - time.Sleep(50 * time.Millisecond) - w.Header().Set("X-Influxdb-Version", "x.x") - return - })) -} - -// Ensure that data with epoch times can be decoded. -func TestBatchPoints_Normal(t *testing.T) { - var bp client.BatchPoints - data := []byte(` -{ - "database": "foo", - "retentionPolicy": "bar", - "points": [ - { - "name": "cpu", - "tags": { - "host": "server01" - }, - "time": 14244733039069373, - "precision": "n", - "values": { - "value": 4541770385657154000 - } - }, - { - "name": "cpu", - "tags": { - "host": "server01" - }, - "time": 14244733039069380, - "precision": "n", - "values": { - "value": 7199311900554737000 - } - } - ] -} -`) - - if err := json.Unmarshal(data, &bp); err != nil { - t.Errorf("unable to unmarshal nanosecond data: %s", err.Error()) - } -} - -func TestClient_Timeout(t *testing.T) { - done := make(chan bool) - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - <-done - })) - defer ts.Close() - defer func() { done <- true }() - u, _ := url.Parse(ts.URL) - config := client.Config{URL: *u, Timeout: 500 * time.Millisecond} - c, err := client.NewClient(config) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - query := client.Query{} - _, err = c.Query(query) - if err == nil { - t.Fatalf("unexpected success. expected timeout error") - } else if !strings.Contains(err.Error(), "request canceled") && - !strings.Contains(err.Error(), "use of closed network connection") { - t.Fatalf("unexpected error. expected 'request canceled' error, got %v", err) - } -} - -func TestClient_NoTimeout(t *testing.T) { - if testing.Short() { - t.Skip("skipping in short mode") - } - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - time.Sleep(1 * time.Second) - var data client.Response - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(data) - })) - defer ts.Close() - - u, _ := url.Parse(ts.URL) - config := client.Config{URL: *u} - c, err := client.NewClient(config) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - - query := client.Query{} - _, err = c.Query(query) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } -} - -func TestClient_WriteUint64(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var data client.Response - w.WriteHeader(http.StatusNoContent) - _ = json.NewEncoder(w).Encode(data) - })) - defer ts.Close() - - u, _ := url.Parse(ts.URL) - config := client.Config{URL: *u} - c, err := client.NewClient(config) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - bp := client.BatchPoints{ - Points: []client.Point{ - { - Fields: map[string]interface{}{"value": uint64(10)}, - }, - }, - } - r, err := c.Write(bp) - if err == nil { - t.Fatalf("unexpected error. expected err, actual %v", err) - } - if r != nil { - t.Fatalf("unexpected response. expected %v, actual %v", nil, r) - } -} - -func TestClient_ParseConnectionString_IPv6(t *testing.T) { - path := "[fdf5:9ede:1875:0:a9ee:a600:8fe3:d495]:8086" - u, err := client.ParseConnectionString(path, false) - if err != nil { - t.Fatalf("unexpected error, expected %v, actual %v", nil, err) - } - if u.Host != path { - t.Fatalf("ipv6 parse failed, expected %s, actual %s", path, u.Host) - } -} - -func TestClient_CustomCertificates(t *testing.T) { - // generated with: - // openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650 -nodes -config influx.cnf - // influx.cnf: - // [req] - // distinguished_name = req_distinguished_name - // x509_extensions = v3_req - // prompt = no - // [req_distinguished_name] - // C = US - // ST = CA - // L = San Francisco - // O = InfluxDB - // CN = github.com/influxdata - // [v3_req] - // keyUsage = keyEncipherment, dataEncipherment - // extendedKeyUsage = serverAuth - // subjectAltName = @alt_names - // [alt_names] - // IP.1 = 127.0.0.1 - // - key := ` ------BEGIN PRIVATE KEY----- -MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDLswqKJLxfhBRi -4qdj7+jpBxTAi4MewrcMPp+9YlbLke3F7w2DPrZVkYVeWmg8LyTPAigrXeadK6hv -qjRr05a7sMc5+ynivGbWUySWT+u17V85x6VR5TMIkJEOqpiIU8aYk0l+3UcrzVjS -1QZCUBoxVwAVaSR6AXTA8YrVXdk/AI3f22dYiBjFmV4LJJkGjTaCnlDKu54hMU1t -WTyFcoY9TBzZ1XA+ng5RQ/QADeL2PYrTW4s/mLI3jfKKD53EI4uM2FjW37ZfuxTa -mhCR7/lxM4COg9K70y5uebfqJvuoXAwXLOzVbdfF5b9fJFbL67kaK2tiMT3Wt39m -hXzclLTDAgMBAAECggEAK8mpElkjRUUXPMqMQSdpYe5rv5g973bb8n3jyMpC7i/I -dSwWM4hfmbVWfhnhHk7kErvb9raQxGiGJLrp2eP6Gw69RPGA54SodpoY21cCzHDi -b4FDQH+MoOKyy/xQHb4kitfejK70ha320huI5OhjOQgCtJeNh8yYVIGX3pX2BVyu -36UB9tfX1S5pbiHeih3vZGd322Muj/joNzIelnYRBnoO0xqvQ0S1Dk+dLCTHO0/m -u9AZN8c2TsRWZpJPMWwBv8LuABbE0e66/TSsrfklAn86ELCo44lZURDE7uPZ4pIH -FWtmf+nW5Hy6aPhy60E40MqotlejhWwB3ktY/m3JAQKBgQDuB4nhxzJA9lH9EaCt -byvJ9wGVvI3k79hOwc/Z2R3dNe+Ma+TJy+aBppvsLF4qz83aWC+canyasbHcPNR/ -vXQGlsgKfucrmd1PfMV7uvOIkfOjK0E6mRC+jMuKtNTQrdtM1BU/Z7LY0iy0fNJ6 -aNqhFdlJmmk0g+4bR4SAWB6FkwKBgQDbE/7r1u+GdJk/mhdjTi1aegr9lXb0l7L6 -BCvOYhs/Z/pXfsaYPSXhgk2w+LiGk6BaEA2/4Sr0YS2MAAaIhBVeFBIXVpNrXB3K -Yg1jOEeLQ3qoVBeJFhJNrN9ZQx33HANC1W/Y1apMwaYqCRUGVQkrdcsN2KNea1z0 -3qeYeCCSEQKBgCKZKeuNfrp+k1BLnaVYAW9r3ekb7SwXyMM53LJ3oqWiz10D2c+T -OcAirYtYr59dcTiJlPIRcGcz6PxwQxsGOLU0eYM9CvEFfmutYS8o73ksbdOL2AFi -elKYOIXC3yQuATBbq3L56b8mXaUmd5mfYBgGCv1t2ljtzFBext248UbNAoGBAIv1 -2V24YiwnH6THf/ucfVMZNx5Mt8OJivk5YvcmLDw05HWzc5LdNe89PP871z963u3K -5c3ZP4UC9INFnOboY3JIJkqsr9/d6NZcECt8UBDDmoAhwSt+Y1EmiUZQn7s4NUkk -bKE919/Ts6GVTc5O013lkkUVS0HOG4QBH1dEH6LRAoGAStl11WA9tuKXiBl5XG/C -cq9mFPNJK3pEgd6YH874vEnYEEqENR4MFK3uWXus9Nm+VYxbUbPEzFF4kpsfukDg -/JAVqY4lUam7g6fyyaoIIPQEp7jGjbsUf46IjnUjFcaojOugA3EAfn9awREUDuJZ -cvh4WzEegcExTppINW1NB5E= ------END PRIVATE KEY----- -` - cert := ` ------BEGIN CERTIFICATE----- -MIIDdjCCAl6gAwIBAgIJAMYGAwkxUV51MA0GCSqGSIb3DQEBCwUAMFgxCzAJBgNV -BAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzERMA8G -A1UECgwISW5mbHV4REIxETAPBgNVBAMMCGluZmx1eGRiMB4XDTE1MTIyOTAxNTg1 -NloXDTI1MTIyNjAxNTg1NlowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMRYw -FAYDVQQHDA1TYW4gRnJhbmNpc2NvMREwDwYDVQQKDAhJbmZsdXhEQjERMA8GA1UE -AwwIaW5mbHV4ZGIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDLswqK -JLxfhBRi4qdj7+jpBxTAi4MewrcMPp+9YlbLke3F7w2DPrZVkYVeWmg8LyTPAigr -XeadK6hvqjRr05a7sMc5+ynivGbWUySWT+u17V85x6VR5TMIkJEOqpiIU8aYk0l+ -3UcrzVjS1QZCUBoxVwAVaSR6AXTA8YrVXdk/AI3f22dYiBjFmV4LJJkGjTaCnlDK -u54hMU1tWTyFcoY9TBzZ1XA+ng5RQ/QADeL2PYrTW4s/mLI3jfKKD53EI4uM2FjW -37ZfuxTamhCR7/lxM4COg9K70y5uebfqJvuoXAwXLOzVbdfF5b9fJFbL67kaK2ti -MT3Wt39mhXzclLTDAgMBAAGjQzBBMAwGA1UdEwQFMAMBAf8wCwYDVR0PBAQDAgQw -MBMGA1UdJQQMMAoGCCsGAQUFBwMBMA8GA1UdEQQIMAaHBH8AAAEwDQYJKoZIhvcN -AQELBQADggEBAJxgHeduV9q2BuKnrt+sjXLGn/HwbMbgGbgFK6kUKJBWtv6Pa7JJ -m4teDmTMWiaeB2g4N2bmaWTuEZzzShNKG5roFeWm1ilFMAyzkb+VifN4YuDKH62F -3e259qsytiGbbJF3F//4sjfMw8qZVEPvspG1zKsASo0PpSOOUFmxcj0oMAXhnMrk -rRcbk6fufhyq0iZGl8ZLKTCrkjk0b3qlNs6UaRD9/XBB59VlQ8I338sfjV06edwY -jn5Amab0uyoFNEp70Y4WGxrxUTS1GAC1LCA13S7EnidD440UrnWALTarjmHAK6aW -war3JNM1mGB3o2iAtuOJlFIKLpI1x+1e8pI= ------END CERTIFICATE----- -` - cer, err := tls.X509KeyPair([]byte(cert), []byte(key)) - - if err != nil { - t.Fatalf("Received error: %v", err) - } - - server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var data client.Response - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(data) - })) - server.TLS = &tls.Config{Certificates: []tls.Certificate{cer}} - server.TLS.BuildNameToCertificate() - server.StartTLS() - defer server.Close() - - certFile, _ := ioutil.TempFile("", "influx-cert-") - certFile.WriteString(cert) - certFile.Close() - defer os.Remove(certFile.Name()) - - u, _ := url.Parse(server.URL) - - tests := []struct { - name string - unsafeSsl bool - expected error - }{ - {name: "validate certificates", unsafeSsl: false, expected: errors.New("error")}, - {name: "not validate certificates", unsafeSsl: true, expected: nil}, - } - - for _, test := range tests { - config := client.Config{URL: *u, UnsafeSsl: test.unsafeSsl} - c, err := client.NewClient(config) - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } - query := client.Query{} - _, err = c.Query(query) - - if (test.expected == nil) != (err == nil) { - t.Fatalf("%s: expected %v. got %v. unsafeSsl: %v", test.name, test.expected, err, test.unsafeSsl) - } - } -} - -func TestChunkedResponse(t *testing.T) { - s := `{"results":[{},{}]}{"results":[{}]}` - r := client.NewChunkedResponse(strings.NewReader(s)) - resp, err := r.NextResponse() - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } else if actual := len(resp.Results); actual != 2 { - t.Fatalf("unexpected number of results. expected %v, actual %v", 2, actual) - } - - resp, err = r.NextResponse() - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } else if actual := len(resp.Results); actual != 1 { - t.Fatalf("unexpected number of results. expected %v, actual %v", 1, actual) - } - - resp, err = r.NextResponse() - if err != nil { - t.Fatalf("unexpected error. expected %v, actual %v", nil, err) - } else if resp != nil { - t.Fatalf("unexpected response. expected %v, actual %v", nil, resp) - } -} diff --git a/vendor/github.com/influxdata/influxdb/client/v2/BUILD b/vendor/github.com/influxdata/influxdb/client/v2/BUILD index 37d30e39aa4a..a9f7f6eded8a 100644 --- a/vendor/github.com/influxdata/influxdb/client/v2/BUILD +++ b/vendor/github.com/influxdata/influxdb/client/v2/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -11,20 +11,6 @@ go_library( deps = ["//vendor/github.com/influxdata/influxdb/models:go_default_library"], ) -go_test( - name = "go_default_test", - srcs = ["client_test.go"], - importpath = "github.com/influxdata/influxdb/client/v2", - library = ":go_default_library", -) - -go_test( - name = "go_default_xtest", - srcs = ["example_test.go"], - importpath = "github.com/influxdata/influxdb/client/v2_test", - deps = [":go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/influxdata/influxdb/client/v2/client_test.go b/vendor/github.com/influxdata/influxdb/client/v2/client_test.go deleted file mode 100644 index 30ee09df4466..000000000000 --- a/vendor/github.com/influxdata/influxdb/client/v2/client_test.go +++ /dev/null @@ -1,480 +0,0 @@ -package client - -import ( - "encoding/json" - "net/http" - "net/http/httptest" - "reflect" - "strings" - "sync" - "testing" - "time" -) - -func TestUDPClient_Query(t *testing.T) { - config := UDPConfig{Addr: "localhost:8089"} - c, err := NewUDPClient(config) - if err != nil { - t.Errorf("unexpected error. expected %v, actual %v", nil, err) - } - defer c.Close() - query := Query{} - _, err = c.Query(query) - if err == nil { - t.Error("Querying UDP client should fail") - } -} - -func TestUDPClient_Ping(t *testing.T) { - config := UDPConfig{Addr: "localhost:8089"} - c, err := NewUDPClient(config) - if err != nil { - t.Errorf("unexpected error. expected %v, actual %v", nil, err) - } - defer c.Close() - - rtt, version, err := c.Ping(0) - if rtt != 0 || version != "" || err != nil { - t.Errorf("unexpected error. expected (%v, '%v', %v), actual (%v, '%v', %v)", 0, "", nil, rtt, version, err) - } -} - -func TestUDPClient_Write(t *testing.T) { - config := UDPConfig{Addr: "localhost:8089"} - c, err := NewUDPClient(config) - if err != nil { - t.Errorf("unexpected error. expected %v, actual %v", nil, err) - } - defer c.Close() - - bp, err := NewBatchPoints(BatchPointsConfig{}) - if err != nil { - t.Errorf("unexpected error. expected %v, actual %v", nil, err) - } - - fields := make(map[string]interface{}) - fields["value"] = 1.0 - pt, _ := NewPoint("cpu", make(map[string]string), fields) - bp.AddPoint(pt) - - err = c.Write(bp) - if err != nil { - t.Errorf("unexpected error. expected %v, actual %v", nil, err) - } -} - -func TestUDPClient_BadAddr(t *testing.T) { - config := UDPConfig{Addr: "foobar@wahoo"} - c, err := NewUDPClient(config) - if err == nil { - defer c.Close() - t.Error("Expected resolve error") - } -} - -func TestUDPClient_Batches(t *testing.T) { - var logger writeLogger - var cl udpclient - - cl.conn = &logger - cl.payloadSize = 20 // should allow for two points per batch - - // expected point should look like this: "cpu a=1i" - fields := map[string]interface{}{"a": 1} - - p, _ := NewPoint("cpu", nil, fields, time.Time{}) - - bp, _ := NewBatchPoints(BatchPointsConfig{}) - - for i := 0; i < 9; i++ { - bp.AddPoint(p) - } - - if err := cl.Write(bp); err != nil { - t.Fatalf("Unexpected error during Write: %v", err) - } - - if len(logger.writes) != 5 { - t.Errorf("Mismatched write count: got %v, exp %v", len(logger.writes), 5) - } -} - -func TestUDPClient_Split(t *testing.T) { - var logger writeLogger - var cl udpclient - - cl.conn = &logger - cl.payloadSize = 1 // force one field per point - - fields := map[string]interface{}{"a": 1, "b": 2, "c": 3, "d": 4} - - p, _ := NewPoint("cpu", nil, fields, time.Unix(1, 0)) - - bp, _ := NewBatchPoints(BatchPointsConfig{}) - - bp.AddPoint(p) - - if err := cl.Write(bp); err != nil { - t.Fatalf("Unexpected error during Write: %v", err) - } - - if len(logger.writes) != len(fields) { - t.Errorf("Mismatched write count: got %v, exp %v", len(logger.writes), len(fields)) - } -} - -type writeLogger struct { - writes [][]byte -} - -func (w *writeLogger) Write(b []byte) (int, error) { - w.writes = append(w.writes, append([]byte(nil), b...)) - return len(b), nil -} - -func (w *writeLogger) Close() error { return nil } - -func TestClient_Query(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var data Response - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(data) - })) - defer ts.Close() - - config := HTTPConfig{Addr: ts.URL} - c, _ := NewHTTPClient(config) - defer c.Close() - - query := Query{} - _, err := c.Query(query) - if err != nil { - t.Errorf("unexpected error. expected %v, actual %v", nil, err) - } -} - -func TestClient_BasicAuth(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - u, p, ok := r.BasicAuth() - - if !ok { - t.Errorf("basic auth error") - } - if u != "username" { - t.Errorf("unexpected username, expected %q, actual %q", "username", u) - } - if p != "password" { - t.Errorf("unexpected password, expected %q, actual %q", "password", p) - } - var data Response - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(data) - })) - defer ts.Close() - - config := HTTPConfig{Addr: ts.URL, Username: "username", Password: "password"} - c, _ := NewHTTPClient(config) - defer c.Close() - - query := Query{} - _, err := c.Query(query) - if err != nil { - t.Errorf("unexpected error. expected %v, actual %v", nil, err) - } -} - -func TestClient_Ping(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var data Response - w.WriteHeader(http.StatusNoContent) - _ = json.NewEncoder(w).Encode(data) - })) - defer ts.Close() - - config := HTTPConfig{Addr: ts.URL} - c, _ := NewHTTPClient(config) - defer c.Close() - - _, _, err := c.Ping(0) - if err != nil { - t.Errorf("unexpected error. expected %v, actual %v", nil, err) - } -} - -func TestClient_Concurrent_Use(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - w.Write([]byte(`{}`)) - })) - defer ts.Close() - - config := HTTPConfig{Addr: ts.URL} - c, _ := NewHTTPClient(config) - defer c.Close() - - var wg sync.WaitGroup - wg.Add(3) - n := 1000 - - go func() { - defer wg.Done() - bp, err := NewBatchPoints(BatchPointsConfig{}) - if err != nil { - t.Errorf("got error %v", err) - } - - for i := 0; i < n; i++ { - if err = c.Write(bp); err != nil { - t.Fatalf("got error %v", err) - } - } - }() - - go func() { - defer wg.Done() - var q Query - for i := 0; i < n; i++ { - if _, err := c.Query(q); err != nil { - t.Fatalf("got error %v", err) - } - } - }() - - go func() { - defer wg.Done() - for i := 0; i < n; i++ { - c.Ping(time.Second) - } - }() - wg.Wait() -} - -func TestClient_Write(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var data Response - w.WriteHeader(http.StatusNoContent) - _ = json.NewEncoder(w).Encode(data) - })) - defer ts.Close() - - config := HTTPConfig{Addr: ts.URL} - c, _ := NewHTTPClient(config) - defer c.Close() - - bp, err := NewBatchPoints(BatchPointsConfig{}) - if err != nil { - t.Errorf("unexpected error. expected %v, actual %v", nil, err) - } - err = c.Write(bp) - if err != nil { - t.Errorf("unexpected error. expected %v, actual %v", nil, err) - } -} - -func TestClient_UserAgent(t *testing.T) { - receivedUserAgent := "" - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - receivedUserAgent = r.UserAgent() - - var data Response - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(data) - })) - defer ts.Close() - - _, err := http.Get(ts.URL) - if err != nil { - t.Errorf("unexpected error. expected %v, actual %v", nil, err) - } - - tests := []struct { - name string - userAgent string - expected string - }{ - { - name: "Empty user agent", - userAgent: "", - expected: "InfluxDBClient", - }, - { - name: "Custom user agent", - userAgent: "Test Influx Client", - expected: "Test Influx Client", - }, - } - - for _, test := range tests { - - config := HTTPConfig{Addr: ts.URL, UserAgent: test.userAgent} - c, _ := NewHTTPClient(config) - defer c.Close() - - receivedUserAgent = "" - query := Query{} - _, err = c.Query(query) - if err != nil { - t.Errorf("unexpected error. expected %v, actual %v", nil, err) - } - if !strings.HasPrefix(receivedUserAgent, test.expected) { - t.Errorf("Unexpected user agent. expected %v, actual %v", test.expected, receivedUserAgent) - } - - receivedUserAgent = "" - bp, _ := NewBatchPoints(BatchPointsConfig{}) - err = c.Write(bp) - if err != nil { - t.Errorf("unexpected error. expected %v, actual %v", nil, err) - } - if !strings.HasPrefix(receivedUserAgent, test.expected) { - t.Errorf("Unexpected user agent. expected %v, actual %v", test.expected, receivedUserAgent) - } - - receivedUserAgent = "" - _, err := c.Query(query) - if err != nil { - t.Errorf("unexpected error. expected %v, actual %v", nil, err) - } - if receivedUserAgent != test.expected { - t.Errorf("Unexpected user agent. expected %v, actual %v", test.expected, receivedUserAgent) - } - } -} - -func TestClient_PointString(t *testing.T) { - const shortForm = "2006-Jan-02" - time1, _ := time.Parse(shortForm, "2013-Feb-03") - tags := map[string]string{"cpu": "cpu-total"} - fields := map[string]interface{}{"idle": 10.1, "system": 50.9, "user": 39.0} - p, _ := NewPoint("cpu_usage", tags, fields, time1) - - s := "cpu_usage,cpu=cpu-total idle=10.1,system=50.9,user=39 1359849600000000000" - if p.String() != s { - t.Errorf("Point String Error, got %s, expected %s", p.String(), s) - } - - s = "cpu_usage,cpu=cpu-total idle=10.1,system=50.9,user=39 1359849600000" - if p.PrecisionString("ms") != s { - t.Errorf("Point String Error, got %s, expected %s", - p.PrecisionString("ms"), s) - } -} - -func TestClient_PointWithoutTimeString(t *testing.T) { - tags := map[string]string{"cpu": "cpu-total"} - fields := map[string]interface{}{"idle": 10.1, "system": 50.9, "user": 39.0} - p, _ := NewPoint("cpu_usage", tags, fields) - - s := "cpu_usage,cpu=cpu-total idle=10.1,system=50.9,user=39" - if p.String() != s { - t.Errorf("Point String Error, got %s, expected %s", p.String(), s) - } - - if p.PrecisionString("ms") != s { - t.Errorf("Point String Error, got %s, expected %s", - p.PrecisionString("ms"), s) - } -} - -func TestClient_PointName(t *testing.T) { - tags := map[string]string{"cpu": "cpu-total"} - fields := map[string]interface{}{"idle": 10.1, "system": 50.9, "user": 39.0} - p, _ := NewPoint("cpu_usage", tags, fields) - - exp := "cpu_usage" - if p.Name() != exp { - t.Errorf("Error, got %s, expected %s", - p.Name(), exp) - } -} - -func TestClient_PointTags(t *testing.T) { - tags := map[string]string{"cpu": "cpu-total"} - fields := map[string]interface{}{"idle": 10.1, "system": 50.9, "user": 39.0} - p, _ := NewPoint("cpu_usage", tags, fields) - - if !reflect.DeepEqual(tags, p.Tags()) { - t.Errorf("Error, got %v, expected %v", - p.Tags(), tags) - } -} - -func TestClient_PointUnixNano(t *testing.T) { - const shortForm = "2006-Jan-02" - time1, _ := time.Parse(shortForm, "2013-Feb-03") - tags := map[string]string{"cpu": "cpu-total"} - fields := map[string]interface{}{"idle": 10.1, "system": 50.9, "user": 39.0} - p, _ := NewPoint("cpu_usage", tags, fields, time1) - - exp := int64(1359849600000000000) - if p.UnixNano() != exp { - t.Errorf("Error, got %d, expected %d", - p.UnixNano(), exp) - } -} - -func TestClient_PointFields(t *testing.T) { - tags := map[string]string{"cpu": "cpu-total"} - fields := map[string]interface{}{"idle": 10.1, "system": 50.9, "user": 39.0} - p, _ := NewPoint("cpu_usage", tags, fields) - - if !reflect.DeepEqual(fields, p.Fields()) { - t.Errorf("Error, got %v, expected %v", - p.Fields(), fields) - } -} - -func TestBatchPoints_PrecisionError(t *testing.T) { - _, err := NewBatchPoints(BatchPointsConfig{Precision: "foobar"}) - if err == nil { - t.Errorf("Precision: foobar should have errored") - } - - bp, _ := NewBatchPoints(BatchPointsConfig{Precision: "ns"}) - err = bp.SetPrecision("foobar") - if err == nil { - t.Errorf("Precision: foobar should have errored") - } -} - -func TestBatchPoints_SettersGetters(t *testing.T) { - bp, _ := NewBatchPoints(BatchPointsConfig{ - Precision: "ns", - Database: "db", - RetentionPolicy: "rp", - WriteConsistency: "wc", - }) - if bp.Precision() != "ns" { - t.Errorf("Expected: %s, got %s", bp.Precision(), "ns") - } - if bp.Database() != "db" { - t.Errorf("Expected: %s, got %s", bp.Database(), "db") - } - if bp.RetentionPolicy() != "rp" { - t.Errorf("Expected: %s, got %s", bp.RetentionPolicy(), "rp") - } - if bp.WriteConsistency() != "wc" { - t.Errorf("Expected: %s, got %s", bp.WriteConsistency(), "wc") - } - - bp.SetDatabase("db2") - bp.SetRetentionPolicy("rp2") - bp.SetWriteConsistency("wc2") - err := bp.SetPrecision("s") - if err != nil { - t.Errorf("Did not expect error: %s", err.Error()) - } - - if bp.Precision() != "s" { - t.Errorf("Expected: %s, got %s", bp.Precision(), "s") - } - if bp.Database() != "db2" { - t.Errorf("Expected: %s, got %s", bp.Database(), "db2") - } - if bp.RetentionPolicy() != "rp2" { - t.Errorf("Expected: %s, got %s", bp.RetentionPolicy(), "rp2") - } - if bp.WriteConsistency() != "wc2" { - t.Errorf("Expected: %s, got %s", bp.WriteConsistency(), "wc2") - } -} diff --git a/vendor/github.com/influxdata/influxdb/client/v2/example_test.go b/vendor/github.com/influxdata/influxdb/client/v2/example_test.go deleted file mode 100644 index 68bb24bc70d2..000000000000 --- a/vendor/github.com/influxdata/influxdb/client/v2/example_test.go +++ /dev/null @@ -1,265 +0,0 @@ -package client_test - -import ( - "fmt" - "math/rand" - "os" - "time" - - "github.com/influxdata/influxdb/client/v2" -) - -// Create a new client -func ExampleClient() { - // NOTE: this assumes you've setup a user and have setup shell env variables, - // namely INFLUX_USER/INFLUX_PWD. If not just omit Username/Password below. - _, err := client.NewHTTPClient(client.HTTPConfig{ - Addr: "http://localhost:8086", - Username: os.Getenv("INFLUX_USER"), - Password: os.Getenv("INFLUX_PWD"), - }) - if err != nil { - fmt.Println("Error creating InfluxDB Client: ", err.Error()) - } -} - -// Write a point using the UDP client -func ExampleClient_uDP() { - // Make client - config := client.UDPConfig{Addr: "localhost:8089"} - c, err := client.NewUDPClient(config) - if err != nil { - fmt.Println("Error: ", err.Error()) - } - defer c.Close() - - // Create a new point batch - bp, _ := client.NewBatchPoints(client.BatchPointsConfig{ - Precision: "s", - }) - - // Create a point and add to batch - tags := map[string]string{"cpu": "cpu-total"} - fields := map[string]interface{}{ - "idle": 10.1, - "system": 53.3, - "user": 46.6, - } - pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now()) - if err != nil { - fmt.Println("Error: ", err.Error()) - } - bp.AddPoint(pt) - - // Write the batch - c.Write(bp) -} - -// Ping the cluster using the HTTP client -func ExampleClient_Ping() { - // Make client - c, err := client.NewHTTPClient(client.HTTPConfig{ - Addr: "http://localhost:8086", - }) - if err != nil { - fmt.Println("Error creating InfluxDB Client: ", err.Error()) - } - defer c.Close() - - _, _, err = c.Ping(0) - if err != nil { - fmt.Println("Error pinging InfluxDB Cluster: ", err.Error()) - } -} - -// Write a point using the HTTP client -func ExampleClient_write() { - // Make client - c, err := client.NewHTTPClient(client.HTTPConfig{ - Addr: "http://localhost:8086", - }) - if err != nil { - fmt.Println("Error creating InfluxDB Client: ", err.Error()) - } - defer c.Close() - - // Create a new point batch - bp, _ := client.NewBatchPoints(client.BatchPointsConfig{ - Database: "BumbleBeeTuna", - Precision: "s", - }) - - // Create a point and add to batch - tags := map[string]string{"cpu": "cpu-total"} - fields := map[string]interface{}{ - "idle": 10.1, - "system": 53.3, - "user": 46.6, - } - pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now()) - if err != nil { - fmt.Println("Error: ", err.Error()) - } - bp.AddPoint(pt) - - // Write the batch - c.Write(bp) -} - -// Create a batch and add a point -func ExampleBatchPoints() { - // Create a new point batch - bp, _ := client.NewBatchPoints(client.BatchPointsConfig{ - Database: "BumbleBeeTuna", - Precision: "s", - }) - - // Create a point and add to batch - tags := map[string]string{"cpu": "cpu-total"} - fields := map[string]interface{}{ - "idle": 10.1, - "system": 53.3, - "user": 46.6, - } - pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now()) - if err != nil { - fmt.Println("Error: ", err.Error()) - } - bp.AddPoint(pt) -} - -// Using the BatchPoints setter functions -func ExampleBatchPoints_setters() { - // Create a new point batch - bp, _ := client.NewBatchPoints(client.BatchPointsConfig{}) - bp.SetDatabase("BumbleBeeTuna") - bp.SetPrecision("ms") - - // Create a point and add to batch - tags := map[string]string{"cpu": "cpu-total"} - fields := map[string]interface{}{ - "idle": 10.1, - "system": 53.3, - "user": 46.6, - } - pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now()) - if err != nil { - fmt.Println("Error: ", err.Error()) - } - bp.AddPoint(pt) -} - -// Create a new point with a timestamp -func ExamplePoint() { - tags := map[string]string{"cpu": "cpu-total"} - fields := map[string]interface{}{ - "idle": 10.1, - "system": 53.3, - "user": 46.6, - } - pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now()) - if err == nil { - fmt.Println("We created a point: ", pt.String()) - } -} - -// Create a new point without a timestamp -func ExamplePoint_withoutTime() { - tags := map[string]string{"cpu": "cpu-total"} - fields := map[string]interface{}{ - "idle": 10.1, - "system": 53.3, - "user": 46.6, - } - pt, err := client.NewPoint("cpu_usage", tags, fields) - if err == nil { - fmt.Println("We created a point w/o time: ", pt.String()) - } -} - -// Write 1000 points -func ExampleClient_write1000() { - sampleSize := 1000 - - // Make client - c, err := client.NewHTTPClient(client.HTTPConfig{ - Addr: "http://localhost:8086", - }) - if err != nil { - fmt.Println("Error creating InfluxDB Client: ", err.Error()) - } - defer c.Close() - - rand.Seed(42) - - bp, _ := client.NewBatchPoints(client.BatchPointsConfig{ - Database: "systemstats", - Precision: "us", - }) - - for i := 0; i < sampleSize; i++ { - regions := []string{"us-west1", "us-west2", "us-west3", "us-east1"} - tags := map[string]string{ - "cpu": "cpu-total", - "host": fmt.Sprintf("host%d", rand.Intn(1000)), - "region": regions[rand.Intn(len(regions))], - } - - idle := rand.Float64() * 100.0 - fields := map[string]interface{}{ - "idle": idle, - "busy": 100.0 - idle, - } - - pt, err := client.NewPoint( - "cpu_usage", - tags, - fields, - time.Now(), - ) - if err != nil { - println("Error:", err.Error()) - continue - } - bp.AddPoint(pt) - } - - err = c.Write(bp) - if err != nil { - fmt.Println("Error: ", err.Error()) - } -} - -// Make a Query -func ExampleClient_query() { - // Make client - c, err := client.NewHTTPClient(client.HTTPConfig{ - Addr: "http://localhost:8086", - }) - if err != nil { - fmt.Println("Error creating InfluxDB Client: ", err.Error()) - } - defer c.Close() - - q := client.NewQuery("SELECT count(value) FROM shapes", "square_holes", "ns") - if response, err := c.Query(q); err == nil && response.Error() == nil { - fmt.Println(response.Results) - } -} - -// Create a Database with a query -func ExampleClient_createDatabase() { - // Make client - c, err := client.NewHTTPClient(client.HTTPConfig{ - Addr: "http://localhost:8086", - }) - if err != nil { - fmt.Println("Error creating InfluxDB Client: ", err.Error()) - } - defer c.Close() - - q := client.NewQuery("CREATE DATABASE telegraf", "", "") - if response, err := c.Query(q); err == nil && response.Error() == nil { - fmt.Println(response.Results) - } -} diff --git a/vendor/github.com/influxdata/influxdb/models/BUILD b/vendor/github.com/influxdata/influxdb/models/BUILD index 889d46406103..85d0f3e65d4f 100644 --- a/vendor/github.com/influxdata/influxdb/models/BUILD +++ b/vendor/github.com/influxdata/influxdb/models/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -16,24 +16,6 @@ go_library( deps = ["//vendor/github.com/influxdata/influxdb/pkg/escape:go_default_library"], ) -go_test( - name = "go_default_test", - srcs = ["inline_strconv_parse_test.go"], - importpath = "github.com/influxdata/influxdb/models", - library = ":go_default_library", -) - -go_test( - name = "go_default_xtest", - srcs = [ - "inline_fnv_test.go", - "points_test.go", - "statistic_test.go", - ], - importpath = "github.com/influxdata/influxdb/models_test", - deps = [":go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/influxdata/influxdb/models/inline_fnv_test.go b/vendor/github.com/influxdata/influxdb/models/inline_fnv_test.go deleted file mode 100644 index 62bc53ec0dce..000000000000 --- a/vendor/github.com/influxdata/influxdb/models/inline_fnv_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package models_test - -import ( - "hash/fnv" - "testing" - "testing/quick" - - "github.com/influxdata/influxdb/models" -) - -func TestInlineFNV64aEquivalenceFuzz(t *testing.T) { - f := func(data []byte) bool { - stdlibFNV := fnv.New64a() - stdlibFNV.Write(data) - want := stdlibFNV.Sum64() - - inlineFNV := models.NewInlineFNV64a() - inlineFNV.Write(data) - got := inlineFNV.Sum64() - - return want == got - } - cfg := &quick.Config{ - MaxCount: 10000, - } - if err := quick.Check(f, cfg); err != nil { - t.Fatal(err) - } -} diff --git a/vendor/github.com/influxdata/influxdb/models/inline_strconv_parse_test.go b/vendor/github.com/influxdata/influxdb/models/inline_strconv_parse_test.go deleted file mode 100644 index 119f543d78b0..000000000000 --- a/vendor/github.com/influxdata/influxdb/models/inline_strconv_parse_test.go +++ /dev/null @@ -1,103 +0,0 @@ -package models - -import ( - "strconv" - "testing" - "testing/quick" -) - -func TestParseIntBytesEquivalenceFuzz(t *testing.T) { - f := func(b []byte, base int, bitSize int) bool { - exp, expErr := strconv.ParseInt(string(b), base, bitSize) - got, gotErr := parseIntBytes(b, base, bitSize) - - return exp == got && checkErrs(expErr, gotErr) - } - - cfg := &quick.Config{ - MaxCount: 10000, - } - - if err := quick.Check(f, cfg); err != nil { - t.Fatal(err) - } -} - -func TestParseIntBytesValid64bitBase10EquivalenceFuzz(t *testing.T) { - buf := []byte{} - f := func(n int64) bool { - buf = strconv.AppendInt(buf[:0], n, 10) - - exp, expErr := strconv.ParseInt(string(buf), 10, 64) - got, gotErr := parseIntBytes(buf, 10, 64) - - return exp == got && checkErrs(expErr, gotErr) - } - - cfg := &quick.Config{ - MaxCount: 10000, - } - - if err := quick.Check(f, cfg); err != nil { - t.Fatal(err) - } -} - -func TestParseFloatBytesEquivalenceFuzz(t *testing.T) { - f := func(b []byte, bitSize int) bool { - exp, expErr := strconv.ParseFloat(string(b), bitSize) - got, gotErr := parseFloatBytes(b, bitSize) - - return exp == got && checkErrs(expErr, gotErr) - } - - cfg := &quick.Config{ - MaxCount: 10000, - } - - if err := quick.Check(f, cfg); err != nil { - t.Fatal(err) - } -} - -func TestParseFloatBytesValid64bitEquivalenceFuzz(t *testing.T) { - buf := []byte{} - f := func(n float64) bool { - buf = strconv.AppendFloat(buf[:0], n, 'f', -1, 64) - - exp, expErr := strconv.ParseFloat(string(buf), 64) - got, gotErr := parseFloatBytes(buf, 64) - - return exp == got && checkErrs(expErr, gotErr) - } - - cfg := &quick.Config{ - MaxCount: 10000, - } - - if err := quick.Check(f, cfg); err != nil { - t.Fatal(err) - } -} - -func TestParseBoolBytesEquivalence(t *testing.T) { - var buf []byte - for _, s := range []string{"1", "t", "T", "TRUE", "true", "True", "0", "f", "F", "FALSE", "false", "False", "fail", "TrUe", "FAlSE", "numbers", ""} { - buf = append(buf[:0], s...) - - exp, expErr := strconv.ParseBool(s) - got, gotErr := parseBoolBytes(buf) - - if got != exp || !checkErrs(expErr, gotErr) { - t.Errorf("Failed to parse boolean value %q correctly: wanted (%t, %v), got (%t, %v)", s, exp, expErr, got, gotErr) - } - } -} - -func checkErrs(a, b error) bool { - if (a == nil) != (b == nil) { - return false - } - - return a == nil || a.Error() == b.Error() -} diff --git a/vendor/github.com/influxdata/influxdb/models/points_test.go b/vendor/github.com/influxdata/influxdb/models/points_test.go deleted file mode 100644 index 0652964696ce..000000000000 --- a/vendor/github.com/influxdata/influxdb/models/points_test.go +++ /dev/null @@ -1,2170 +0,0 @@ -package models_test - -import ( - "bytes" - "fmt" - "math" - "math/rand" - "reflect" - "strconv" - "strings" - "testing" - "time" - - "github.com/influxdata/influxdb/models" -) - -var ( - tags = models.NewTags(map[string]string{"foo": "bar", "apple": "orange", "host": "serverA", "region": "uswest"}) - fields = models.Fields{ - "int64": int64(math.MaxInt64), - "uint32": uint32(math.MaxUint32), - "string": "String field that has a decent length, probably some log message or something", - "boolean": false, - "float64-tiny": float64(math.SmallestNonzeroFloat64), - "float64-large": float64(math.MaxFloat64), - } - maxFloat64 = strconv.FormatFloat(math.MaxFloat64, 'f', 1, 64) - minFloat64 = strconv.FormatFloat(-math.MaxFloat64, 'f', 1, 64) -) - -func TestMarshal(t *testing.T) { - got := tags.HashKey() - if exp := ",apple=orange,foo=bar,host=serverA,region=uswest"; string(got) != exp { - t.Log("got: ", string(got)) - t.Log("exp: ", exp) - t.Error("invalid match") - } -} - -func BenchmarkMarshal(b *testing.B) { - for i := 0; i < b.N; i++ { - tags.HashKey() - } -} - -func TestPoint_StringSize(t *testing.T) { - testPoint_cube(t, func(p models.Point) { - l := p.StringSize() - s := p.String() - - if l != len(s) { - t.Errorf("Incorrect length for %q. got %v, exp %v", s, l, len(s)) - } - }) - -} - -func TestPoint_AppendString(t *testing.T) { - testPoint_cube(t, func(p models.Point) { - got := p.AppendString(nil) - exp := []byte(p.String()) - - if !reflect.DeepEqual(exp, got) { - t.Errorf("AppendString() didn't match String(): got %v, exp %v", got, exp) - } - }) -} - -func testPoint_cube(t *testing.T, f func(p models.Point)) { - // heard of a table-driven test? let's make a cube-driven test... - tagList := []models.Tags{nil, {models.Tag{Key: []byte("foo"), Value: []byte("bar")}}, tags} - fieldList := []models.Fields{{"a": 42.0}, {"a": 42, "b": "things"}, fields} - timeList := []time.Time{time.Time{}, time.Unix(0, 0), time.Unix(-34526, 0), time.Unix(231845, 0), time.Now()} - - for _, tagSet := range tagList { - for _, fieldSet := range fieldList { - for _, pointTime := range timeList { - p, err := models.NewPoint("test", tagSet, fieldSet, pointTime) - if err != nil { - t.Errorf("unexpected error creating point: %v", err) - continue - } - - f(p) - } - } - } -} - -var p models.Point - -func BenchmarkNewPoint(b *testing.B) { - ts := time.Now() - for i := 0; i < b.N; i++ { - p, _ = models.NewPoint("measurement", tags, fields, ts) - } -} - -func BenchmarkParsePointNoTags5000(b *testing.B) { - var batch [5000]string - for i := 0; i < len(batch); i++ { - batch[i] = `cpu value=1i 1000000000` - } - lines := strings.Join(batch[:], "\n") - b.ResetTimer() - for i := 0; i < b.N; i++ { - models.ParsePoints([]byte(lines)) - b.SetBytes(int64(len(lines))) - } -} - -func BenchmarkParsePointNoTags(b *testing.B) { - line := `cpu value=1i 1000000000` - for i := 0; i < b.N; i++ { - models.ParsePoints([]byte(line)) - b.SetBytes(int64(len(line))) - } -} - -func BenchmarkParsePointWithPrecisionN(b *testing.B) { - line := `cpu value=1i 1000000000` - defaultTime := time.Now().UTC() - for i := 0; i < b.N; i++ { - models.ParsePointsWithPrecision([]byte(line), defaultTime, "n") - b.SetBytes(int64(len(line))) - } -} - -func BenchmarkParsePointWithPrecisionU(b *testing.B) { - line := `cpu value=1i 1000000000` - defaultTime := time.Now().UTC() - for i := 0; i < b.N; i++ { - models.ParsePointsWithPrecision([]byte(line), defaultTime, "u") - b.SetBytes(int64(len(line))) - } -} - -func BenchmarkParsePointsTagsSorted2(b *testing.B) { - line := `cpu,host=serverA,region=us-west value=1i 1000000000` - for i := 0; i < b.N; i++ { - models.ParsePoints([]byte(line)) - b.SetBytes(int64(len(line))) - } -} - -func BenchmarkParsePointsTagsSorted5(b *testing.B) { - line := `cpu,env=prod,host=serverA,region=us-west,target=servers,zone=1c value=1i 1000000000` - for i := 0; i < b.N; i++ { - models.ParsePoints([]byte(line)) - b.SetBytes(int64(len(line))) - } -} - -func BenchmarkParsePointsTagsSorted10(b *testing.B) { - line := `cpu,env=prod,host=serverA,region=us-west,tag1=value1,tag2=value2,tag3=value3,tag4=value4,tag5=value5,target=servers,zone=1c value=1i 1000000000` - for i := 0; i < b.N; i++ { - models.ParsePoints([]byte(line)) - b.SetBytes(int64(len(line))) - } -} - -func BenchmarkParsePointsTagsUnSorted2(b *testing.B) { - line := `cpu,region=us-west,host=serverA value=1i 1000000000` - for i := 0; i < b.N; i++ { - pt, _ := models.ParsePoints([]byte(line)) - b.SetBytes(int64(len(line))) - pt[0].Key() - } -} - -func BenchmarkParsePointsTagsUnSorted5(b *testing.B) { - line := `cpu,region=us-west,host=serverA,env=prod,target=servers,zone=1c value=1i 1000000000` - for i := 0; i < b.N; i++ { - pt, _ := models.ParsePoints([]byte(line)) - b.SetBytes(int64(len(line))) - pt[0].Key() - } -} - -func BenchmarkParsePointsTagsUnSorted10(b *testing.B) { - line := `cpu,region=us-west,host=serverA,env=prod,target=servers,zone=1c,tag1=value1,tag2=value2,tag3=value3,tag4=value4,tag5=value5 value=1i 1000000000` - for i := 0; i < b.N; i++ { - pt, _ := models.ParsePoints([]byte(line)) - b.SetBytes(int64(len(line))) - pt[0].Key() - } -} - -func BenchmarkParseKey(b *testing.B) { - line := `cpu,region=us-west,host=serverA,env=prod,target=servers,zone=1c,tag1=value1,tag2=value2,tag3=value3,tag4=value4,tag5=value5` - for i := 0; i < b.N; i++ { - models.ParseKey([]byte(line)) - } -} - -// TestPoint wraps a models.Point but also makes available the raw -// arguments to the Point. -// -// This is useful for ensuring that comparisons between results of -// operations on Points match the expected input data to the Point, -// since models.Point does not expose the raw input data (e.g., tags) -// via its API. -type TestPoint struct { - RawFields models.Fields - RawTags models.Tags - RawTime time.Time - models.Point -} - -// NewTestPoint returns a new TestPoint. -// -// NewTestPoint panics if it is not a valid models.Point. -func NewTestPoint(name string, tags models.Tags, fields models.Fields, time time.Time) TestPoint { - return TestPoint{ - RawTags: tags, - RawFields: fields, - RawTime: time, - Point: models.MustNewPoint(name, tags, fields, time), - } -} - -func test(t *testing.T, line string, point TestPoint) { - pts, err := models.ParsePointsWithPrecision([]byte(line), time.Unix(0, 0), "n") - if err != nil { - t.Fatalf(`ParsePoints("%s") mismatch. got %v, exp nil`, line, err) - } - - if exp := 1; len(pts) != exp { - t.Fatalf(`ParsePoints("%s") len mismatch. got %d, exp %d`, line, len(pts), exp) - } - - if exp := point.Key(); !bytes.Equal(pts[0].Key(), exp) { - t.Errorf("ParsePoints(\"%s\") key mismatch.\ngot %v\nexp %v", line, string(pts[0].Key()), string(exp)) - } - - if exp := len(point.Tags()); len(pts[0].Tags()) != exp { - t.Errorf(`ParsePoints("%s") tags mismatch. got %v, exp %v`, line, pts[0].Tags(), exp) - } - - for _, tag := range pts[0].Tags() { - if !bytes.Equal(tag.Value, point.RawTags.Get(tag.Key)) { - t.Errorf(`ParsePoints("%s") tags mismatch. got %s, exp %s`, line, tag.Value, point.RawTags.Get(tag.Key)) - } - } - - for name, value := range point.RawFields { - val := pts[0].Fields()[name] - expfval, ok := val.(float64) - - if ok && math.IsNaN(expfval) { - gotfval, ok := value.(float64) - if ok && !math.IsNaN(gotfval) { - t.Errorf(`ParsePoints("%s") field '%s' mismatch. exp NaN`, line, name) - } - } else if !reflect.DeepEqual(pts[0].Fields()[name], value) { - t.Errorf(`ParsePoints("%s") field '%s' mismatch. got %[3]v (%[3]T), exp %[4]v (%[4]T)`, line, name, pts[0].Fields()[name], value) - } - } - - if !pts[0].Time().Equal(point.Time()) { - t.Errorf(`ParsePoints("%s") time mismatch. got %v, exp %v`, line, pts[0].Time(), point.Time()) - } - - if !strings.HasPrefix(pts[0].String(), line) { - t.Errorf("ParsePoints string mismatch.\ngot: %v\nexp: %v", pts[0].String(), line) - } -} - -func TestParsePointNoValue(t *testing.T) { - pts, err := models.ParsePointsString("") - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, "", err) - } - - if exp := 0; len(pts) != exp { - t.Errorf(`ParsePoints("%s") len mismatch. got %v, exp %v`, "", len(pts), exp) - } -} - -func TestParsePointWhitespaceValue(t *testing.T) { - pts, err := models.ParsePointsString(" ") - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, "", err) - } - - if exp := 0; len(pts) != exp { - t.Errorf(`ParsePoints("%s") len mismatch. got %v, exp %v`, "", len(pts), exp) - } -} - -func TestParsePointNoFields(t *testing.T) { - expectedSuffix := "missing fields" - examples := []string{ - "cpu_load_short,host=server01,region=us-west", - "cpu", - "cpu,host==", - "=", - } - - for i, example := range examples { - _, err := models.ParsePointsString(example) - if err == nil { - t.Errorf(`[Example %d] ParsePoints("%s") mismatch. got nil, exp error`, i, example) - } else if !strings.HasSuffix(err.Error(), expectedSuffix) { - t.Errorf(`[Example %d] ParsePoints("%s") mismatch. got %q, exp suffix %q`, i, example, err, expectedSuffix) - } - } -} - -func TestParsePointNoTimestamp(t *testing.T) { - test(t, "cpu value=1", NewTestPoint("cpu", nil, models.Fields{"value": 1.0}, time.Unix(0, 0))) -} - -func TestParsePointMissingQuote(t *testing.T) { - expectedSuffix := "unbalanced quotes" - examples := []string{ - `cpu,host=serverA value="test`, - `cpu,host=serverA value="test""`, - } - - for i, example := range examples { - _, err := models.ParsePointsString(example) - if err == nil { - t.Errorf(`[Example %d] ParsePoints("%s") mismatch. got nil, exp error`, i, example) - } else if !strings.HasSuffix(err.Error(), expectedSuffix) { - t.Errorf(`[Example %d] ParsePoints("%s") mismatch. got %q, exp suffix %q`, i, example, err, expectedSuffix) - } - } -} - -func TestParsePointMissingTagKey(t *testing.T) { - expectedSuffix := "missing tag key" - examples := []string{ - `cpu, value=1`, - `cpu,`, - `cpu,,,`, - `cpu,host=serverA,=us-east value=1i`, - `cpu,host=serverAa\,,=us-east value=1i`, - `cpu,host=serverA\,,=us-east value=1i`, - `cpu, =serverA value=1i`, - } - - for i, example := range examples { - _, err := models.ParsePointsString(example) - if err == nil { - t.Errorf(`[Example %d] ParsePoints("%s") mismatch. got nil, exp error`, i, example) - } else if !strings.HasSuffix(err.Error(), expectedSuffix) { - t.Errorf(`[Example %d] ParsePoints("%s") mismatch. got %q, exp suffix %q`, i, example, err, expectedSuffix) - } - } - - _, err := models.ParsePointsString(`cpu,host=serverA,\ =us-east value=1i`) - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,\ =us-east value=1i`, err) - } -} - -func TestParsePointMissingTagValue(t *testing.T) { - expectedSuffix := "missing tag value" - examples := []string{ - `cpu,host`, - `cpu,host,`, - `cpu,host=`, - `cpu,host value=1i`, - `cpu,host=serverA,region value=1i`, - `cpu,host=serverA,region= value=1i`, - `cpu,host=serverA,region=,zone=us-west value=1i`, - } - - for i, example := range examples { - _, err := models.ParsePointsString(example) - if err == nil { - t.Errorf(`[Example %d] ParsePoints("%s") mismatch. got nil, exp error`, i, example) - } else if !strings.HasSuffix(err.Error(), expectedSuffix) { - t.Errorf(`[Example %d] ParsePoints("%s") mismatch. got %q, exp suffix %q`, i, example, err, expectedSuffix) - } - } -} - -func TestParsePointInvalidTagFormat(t *testing.T) { - expectedSuffix := "invalid tag format" - examples := []string{ - `cpu,host=f=o,`, - `cpu,host=f\==o,`, - } - - for i, example := range examples { - _, err := models.ParsePointsString(example) - if err == nil { - t.Errorf(`[Example %d] ParsePoints("%s") mismatch. got nil, exp error`, i, example) - } else if !strings.HasSuffix(err.Error(), expectedSuffix) { - t.Errorf(`[Example %d] ParsePoints("%s") mismatch. got %q, exp suffix %q`, i, example, err, expectedSuffix) - } - } -} - -func TestParsePointMissingFieldName(t *testing.T) { - _, err := models.ParsePointsString(`cpu,host=serverA,region=us-west =`) - if err == nil { - t.Errorf(`ParsePoints("%s") mismatch. got nil, exp error`, `cpu,host=serverA,region=us-west =`) - } - - _, err = models.ParsePointsString(`cpu,host=serverA,region=us-west =123i`) - if err == nil { - t.Errorf(`ParsePoints("%s") mismatch. got nil, exp error`, `cpu,host=serverA,region=us-west =123i`) - } - - _, err = models.ParsePointsString(`cpu,host=serverA,region=us-west a\ =123i`) - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got nil, exp error`, `cpu,host=serverA,region=us-west a\ =123i`) - } - _, err = models.ParsePointsString(`cpu,host=serverA,region=us-west value=123i,=456i`) - if err == nil { - t.Errorf(`ParsePoints("%s") mismatch. got nil, exp error`, `cpu,host=serverA,region=us-west value=123i,=456i`) - } -} - -func TestParsePointMissingFieldValue(t *testing.T) { - _, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=`) - if err == nil { - t.Errorf(`ParsePoints("%s") mismatch. got nil, exp error`, `cpu,host=serverA,region=us-west value=`) - } - - _, err = models.ParsePointsString(`cpu,host=serverA,region=us-west value= 1000000000i`) - if err == nil { - t.Errorf(`ParsePoints("%s") mismatch. got nil, exp error`, `cpu,host=serverA,region=us-west value= 1000000000i`) - } - - _, err = models.ParsePointsString(`cpu,host=serverA,region=us-west value=,value2=1i`) - if err == nil { - t.Errorf(`ParsePoints("%s") mismatch. got nil, exp error`, `cpu,host=serverA,region=us-west value=,value2=1i`) - } - - _, err = models.ParsePointsString(`cpu,host=server01,region=us-west 1434055562000000000i`) - if err == nil { - t.Errorf(`ParsePoints("%s") mismatch. got nil, exp error`, `cpu,host=server01,region=us-west 1434055562000000000i`) - } - - _, err = models.ParsePointsString(`cpu,host=server01,region=us-west value=1i,b`) - if err == nil { - t.Errorf(`ParsePoints("%s") mismatch. got nil, exp error`, `cpu,host=server01,region=us-west value=1i,b`) - } -} - -func TestParsePointBadNumber(t *testing.T) { - for _, tt := range []string{ - "cpu v=- ", - "cpu v=-i ", - "cpu v=-. ", - "cpu v=. ", - "cpu v=1.0i ", - "cpu v=1ii ", - "cpu v=1a ", - "cpu v=-e-e-e ", - "cpu v=42+3 ", - "cpu v= ", - } { - _, err := models.ParsePointsString(tt) - if err == nil { - t.Errorf("Point %q should be invalid", tt) - } - } -} - -func TestParsePointMaxInt64(t *testing.T) { - // out of range - _, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=9223372036854775808i`) - exp := `unable to parse 'cpu,host=serverA,region=us-west value=9223372036854775808i': unable to parse integer 9223372036854775808: strconv.ParseInt: parsing "9223372036854775808": value out of range` - if err == nil || (err != nil && err.Error() != exp) { - t.Fatalf("Error mismatch:\nexp: %s\ngot: %v", exp, err) - } - - // max int - p, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=9223372036854775807i`) - if err != nil { - t.Fatalf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=9223372036854775807i`, err) - } - if exp, got := int64(9223372036854775807), p[0].Fields()["value"].(int64); exp != got { - t.Fatalf("ParsePoints Value mismatch. \nexp: %v\ngot: %v", exp, got) - } - - // leading zeros - _, err = models.ParsePointsString(`cpu,host=serverA,region=us-west value=0009223372036854775807i`) - if err != nil { - t.Fatalf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=0009223372036854775807i`, err) - } -} - -func TestParsePointMinInt64(t *testing.T) { - // out of range - _, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=-9223372036854775809i`) - if err == nil { - t.Errorf(`ParsePoints("%s") mismatch. got nil, exp error`, `cpu,host=serverA,region=us-west value=-9223372036854775809i`) - } - - // min int - _, err = models.ParsePointsString(`cpu,host=serverA,region=us-west value=-9223372036854775808i`) - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=-9223372036854775808i`, err) - } - - // leading zeros - _, err = models.ParsePointsString(`cpu,host=serverA,region=us-west value=-0009223372036854775808i`) - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=-0009223372036854775808i`, err) - } -} - -func TestParsePointMaxFloat64(t *testing.T) { - // out of range - _, err := models.ParsePointsString(fmt.Sprintf(`cpu,host=serverA,region=us-west value=%s`, "1"+string(maxFloat64))) - if err == nil { - t.Errorf(`ParsePoints("%s") mismatch. got nil, exp error`, `cpu,host=serverA,region=us-west value=...`) - } - - // max float - _, err = models.ParsePointsString(fmt.Sprintf(`cpu,host=serverA,region=us-west value=%s`, string(maxFloat64))) - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=9223372036854775807`, err) - } - - // leading zeros - _, err = models.ParsePointsString(fmt.Sprintf(`cpu,host=serverA,region=us-west value=%s`, "0000"+string(maxFloat64))) - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=0009223372036854775807`, err) - } -} - -func TestParsePointMinFloat64(t *testing.T) { - // out of range - _, err := models.ParsePointsString(fmt.Sprintf(`cpu,host=serverA,region=us-west value=%s`, "-1"+string(minFloat64)[1:])) - if err == nil { - t.Errorf(`ParsePoints("%s") mismatch. got nil, exp error`, `cpu,host=serverA,region=us-west value=...`) - } - - // min float - _, err = models.ParsePointsString(fmt.Sprintf(`cpu,host=serverA,region=us-west value=%s`, string(minFloat64))) - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=...`, err) - } - - // leading zeros - _, err = models.ParsePointsString(fmt.Sprintf(`cpu,host=serverA,region=us-west value=%s`, "-0000000"+string(minFloat64)[1:])) - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=...`, err) - } -} - -func TestParsePointNumberNonNumeric(t *testing.T) { - _, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=.1a`) - if err == nil { - t.Errorf(`ParsePoints("%s") mismatch. got nil, exp error`, `cpu,host=serverA,region=us-west value=.1a`) - } -} - -func TestParsePointNegativeWrongPlace(t *testing.T) { - _, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=0.-1`) - if err == nil { - t.Errorf(`ParsePoints("%s") mismatch. got nil, exp error`, `cpu,host=serverA,region=us-west value=0.-1`) - } -} - -func TestParsePointOnlyNegativeSign(t *testing.T) { - _, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=-`) - if err == nil { - t.Errorf(`ParsePoints("%s") mismatch. got nil, exp error`, `cpu,host=serverA,region=us-west value=-`) - } -} - -func TestParsePointFloatMultipleDecimals(t *testing.T) { - _, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=1.1.1`) - if err == nil { - t.Errorf(`ParsePoints("%s") mismatch. got nil, exp error`, `cpu,host=serverA,region=us-west value=1.1.1`) - } -} - -func TestParsePointInteger(t *testing.T) { - _, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=1i`) - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=1i`, err) - } -} - -func TestParsePointNegativeInteger(t *testing.T) { - _, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=-1i`) - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=-1i`, err) - } -} - -func TestParsePointNegativeFloat(t *testing.T) { - _, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=-1.0`) - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=-1.0`, err) - } -} - -func TestParsePointFloatNoLeadingDigit(t *testing.T) { - _, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=.1`) - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=-1.0`, err) - } -} - -func TestParsePointFloatScientific(t *testing.T) { - _, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=1.0e4`) - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=1.0e4`, err) - } - - pts, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=1e4`) - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=1.0e4`, err) - } - - if pts[0].Fields()["value"] != 1e4 { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=1e4`, err) - } -} - -func TestParsePointFloatScientificUpper(t *testing.T) { - _, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=1.0E4`) - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=1.0E4`, err) - } - - pts, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=1E4`) - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=1.0E4`, err) - } - - if pts[0].Fields()["value"] != 1e4 { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=1E4`, err) - } -} - -func TestParsePointFloatScientificDecimal(t *testing.T) { - _, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=1.0e-4`) - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=1.0e-4`, err) - } -} - -func TestParsePointFloatNegativeScientific(t *testing.T) { - _, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=-1.0e-4`) - if err != nil { - t.Errorf(`ParsePoints("%s") mismatch. got %v, exp nil`, `cpu,host=serverA,region=us-west value=-1.0e-4`, err) - } -} - -func TestParsePointBooleanInvalid(t *testing.T) { - _, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=a`) - if err == nil { - t.Errorf(`ParsePoints("%s") mismatch. got nil, exp error`, `cpu,host=serverA,region=us-west value=a`) - } -} - -func TestParsePointScientificIntInvalid(t *testing.T) { - _, err := models.ParsePointsString(`cpu,host=serverA,region=us-west value=9ie10`) - if err == nil { - t.Errorf(`ParsePoints("%s") mismatch. got nil, exp error`, `cpu,host=serverA,region=us-west value=9ie10`) - } - - _, err = models.ParsePointsString(`cpu,host=serverA,region=us-west value=9e10i`) - if err == nil { - t.Errorf(`ParsePoints("%s") mismatch. got nil, exp error`, `cpu,host=serverA,region=us-west value=9e10i`) - } -} - -func TestParsePointWhitespace(t *testing.T) { - examples := []string{ - `cpu value=1.0 1257894000000000000`, - `cpu value=1.0 1257894000000000000`, - `cpu value=1.0 1257894000000000000`, - `cpu value=1.0 1257894000000000000 `, - `cpu value=1.0 1257894000000000000 -`, - `cpu value=1.0 1257894000000000000 -`, - } - - expPoint := NewTestPoint("cpu", models.Tags{}, models.Fields{"value": 1.0}, time.Unix(0, 1257894000000000000)) - for i, example := range examples { - pts, err := models.ParsePoints([]byte(example)) - if err != nil { - t.Fatalf(`[Example %d] ParsePoints("%s") error. got %v, exp nil`, i, example, err) - } - - if got, exp := len(pts), 1; got != exp { - t.Fatalf("[Example %d] got %d points, expected %d", i, got, exp) - } - - if got, exp := pts[0].Name(), expPoint.Name(); got != exp { - t.Fatalf("[Example %d] got %v measurement, expected %v", i, got, exp) - } - - if got, exp := len(pts[0].Fields()), len(expPoint.Fields()); got != exp { - t.Fatalf("[Example %d] got %d fields, expected %d", i, got, exp) - } - - if got, exp := pts[0].Fields()["value"], expPoint.Fields()["value"]; got != exp { - t.Fatalf(`[Example %d] got %v for field "value", expected %v`, i, got, exp) - } - - if got, exp := pts[0].Time().UnixNano(), expPoint.Time().UnixNano(); got != exp { - t.Fatalf(`[Example %d] got %d time, expected %d`, i, got, exp) - } - } -} - -func TestParsePointUnescape(t *testing.T) { - // commas in measurement name - test(t, `foo\,bar value=1i`, - NewTestPoint( - "foo,bar", // comma in the name - models.NewTags(map[string]string{}), - models.Fields{ - "value": int64(1), - }, - time.Unix(0, 0))) - - // comma in measurement name with tags - test(t, `cpu\,main,regions=east value=1.0`, - NewTestPoint( - "cpu,main", // comma in the name - models.NewTags(map[string]string{ - "regions": "east", - }), - models.Fields{ - "value": 1.0, - }, - time.Unix(0, 0))) - - // spaces in measurement name - test(t, `cpu\ load,region=east value=1.0`, - NewTestPoint( - "cpu load", // space in the name - models.NewTags(map[string]string{ - "region": "east", - }), - models.Fields{ - "value": 1.0, - }, - time.Unix(0, 0))) - - // equals in measurement name - test(t, `cpu\=load,region=east value=1.0`, - NewTestPoint( - `cpu\=load`, // backslash is literal - models.NewTags(map[string]string{ - "region": "east", - }), - models.Fields{ - "value": 1.0, - }, - time.Unix(0, 0))) - - // equals in measurement name - test(t, `cpu=load,region=east value=1.0`, - NewTestPoint( - `cpu=load`, // literal equals is fine in measurement name - models.NewTags(map[string]string{ - "region": "east", - }), - models.Fields{ - "value": 1.0, - }, - time.Unix(0, 0))) - - // commas in tag names - test(t, `cpu,region\,zone=east value=1.0`, - NewTestPoint("cpu", - models.NewTags(map[string]string{ - "region,zone": "east", // comma in the tag key - }), - models.Fields{ - "value": 1.0, - }, - time.Unix(0, 0))) - - // spaces in tag name - test(t, `cpu,region\ zone=east value=1.0`, - NewTestPoint("cpu", - models.NewTags(map[string]string{ - "region zone": "east", // space in the tag name - }), - models.Fields{ - "value": 1.0, - }, - time.Unix(0, 0))) - - // backslash with escaped equals in tag name - test(t, `cpu,reg\\=ion=east value=1.0`, - NewTestPoint("cpu", - models.NewTags(map[string]string{ - `reg\=ion`: "east", - }), - models.Fields{ - "value": 1.0, - }, - time.Unix(0, 0))) - - // space is tag name - test(t, `cpu,\ =east value=1.0`, - NewTestPoint("cpu", - models.NewTags(map[string]string{ - " ": "east", // tag name is single space - }), - models.Fields{ - "value": 1.0, - }, - time.Unix(0, 0))) - - // commas in tag values - test(t, `cpu,regions=east\,west value=1.0`, - NewTestPoint("cpu", - models.NewTags(map[string]string{ - "regions": "east,west", // comma in the tag value - }), - models.Fields{ - "value": 1.0, - }, - time.Unix(0, 0))) - - // backslash literal followed by escaped space - test(t, `cpu,regions=\\ east value=1.0`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{ - "regions": `\ east`, - }), - models.Fields{ - "value": 1.0, - }, - time.Unix(0, 0))) - - // backslash literal followed by escaped space - test(t, `cpu,regions=eas\\ t value=1.0`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{ - "regions": `eas\ t`, - }), - models.Fields{ - "value": 1.0, - }, - time.Unix(0, 0))) - - // backslash literal followed by trailing space - test(t, `cpu,regions=east\\ value=1.0`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{ - "regions": `east\ `, - }), - models.Fields{ - "value": 1.0, - }, - time.Unix(0, 0))) - - // spaces in tag values - test(t, `cpu,regions=east\ west value=1.0`, - NewTestPoint("cpu", - models.NewTags(map[string]string{ - "regions": "east west", // comma in the tag value - }), - models.Fields{ - "value": 1.0, - }, - time.Unix(0, 0))) - - // commas in field keys - test(t, `cpu,regions=east value\,ms=1.0`, - NewTestPoint("cpu", - models.NewTags(map[string]string{ - "regions": "east", - }), - models.Fields{ - "value,ms": 1.0, // comma in the field keys - }, - time.Unix(0, 0))) - - // spaces in field keys - test(t, `cpu,regions=east value\ ms=1.0`, - NewTestPoint("cpu", - models.NewTags(map[string]string{ - "regions": "east", - }), - models.Fields{ - "value ms": 1.0, // comma in the field keys - }, - time.Unix(0, 0))) - - // tag with no value - test(t, `cpu,regions=east value="1"`, - NewTestPoint("cpu", - models.NewTags(map[string]string{ - "regions": "east", - "foobar": "", - }), - models.Fields{ - "value": "1", - }, - time.Unix(0, 0))) - - // commas in field values - test(t, `cpu,regions=east value="1,0"`, - NewTestPoint("cpu", - models.NewTags(map[string]string{ - "regions": "east", - }), - models.Fields{ - "value": "1,0", // comma in the field value - }, - time.Unix(0, 0))) - - // random character escaped - test(t, `cpu,regions=eas\t value=1.0`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{ - "regions": "eas\\t", - }), - models.Fields{ - "value": 1.0, - }, - time.Unix(0, 0))) - - // backslash literal followed by escaped characters - test(t, `cpu,regions=\\,\,\=east value=1.0`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{ - "regions": `\,,=east`, - }), - models.Fields{ - "value": 1.0, - }, - time.Unix(0, 0))) - - // field keys using escape char. - test(t, `cpu \a=1i`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{}), - models.Fields{ - "\\a": int64(1), // Left as parsed since it's not a known escape sequence. - }, - time.Unix(0, 0))) - - // measurement, tag and tag value with equals - test(t, `cpu=load,equals\=foo=tag\=value value=1i`, - NewTestPoint( - "cpu=load", // Not escaped - models.NewTags(map[string]string{ - "equals=foo": "tag=value", // Tag and value unescaped - }), - models.Fields{ - "value": int64(1), - }, - time.Unix(0, 0))) - -} - -func TestParsePointWithTags(t *testing.T) { - test(t, - "cpu,host=serverA,region=us-east value=1.0 1000000000", - NewTestPoint("cpu", - models.NewTags(map[string]string{"host": "serverA", "region": "us-east"}), - models.Fields{"value": 1.0}, time.Unix(1, 0))) -} - -func TestParsePointWithDuplicateTags(t *testing.T) { - for i, tt := range []struct { - line string - err string - }{ - { - line: `cpu,host=serverA,host=serverB value=1i 1000000000`, - err: `unable to parse 'cpu,host=serverA,host=serverB value=1i 1000000000': duplicate tags`, - }, - { - line: `cpu,b=2,b=1,c=3 value=1i 1000000000`, - err: `unable to parse 'cpu,b=2,b=1,c=3 value=1i 1000000000': duplicate tags`, - }, - { - line: `cpu,b=2,c=3,b=1 value=1i 1000000000`, - err: `unable to parse 'cpu,b=2,c=3,b=1 value=1i 1000000000': duplicate tags`, - }, - } { - _, err := models.ParsePointsString(tt.line) - if err == nil || tt.err != err.Error() { - t.Errorf("%d. ParsePoint() expected error '%s'. got '%s'", i, tt.err, err) - } - } -} - -func TestParsePointWithStringField(t *testing.T) { - test(t, `cpu,host=serverA,region=us-east value=1.0,str="foo",str2="bar" 1000000000`, - NewTestPoint("cpu", - models.NewTags(map[string]string{ - "host": "serverA", - "region": "us-east", - }), - models.Fields{ - "value": 1.0, - "str": "foo", - "str2": "bar", - }, - time.Unix(1, 0)), - ) - - test(t, `cpu,host=serverA,region=us-east str="foo \" bar" 1000000000`, - NewTestPoint("cpu", - models.NewTags(map[string]string{ - "host": "serverA", - "region": "us-east", - }), - models.Fields{ - "str": `foo " bar`, - }, - time.Unix(1, 0)), - ) - -} - -func TestParsePointWithStringWithSpaces(t *testing.T) { - test(t, `cpu,host=serverA,region=us-east value=1.0,str="foo bar" 1000000000`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{ - "host": "serverA", - "region": "us-east", - }), - models.Fields{ - "value": 1.0, - "str": "foo bar", // spaces in string value - }, - time.Unix(1, 0)), - ) -} - -func TestParsePointWithStringWithNewline(t *testing.T) { - test(t, "cpu,host=serverA,region=us-east value=1.0,str=\"foo\nbar\" 1000000000", - NewTestPoint( - "cpu", - models.NewTags(map[string]string{ - "host": "serverA", - "region": "us-east", - }), - models.Fields{ - "value": 1.0, - "str": "foo\nbar", // newline in string value - }, - time.Unix(1, 0)), - ) -} - -func TestParsePointWithStringWithCommas(t *testing.T) { - // escaped comma - test(t, `cpu,host=serverA,region=us-east value=1.0,str="foo\,bar" 1000000000`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{ - "host": "serverA", - "region": "us-east", - }), - models.Fields{ - "value": 1.0, - "str": `foo\,bar`, // commas in string value - }, - time.Unix(1, 0)), - ) - - // non-escaped comma - test(t, `cpu,host=serverA,region=us-east value=1.0,str="foo,bar" 1000000000`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{ - "host": "serverA", - "region": "us-east", - }), - models.Fields{ - "value": 1.0, - "str": "foo,bar", // commas in string value - }, - time.Unix(1, 0)), - ) - - // string w/ trailing escape chars - test(t, `cpu,host=serverA,region=us-east str="foo\\",str2="bar" 1000000000`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{ - "host": "serverA", - "region": "us-east", - }), - models.Fields{ - "str": "foo\\", // trailing escape char - "str2": "bar", - }, - time.Unix(1, 0)), - ) -} - -func TestParsePointQuotedMeasurement(t *testing.T) { - // non-escaped comma - test(t, `"cpu",host=serverA,region=us-east value=1.0 1000000000`, - NewTestPoint( - `"cpu"`, - models.NewTags(map[string]string{ - "host": "serverA", - "region": "us-east", - }), - models.Fields{ - "value": 1.0, - }, - time.Unix(1, 0)), - ) -} - -func TestParsePointQuotedTags(t *testing.T) { - test(t, `cpu,"host"="serverA",region=us-east value=1.0 1000000000`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{ - `"host"`: `"serverA"`, - "region": "us-east", - }), - models.Fields{ - "value": 1.0, - }, - time.Unix(1, 0)), - ) -} - -func TestParsePointsUnbalancedQuotedTags(t *testing.T) { - pts, err := models.ParsePointsString("baz,mytag=\"a x=1 1441103862125\nbaz,mytag=a z=1 1441103862126") - if err != nil { - t.Fatalf("ParsePoints failed: %v", err) - } - - if exp := 2; len(pts) != exp { - t.Fatalf("ParsePoints count mismatch. got %v, exp %v", len(pts), exp) - } - - // Expected " in the tag value - exp := models.MustNewPoint("baz", models.NewTags(map[string]string{"mytag": `"a`}), - models.Fields{"x": float64(1)}, time.Unix(0, 1441103862125)) - - if pts[0].String() != exp.String() { - t.Errorf("Point mismatch:\ngot: %v\nexp: %v", pts[0].String(), exp.String()) - } - - // Expected two points to ensure we did not overscan the line - exp = models.MustNewPoint("baz", models.NewTags(map[string]string{"mytag": `a`}), - models.Fields{"z": float64(1)}, time.Unix(0, 1441103862126)) - - if pts[1].String() != exp.String() { - t.Errorf("Point mismatch:\ngot: %v\nexp: %v", pts[1].String(), exp.String()) - } - -} - -func TestParsePointEscapedStringsAndCommas(t *testing.T) { - // non-escaped comma and quotes - test(t, `cpu,host=serverA,region=us-east value="{Hello\"{,}\" World}" 1000000000`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{ - "host": "serverA", - "region": "us-east", - }), - models.Fields{ - "value": `{Hello"{,}" World}`, - }, - time.Unix(1, 0)), - ) - - // escaped comma and quotes - test(t, `cpu,host=serverA,region=us-east value="{Hello\"{\,}\" World}" 1000000000`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{ - "host": "serverA", - "region": "us-east", - }), - models.Fields{ - "value": `{Hello"{\,}" World}`, - }, - time.Unix(1, 0)), - ) -} - -func TestParsePointWithStringWithEquals(t *testing.T) { - test(t, `cpu,host=serverA,region=us-east str="foo=bar",value=1.0 1000000000`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{ - "host": "serverA", - "region": "us-east", - }), - models.Fields{ - "value": 1.0, - "str": "foo=bar", // spaces in string value - }, - time.Unix(1, 0)), - ) -} - -func TestParsePointWithStringWithBackslash(t *testing.T) { - test(t, `cpu value="test\\\"" 1000000000`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{}), - models.Fields{ - "value": `test\"`, - }, - time.Unix(1, 0)), - ) - - test(t, `cpu value="test\\" 1000000000`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{}), - models.Fields{ - "value": `test\`, - }, - time.Unix(1, 0)), - ) - - test(t, `cpu value="test\\\"" 1000000000`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{}), - models.Fields{ - "value": `test\"`, - }, - time.Unix(1, 0)), - ) - - test(t, `cpu value="test\"" 1000000000`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{}), - models.Fields{ - "value": `test"`, - }, - time.Unix(1, 0)), - ) -} - -func TestParsePointWithBoolField(t *testing.T) { - test(t, `cpu,host=serverA,region=us-east true=true,t=t,T=T,TRUE=TRUE,True=True,false=false,f=f,F=F,FALSE=FALSE,False=False 1000000000`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{ - "host": "serverA", - "region": "us-east", - }), - models.Fields{ - "t": true, - "T": true, - "true": true, - "True": true, - "TRUE": true, - "f": false, - "F": false, - "false": false, - "False": false, - "FALSE": false, - }, - time.Unix(1, 0)), - ) -} - -func TestParsePointUnicodeString(t *testing.T) { - test(t, `cpu,host=serverA,region=us-east value="wè" 1000000000`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{ - "host": "serverA", - "region": "us-east", - }), - models.Fields{ - "value": "wè", - }, - time.Unix(1, 0)), - ) -} - -func TestParsePointNegativeTimestamp(t *testing.T) { - test(t, `cpu value=1 -1`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{}), - models.Fields{ - "value": 1.0, - }, - time.Unix(0, -1)), - ) -} - -func TestParsePointMaxTimestamp(t *testing.T) { - test(t, fmt.Sprintf(`cpu value=1 %d`, models.MaxNanoTime), - NewTestPoint( - "cpu", - models.NewTags(map[string]string{}), - models.Fields{ - "value": 1.0, - }, - time.Unix(0, models.MaxNanoTime)), - ) -} - -func TestParsePointMinTimestamp(t *testing.T) { - test(t, `cpu value=1 -9223372036854775806`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{}), - models.Fields{ - "value": 1.0, - }, - time.Unix(0, models.MinNanoTime)), - ) -} - -func TestParsePointInvalidTimestamp(t *testing.T) { - examples := []string{ - "cpu value=1 9223372036854775808", - "cpu value=1 -92233720368547758078", - "cpu value=1 -", - "cpu value=1 -/", - "cpu value=1 -1?", - "cpu value=1 1-", - "cpu value=1 9223372036854775807 12", - } - - for i, example := range examples { - _, err := models.ParsePointsString(example) - if err == nil { - t.Fatalf("[Example %d] ParsePoints failed: %v", i, err) - } - } -} - -func TestNewPointFloatWithoutDecimal(t *testing.T) { - test(t, `cpu value=1 1000000000`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{}), - models.Fields{ - "value": 1.0, - }, - time.Unix(1, 0)), - ) -} -func TestNewPointNegativeFloat(t *testing.T) { - test(t, `cpu value=-0.64 1000000000`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{}), - models.Fields{ - "value": -0.64, - }, - time.Unix(1, 0)), - ) -} - -func TestNewPointFloatNoDecimal(t *testing.T) { - test(t, `cpu value=1. 1000000000`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{}), - models.Fields{ - "value": 1.0, - }, - time.Unix(1, 0)), - ) -} - -func TestNewPointFloatScientific(t *testing.T) { - test(t, `cpu value=6.632243e+06 1000000000`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{}), - models.Fields{ - "value": float64(6632243), - }, - time.Unix(1, 0)), - ) -} - -func TestNewPointLargeInteger(t *testing.T) { - test(t, `cpu value=6632243i 1000000000`, - NewTestPoint( - "cpu", - models.NewTags(map[string]string{}), - models.Fields{ - "value": int64(6632243), // if incorrectly encoded as a float, it would show up as 6.632243e+06 - }, - time.Unix(1, 0)), - ) -} - -func TestParsePointNaN(t *testing.T) { - _, err := models.ParsePointsString("cpu value=NaN 1000000000") - if err == nil { - t.Fatalf("ParsePoints expected error, got nil") - } - - _, err = models.ParsePointsString("cpu value=nAn 1000000000") - if err == nil { - t.Fatalf("ParsePoints expected error, got nil") - } - - _, err = models.ParsePointsString("cpu value=NaN") - if err == nil { - t.Fatalf("ParsePoints expected error, got nil") - } -} - -func TestNewPointLargeNumberOfTags(t *testing.T) { - tags := "" - for i := 0; i < 255; i++ { - tags += fmt.Sprintf(",tag%d=value%d", i, i) - } - - pt, err := models.ParsePointsString(fmt.Sprintf("cpu%s value=1", tags)) - if err != nil { - t.Fatalf("ParsePoints() with max tags failed: %v", err) - } - - if len(pt[0].Tags()) != 255 { - t.Fatalf("expected %d tags, got %d", 255, len(pt[0].Tags())) - } -} - -func TestParsePointIntsFloats(t *testing.T) { - pts, err := models.ParsePoints([]byte(`cpu,host=serverA,region=us-east int=10i,float=11.0,float2=12.1 1000000000`)) - if err != nil { - t.Fatalf(`ParsePoints() failed. got %s`, err) - } - - if exp := 1; len(pts) != exp { - t.Errorf("ParsePoint() len mismatch: got %v, exp %v", len(pts), exp) - } - pt := pts[0] - - if _, ok := pt.Fields()["int"].(int64); !ok { - t.Errorf("ParsePoint() int field mismatch: got %T, exp %T", pt.Fields()["int"], int64(10)) - } - - if _, ok := pt.Fields()["float"].(float64); !ok { - t.Errorf("ParsePoint() float field mismatch: got %T, exp %T", pt.Fields()["float64"], float64(11.0)) - } - - if _, ok := pt.Fields()["float2"].(float64); !ok { - t.Errorf("ParsePoint() float field mismatch: got %T, exp %T", pt.Fields()["float64"], float64(12.1)) - } -} - -func TestParsePointKeyUnsorted(t *testing.T) { - pts, err := models.ParsePoints([]byte("cpu,last=1,first=2 value=1i")) - if err != nil { - t.Fatalf(`ParsePoints() failed. got %s`, err) - } - - if exp := 1; len(pts) != exp { - t.Errorf("ParsePoint() len mismatch: got %v, exp %v", len(pts), exp) - } - pt := pts[0] - - if exp := "cpu,first=2,last=1"; string(pt.Key()) != exp { - t.Errorf("ParsePoint key not sorted. got %v, exp %v", string(pt.Key()), exp) - } -} - -func TestParsePointToString(t *testing.T) { - line := `cpu,host=serverA,region=us-east bool=false,float=11,float2=12.123,int=10i,str="string val" 1000000000` - pts, err := models.ParsePoints([]byte(line)) - if err != nil { - t.Fatalf(`ParsePoints() failed. got %s`, err) - } - if exp := 1; len(pts) != exp { - t.Errorf("ParsePoint() len mismatch: got %v, exp %v", len(pts), exp) - } - pt := pts[0] - - got := pt.String() - if line != got { - t.Errorf("ParsePoint() to string mismatch:\n got %v\n exp %v", got, line) - } - - pt = models.MustNewPoint("cpu", models.NewTags(map[string]string{"host": "serverA", "region": "us-east"}), - models.Fields{"int": 10, "float": float64(11.0), "float2": float64(12.123), "bool": false, "str": "string val"}, - time.Unix(1, 0)) - - got = pt.String() - if line != got { - t.Errorf("NewPoint() to string mismatch:\n got %v\n exp %v", got, line) - } -} - -func TestParsePointsWithPrecision(t *testing.T) { - tests := []struct { - name string - line string - precision string - exp string - }{ - { - name: "nanosecond by default", - line: `cpu,host=serverA,region=us-east value=1.0 946730096789012345`, - precision: "", - exp: "cpu,host=serverA,region=us-east value=1.0 946730096789012345", - }, - { - name: "nanosecond", - line: `cpu,host=serverA,region=us-east value=1.0 946730096789012345`, - precision: "n", - exp: "cpu,host=serverA,region=us-east value=1.0 946730096789012345", - }, - { - name: "microsecond", - line: `cpu,host=serverA,region=us-east value=1.0 946730096789012`, - precision: "u", - exp: "cpu,host=serverA,region=us-east value=1.0 946730096789012000", - }, - { - name: "millisecond", - line: `cpu,host=serverA,region=us-east value=1.0 946730096789`, - precision: "ms", - exp: "cpu,host=serverA,region=us-east value=1.0 946730096789000000", - }, - { - name: "second", - line: `cpu,host=serverA,region=us-east value=1.0 946730096`, - precision: "s", - exp: "cpu,host=serverA,region=us-east value=1.0 946730096000000000", - }, - { - name: "minute", - line: `cpu,host=serverA,region=us-east value=1.0 15778834`, - precision: "m", - exp: "cpu,host=serverA,region=us-east value=1.0 946730040000000000", - }, - { - name: "hour", - line: `cpu,host=serverA,region=us-east value=1.0 262980`, - precision: "h", - exp: "cpu,host=serverA,region=us-east value=1.0 946728000000000000", - }, - } - for _, test := range tests { - pts, err := models.ParsePointsWithPrecision([]byte(test.line), time.Now().UTC(), test.precision) - if err != nil { - t.Fatalf(`%s: ParsePoints() failed. got %s`, test.name, err) - } - if exp := 1; len(pts) != exp { - t.Errorf("%s: ParsePoint() len mismatch: got %v, exp %v", test.name, len(pts), exp) - } - pt := pts[0] - - got := pt.String() - if got != test.exp { - t.Errorf("%s: ParsePoint() to string mismatch:\n got %v\n exp %v", test.name, got, test.exp) - } - } -} - -func TestParsePointsWithPrecisionNoTime(t *testing.T) { - line := `cpu,host=serverA,region=us-east value=1.0` - tm, _ := time.Parse(time.RFC3339Nano, "2000-01-01T12:34:56.789012345Z") - tests := []struct { - name string - precision string - exp string - }{ - { - name: "no precision", - precision: "", - exp: "cpu,host=serverA,region=us-east value=1.0 946730096789012345", - }, - { - name: "nanosecond precision", - precision: "n", - exp: "cpu,host=serverA,region=us-east value=1.0 946730096789012345", - }, - { - name: "microsecond precision", - precision: "u", - exp: "cpu,host=serverA,region=us-east value=1.0 946730096789012000", - }, - { - name: "millisecond precision", - precision: "ms", - exp: "cpu,host=serverA,region=us-east value=1.0 946730096789000000", - }, - { - name: "second precision", - precision: "s", - exp: "cpu,host=serverA,region=us-east value=1.0 946730096000000000", - }, - { - name: "minute precision", - precision: "m", - exp: "cpu,host=serverA,region=us-east value=1.0 946730040000000000", - }, - { - name: "hour precision", - precision: "h", - exp: "cpu,host=serverA,region=us-east value=1.0 946728000000000000", - }, - } - - for _, test := range tests { - pts, err := models.ParsePointsWithPrecision([]byte(line), tm, test.precision) - if err != nil { - t.Fatalf(`%s: ParsePoints() failed. got %s`, test.name, err) - } - if exp := 1; len(pts) != exp { - t.Errorf("%s: ParsePoint() len mismatch: got %v, exp %v", test.name, len(pts), exp) - } - pt := pts[0] - - got := pt.String() - if got != test.exp { - t.Errorf("%s: ParsePoint() to string mismatch:\n got %v\n exp %v", test.name, got, test.exp) - } - } -} - -func TestParsePointsWithPrecisionComments(t *testing.T) { - tests := []struct { - name string - batch string - exp string - lenPoints int - }{ - { - name: "comment only", - batch: `# comment only`, - exp: "cpu,host=serverA,region=us-east value=1.0 946730096789012345", - lenPoints: 0, - }, - { - name: "point with comment above", - batch: `# a point is below -cpu,host=serverA,region=us-east value=1.0 946730096789012345`, - exp: "cpu,host=serverA,region=us-east value=1.0 946730096789012345", - lenPoints: 1, - }, - { - name: "point with comment below", - batch: `cpu,host=serverA,region=us-east value=1.0 946730096789012345 -# end of points`, - exp: "cpu,host=serverA,region=us-east value=1.0 946730096789012345", - lenPoints: 1, - }, - { - name: "indented comment", - batch: ` # a point is below -cpu,host=serverA,region=us-east value=1.0 946730096789012345`, - exp: "cpu,host=serverA,region=us-east value=1.0 946730096789012345", - lenPoints: 1, - }, - } - for _, test := range tests { - pts, err := models.ParsePointsWithPrecision([]byte(test.batch), time.Now().UTC(), "") - if err != nil { - t.Fatalf(`%s: ParsePoints() failed. got %s`, test.name, err) - } - pointsLength := len(pts) - if exp := test.lenPoints; pointsLength != exp { - t.Errorf("%s: ParsePoint() len mismatch: got %v, exp %v", test.name, pointsLength, exp) - } - - if pointsLength > 0 { - pt := pts[0] - - got := pt.String() - if got != test.exp { - t.Errorf("%s: ParsePoint() to string mismatch:\n got %v\n exp %v", test.name, got, test.exp) - } - } - } -} - -func TestNewPointEscaped(t *testing.T) { - // commas - pt := models.MustNewPoint("cpu,main", models.NewTags(map[string]string{"tag,bar": "value"}), models.Fields{"name,bar": 1.0}, time.Unix(0, 0)) - if exp := `cpu\,main,tag\,bar=value name\,bar=1 0`; pt.String() != exp { - t.Errorf("NewPoint().String() mismatch.\ngot %v\nexp %v", pt.String(), exp) - } - - // spaces - pt = models.MustNewPoint("cpu main", models.NewTags(map[string]string{"tag bar": "value"}), models.Fields{"name bar": 1.0}, time.Unix(0, 0)) - if exp := `cpu\ main,tag\ bar=value name\ bar=1 0`; pt.String() != exp { - t.Errorf("NewPoint().String() mismatch.\ngot %v\nexp %v", pt.String(), exp) - } - - // equals - pt = models.MustNewPoint("cpu=main", models.NewTags(map[string]string{"tag=bar": "value=foo"}), models.Fields{"name=bar": 1.0}, time.Unix(0, 0)) - if exp := `cpu=main,tag\=bar=value\=foo name\=bar=1 0`; pt.String() != exp { - t.Errorf("NewPoint().String() mismatch.\ngot %v\nexp %v", pt.String(), exp) - } -} - -func TestNewPointWithoutField(t *testing.T) { - _, err := models.NewPoint("cpu", models.NewTags(map[string]string{"tag": "bar"}), models.Fields{}, time.Unix(0, 0)) - if err == nil { - t.Fatalf(`NewPoint() expected error. got nil`) - } -} - -func TestNewPointUnhandledType(t *testing.T) { - // nil value - pt := models.MustNewPoint("cpu", nil, models.Fields{"value": nil}, time.Unix(0, 0)) - if exp := `cpu value= 0`; pt.String() != exp { - t.Errorf("NewPoint().String() mismatch.\ngot %v\nexp %v", pt.String(), exp) - } - - // unsupported type gets stored as string - now := time.Unix(0, 0).UTC() - pt = models.MustNewPoint("cpu", nil, models.Fields{"value": now}, time.Unix(0, 0)) - if exp := `cpu value="1970-01-01 00:00:00 +0000 UTC" 0`; pt.String() != exp { - t.Errorf("NewPoint().String() mismatch.\ngot %v\nexp %v", pt.String(), exp) - } - - if exp := "1970-01-01 00:00:00 +0000 UTC"; pt.Fields()["value"] != exp { - t.Errorf("NewPoint().String() mismatch.\ngot %v\nexp %v", pt.String(), exp) - } -} - -func TestMakeKeyEscaped(t *testing.T) { - if exp, got := `cpu\ load`, models.MakeKey([]byte(`cpu\ load`), models.NewTags(map[string]string{})); string(got) != exp { - t.Errorf("MakeKey() mismatch.\ngot %v\nexp %v", got, exp) - } - - if exp, got := `cpu\ load`, models.MakeKey([]byte(`cpu load`), models.NewTags(map[string]string{})); string(got) != exp { - t.Errorf("MakeKey() mismatch.\ngot %v\nexp %v", got, exp) - } - - if exp, got := `cpu\,load`, models.MakeKey([]byte(`cpu\,load`), models.NewTags(map[string]string{})); string(got) != exp { - t.Errorf("MakeKey() mismatch.\ngot %v\nexp %v", got, exp) - } - - if exp, got := `cpu\,load`, models.MakeKey([]byte(`cpu,load`), models.NewTags(map[string]string{})); string(got) != exp { - t.Errorf("MakeKey() mismatch.\ngot %v\nexp %v", got, exp) - } - -} - -func TestPrecisionString(t *testing.T) { - tags := map[string]interface{}{"value": float64(1)} - tm, _ := time.Parse(time.RFC3339Nano, "2000-01-01T12:34:56.789012345Z") - tests := []struct { - name string - precision string - exp string - }{ - { - name: "no precision", - precision: "", - exp: "cpu value=1 946730096789012345", - }, - { - name: "nanosecond precision", - precision: "ns", - exp: "cpu value=1 946730096789012345", - }, - { - name: "microsecond precision", - precision: "u", - exp: "cpu value=1 946730096789012", - }, - { - name: "millisecond precision", - precision: "ms", - exp: "cpu value=1 946730096789", - }, - { - name: "second precision", - precision: "s", - exp: "cpu value=1 946730096", - }, - { - name: "minute precision", - precision: "m", - exp: "cpu value=1 15778834", - }, - { - name: "hour precision", - precision: "h", - exp: "cpu value=1 262980", - }, - } - - for _, test := range tests { - pt := models.MustNewPoint("cpu", nil, tags, tm) - act := pt.PrecisionString(test.precision) - - if act != test.exp { - t.Errorf("%s: PrecisionString() mismatch:\n actual: %v\n exp: %v", - test.name, act, test.exp) - } - } -} - -func TestRoundedString(t *testing.T) { - tags := map[string]interface{}{"value": float64(1)} - tm, _ := time.Parse(time.RFC3339Nano, "2000-01-01T12:34:56.789012345Z") - tests := []struct { - name string - precision time.Duration - exp string - }{ - { - name: "no precision", - precision: time.Duration(0), - exp: "cpu value=1 946730096789012345", - }, - { - name: "nanosecond precision", - precision: time.Nanosecond, - exp: "cpu value=1 946730096789012345", - }, - { - name: "microsecond precision", - precision: time.Microsecond, - exp: "cpu value=1 946730096789012000", - }, - { - name: "millisecond precision", - precision: time.Millisecond, - exp: "cpu value=1 946730096789000000", - }, - { - name: "second precision", - precision: time.Second, - exp: "cpu value=1 946730097000000000", - }, - { - name: "minute precision", - precision: time.Minute, - exp: "cpu value=1 946730100000000000", - }, - { - name: "hour precision", - precision: time.Hour, - exp: "cpu value=1 946731600000000000", - }, - } - - for _, test := range tests { - pt := models.MustNewPoint("cpu", nil, tags, tm) - act := pt.RoundedString(test.precision) - - if act != test.exp { - t.Errorf("%s: RoundedString() mismatch:\n actual: %v\n exp: %v", - test.name, act, test.exp) - } - } -} - -func TestParsePointsStringWithExtraBuffer(t *testing.T) { - b := make([]byte, 70*5000) - buf := bytes.NewBuffer(b) - key := "cpu,host=A,region=uswest" - buf.WriteString(fmt.Sprintf("%s value=%.3f 1\n", key, rand.Float64())) - - points, err := models.ParsePointsString(buf.String()) - if err != nil { - t.Fatalf("failed to write points: %s", err.Error()) - } - - pointKey := string(points[0].Key()) - - if len(key) != len(pointKey) { - t.Fatalf("expected length of both keys are same but got %d and %d", len(key), len(pointKey)) - } - - if key != pointKey { - t.Fatalf("expected both keys are same but got %s and %s", key, pointKey) - } -} - -func TestParsePointsQuotesInFieldKey(t *testing.T) { - buf := `cpu "a=1 -cpu value=2 1` - points, err := models.ParsePointsString(buf) - if err != nil { - t.Fatalf("failed to write points: %s", err.Error()) - } - - pointFields := points[0].Fields() - value, ok := pointFields["\"a"] - if !ok { - t.Fatalf("expected to parse field '\"a'") - } - - if value != float64(1) { - t.Fatalf("expected field value to be 1, got %v", value) - } - - // The following input should not parse - buf = `cpu "\, '= "\ v=1.0` - _, err = models.ParsePointsString(buf) - if err == nil { - t.Fatalf("expected parsing failure but got no error") - } -} - -func TestParsePointsQuotesInTags(t *testing.T) { - buf := `t159,label=hey\ "ya a=1i,value=0i -t159,label=another a=2i,value=1i 1` - points, err := models.ParsePointsString(buf) - if err != nil { - t.Fatalf("failed to write points: %s", err.Error()) - } - - if len(points) != 2 { - t.Fatalf("expected 2 points, got %d", len(points)) - } -} - -func TestParsePointsBlankLine(t *testing.T) { - buf := `cpu value=1i 1000000000 - -cpu value=2i 2000000000` - points, err := models.ParsePointsString(buf) - if err != nil { - t.Fatalf("failed to write points: %s", err.Error()) - } - - if len(points) != 2 { - t.Fatalf("expected 2 points, got %d", len(points)) - } -} - -func TestNewPointsWithBytesWithCorruptData(t *testing.T) { - corrupted := []byte{0, 0, 0, 3, 102, 111, 111, 0, 0, 0, 4, 61, 34, 65, 34, 1, 0, 0, 0, 14, 206, 86, 119, 24, 32, 72, 233, 168, 2, 148} - p, err := models.NewPointFromBytes(corrupted) - if p != nil || err == nil { - t.Fatalf("NewPointFromBytes: got: (%v, %v), expected: (nil, error)", p, err) - } -} - -func TestNewPointsRejectsEmptyFieldNames(t *testing.T) { - if _, err := models.NewPoint("foo", nil, models.Fields{"": 1}, time.Now()); err == nil { - t.Fatalf("new point with empty field name. got: nil, expected: error") - } -} - -func TestNewPointsRejectsMaxKey(t *testing.T) { - var key string - for i := 0; i < 65536; i++ { - key += "a" - } - - if _, err := models.NewPoint(key, nil, models.Fields{"value": 1}, time.Now()); err == nil { - t.Fatalf("new point with max key. got: nil, expected: error") - } - - if _, err := models.ParsePointsString(fmt.Sprintf("%v value=1", key)); err == nil { - t.Fatalf("parse point with max key. got: nil, expected: error") - } -} - -func TestParseKeyEmpty(t *testing.T) { - if _, _, err := models.ParseKey(nil); err != nil { - t.Fatalf("unexpected error: %v", err) - } -} - -func TestPoint_FieldIterator_Simple(t *testing.T) { - - p, err := models.ParsePoints([]byte(`m v=42i,f=42 36`)) - if err != nil { - t.Fatal(err) - } - - if len(p) != 1 { - t.Fatalf("wrong number of points, got %d, exp %d", len(p), 1) - } - - fi := p[0].FieldIterator() - - if !fi.Next() { - t.Fatal("field iterator terminated before first field") - } - - if fi.Type() != models.Integer { - t.Fatalf("'42i' should be an Integer, got %v", fi.Type()) - } - - if fi.IntegerValue() != 42 { - t.Fatalf("'42i' should be 42, got %d", fi.IntegerValue()) - } - - if !fi.Next() { - t.Fatalf("field iterator terminated before second field") - } - - if fi.Type() != models.Float { - t.Fatalf("'42' should be a Float, got %v", fi.Type()) - } - - if fi.FloatValue() != 42.0 { - t.Fatalf("'42' should be %f, got %f", 42.0, fi.FloatValue()) - } - - if fi.Next() { - t.Fatal("field iterator didn't terminate") - } -} - -func toFields(fi models.FieldIterator) models.Fields { - m := make(models.Fields) - for fi.Next() { - var v interface{} - switch fi.Type() { - case models.Float: - v = fi.FloatValue() - case models.Integer: - v = fi.IntegerValue() - case models.String: - v = fi.StringValue() - case models.Boolean: - v = fi.BooleanValue() - case models.Empty: - v = nil - default: - panic("unknown type") - } - m[string(fi.FieldKey())] = v - } - return m -} - -func TestPoint_FieldIterator_FieldMap(t *testing.T) { - - points, err := models.ParsePointsString(` -m v=42 -m v=42i -m v="string" -m v=true -m v="string\"with\"escapes" -m v=42i,f=42,g=42.314 -m a=2i,b=3i,c=true,d="stuff",e=-0.23,f=123.456 -`) - - if err != nil { - t.Fatal("failed to parse test points:", err) - } - - for _, p := range points { - exp := p.Fields() - got := toFields(p.FieldIterator()) - - if !reflect.DeepEqual(got, exp) { - t.Errorf("FieldIterator failed for %#q: got %#v, exp %#v", p.String(), got, exp) - } - } -} - -func TestPoint_FieldIterator_Delete_Begin(t *testing.T) { - points, err := models.ParsePointsString(`m a=1,b=2,c=3`) - if err != nil || len(points) != 1 { - t.Fatal("failed parsing point") - } - - fi := points[0].FieldIterator() - fi.Next() // a - fi.Delete() - - fi.Reset() - - got := toFields(fi) - exp := models.Fields{"b": float64(2), "c": float64(3)} - - if !reflect.DeepEqual(got, exp) { - t.Fatalf("Delete failed, got %#v, exp %#v", got, exp) - } -} - -func TestPoint_FieldIterator_Delete_Middle(t *testing.T) { - points, err := models.ParsePointsString(`m a=1,b=2,c=3`) - if err != nil || len(points) != 1 { - t.Fatal("failed parsing point") - } - - fi := points[0].FieldIterator() - fi.Next() // a - fi.Next() // b - fi.Delete() - - fi.Reset() - - got := toFields(fi) - exp := models.Fields{"a": float64(1), "c": float64(3)} - - if !reflect.DeepEqual(got, exp) { - t.Fatalf("Delete failed, got %#v, exp %#v", got, exp) - } -} - -func TestPoint_FieldIterator_Delete_End(t *testing.T) { - points, err := models.ParsePointsString(`m a=1,b=2,c=3`) - if err != nil || len(points) != 1 { - t.Fatal("failed parsing point") - } - - fi := points[0].FieldIterator() - fi.Next() // a - fi.Next() // b - fi.Next() // c - fi.Delete() - - fi.Reset() - - got := toFields(fi) - exp := models.Fields{"a": float64(1), "b": float64(2)} - - if !reflect.DeepEqual(got, exp) { - t.Fatalf("Delete failed, got %#v, exp %#v", got, exp) - } -} - -func TestPoint_FieldIterator_Delete_Nothing(t *testing.T) { - points, err := models.ParsePointsString(`m a=1,b=2,c=3`) - if err != nil || len(points) != 1 { - t.Fatal("failed parsing point") - } - - fi := points[0].FieldIterator() - fi.Delete() - - fi.Reset() - - got := toFields(fi) - exp := models.Fields{"a": float64(1), "b": float64(2), "c": float64(3)} - - if !reflect.DeepEqual(got, exp) { - t.Fatalf("Delete failed, got %#v, exp %#v", got, exp) - } -} - -func TestPoint_FieldIterator_Delete_Twice(t *testing.T) { - points, err := models.ParsePointsString(`m a=1,b=2,c=3`) - if err != nil || len(points) != 1 { - t.Fatal("failed parsing point") - } - - fi := points[0].FieldIterator() - fi.Next() // a - fi.Next() // b - fi.Delete() - fi.Delete() // no-op - - fi.Reset() - - got := toFields(fi) - exp := models.Fields{"a": float64(1), "c": float64(3)} - - if !reflect.DeepEqual(got, exp) { - t.Fatalf("Delete failed, got %#v, exp %#v", got, exp) - } -} diff --git a/vendor/github.com/influxdata/influxdb/models/statistic_test.go b/vendor/github.com/influxdata/influxdb/models/statistic_test.go deleted file mode 100644 index 918c991342fa..000000000000 --- a/vendor/github.com/influxdata/influxdb/models/statistic_test.go +++ /dev/null @@ -1,55 +0,0 @@ -package models_test - -import ( - "reflect" - "testing" - - "github.com/influxdata/influxdb/models" -) - -func TestTags_Merge(t *testing.T) { - examples := []struct { - Base map[string]string - Arg map[string]string - Result map[string]string - }{ - { - Base: nil, - Arg: nil, - Result: map[string]string{}, - }, - { - Base: nil, - Arg: map[string]string{"foo": "foo"}, - Result: map[string]string{"foo": "foo"}, - }, - { - Base: map[string]string{"foo": "foo"}, - Arg: nil, - Result: map[string]string{"foo": "foo"}, - }, - { - Base: map[string]string{"foo": "foo"}, - Arg: map[string]string{"bar": "bar"}, - Result: map[string]string{"foo": "foo", "bar": "bar"}, - }, - { - Base: map[string]string{"foo": "foo", "bar": "bar"}, - Arg: map[string]string{"zoo": "zoo"}, - Result: map[string]string{"foo": "foo", "bar": "bar", "zoo": "zoo"}, - }, - { - Base: map[string]string{"foo": "foo", "bar": "bar"}, - Arg: map[string]string{"bar": "newbar"}, - Result: map[string]string{"foo": "foo", "bar": "newbar"}, - }, - } - - for i, example := range examples { - i++ - result := models.StatisticTags(example.Base).Merge(example.Arg) - if got, exp := result, example.Result; !reflect.DeepEqual(got, exp) { - t.Errorf("[Example %d] got %#v, expected %#v", i, got, exp) - } - } -} diff --git a/vendor/github.com/influxdata/influxdb/pkg/escape/BUILD b/vendor/github.com/influxdata/influxdb/pkg/escape/BUILD index 8d13f889fcf2..7e2d12a94671 100644 --- a/vendor/github.com/influxdata/influxdb/pkg/escape/BUILD +++ b/vendor/github.com/influxdata/influxdb/pkg/escape/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -10,13 +10,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = ["bytes_test.go"], - importpath = "github.com/influxdata/influxdb/pkg/escape", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/influxdata/influxdb/pkg/escape/bytes_test.go b/vendor/github.com/influxdata/influxdb/pkg/escape/bytes_test.go deleted file mode 100644 index e9418f659f78..000000000000 --- a/vendor/github.com/influxdata/influxdb/pkg/escape/bytes_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package escape - -import ( - "bytes" - "reflect" - "strings" - "testing" -) - -func TestUnescape(t *testing.T) { - tests := []struct { - in []byte - out []byte - }{ - { - []byte(nil), - []byte(nil), - }, - - { - []byte(""), - []byte(nil), - }, - - { - []byte("\\,\\\"\\ \\="), - []byte(",\" ="), - }, - - { - []byte("\\\\"), - []byte("\\\\"), - }, - - { - []byte("plain and simple"), - []byte("plain and simple"), - }, - } - - for ii, tt := range tests { - got := Unescape(tt.in) - if !reflect.DeepEqual(got, tt.out) { - t.Errorf("[%d] Unescape(%#v) = %#v, expected %#v", ii, string(tt.in), string(got), string(tt.out)) - } - } -} - -func TestAppendUnescaped(t *testing.T) { - cases := strings.Split(strings.TrimSpace(` -normal -inv\alid -goo\"d -sp\ ace -\,\"\ \= -f\\\ x -`), "\n") - - for _, c := range cases { - exp := Unescape([]byte(c)) - got := AppendUnescaped(nil, []byte(c)) - - if !bytes.Equal(got, exp) { - t.Errorf("AppendUnescaped failed for %#q: got %#q, exp %#q", c, got, exp) - } - } - -} diff --git a/vendor/github.com/jinzhu/gorm/BUILD b/vendor/github.com/jinzhu/gorm/BUILD index 6beba3d632f3..5682ff64041b 100644 --- a/vendor/github.com/jinzhu/gorm/BUILD +++ b/vendor/github.com/jinzhu/gorm/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -34,52 +34,6 @@ go_library( deps = ["//vendor/github.com/jinzhu/inflection:go_default_library"], ) -go_test( - name = "go_default_test", - srcs = [ - "callback_system_test.go", - "search_test.go", - ], - importpath = "github.com/jinzhu/gorm", - library = ":go_default_library", -) - -go_test( - name = "go_default_xtest", - srcs = [ - "association_test.go", - "callbacks_test.go", - "create_test.go", - "customize_column_test.go", - "delete_test.go", - "embedded_struct_test.go", - "errors_test.go", - "field_test.go", - "join_table_test.go", - "main_test.go", - "migration_test.go", - "multi_primary_keys_test.go", - "pointer_test.go", - "polymorphic_test.go", - "preload_test.go", - "query_test.go", - "scaner_test.go", - "scope_test.go", - "update_test.go", - "utils_test.go", - ], - importpath = "github.com/jinzhu/gorm_test", - deps = [ - ":go_default_library", - "//vendor/github.com/erikstmartin/go-testdb:go_default_library", - "//vendor/github.com/jinzhu/gorm/dialects/mssql:go_default_library", - "//vendor/github.com/jinzhu/gorm/dialects/mysql:go_default_library", - "//vendor/github.com/jinzhu/gorm/dialects/postgres:go_default_library", - "//vendor/github.com/jinzhu/gorm/dialects/sqlite:go_default_library", - "//vendor/github.com/jinzhu/now:go_default_library", - ], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/jinzhu/gorm/association_test.go b/vendor/github.com/jinzhu/gorm/association_test.go deleted file mode 100644 index c84f84ed610b..000000000000 --- a/vendor/github.com/jinzhu/gorm/association_test.go +++ /dev/null @@ -1,907 +0,0 @@ -package gorm_test - -import ( - "fmt" - "os" - "reflect" - "sort" - "testing" - - "github.com/jinzhu/gorm" -) - -func TestBelongsTo(t *testing.T) { - post := Post{ - Title: "post belongs to", - Body: "body belongs to", - Category: Category{Name: "Category 1"}, - MainCategory: Category{Name: "Main Category 1"}, - } - - if err := DB.Save(&post).Error; err != nil { - t.Error("Got errors when save post", err) - } - - if post.Category.ID == 0 || post.MainCategory.ID == 0 { - t.Errorf("Category's primary key should be updated") - } - - if post.CategoryId.Int64 == 0 || post.MainCategoryId == 0 { - t.Errorf("post's foreign key should be updated") - } - - // Query - var category1 Category - DB.Model(&post).Association("Category").Find(&category1) - if category1.Name != "Category 1" { - t.Errorf("Query belongs to relations with Association") - } - - var mainCategory1 Category - DB.Model(&post).Association("MainCategory").Find(&mainCategory1) - if mainCategory1.Name != "Main Category 1" { - t.Errorf("Query belongs to relations with Association") - } - - var category11 Category - DB.Model(&post).Related(&category11) - if category11.Name != "Category 1" { - t.Errorf("Query belongs to relations with Related") - } - - if DB.Model(&post).Association("Category").Count() != 1 { - t.Errorf("Post's category count should be 1") - } - - if DB.Model(&post).Association("MainCategory").Count() != 1 { - t.Errorf("Post's main category count should be 1") - } - - // Append - var category2 = Category{ - Name: "Category 2", - } - DB.Model(&post).Association("Category").Append(&category2) - - if category2.ID == 0 { - t.Errorf("Category should has ID when created with Append") - } - - var category21 Category - DB.Model(&post).Related(&category21) - - if category21.Name != "Category 2" { - t.Errorf("Category should be updated with Append") - } - - if DB.Model(&post).Association("Category").Count() != 1 { - t.Errorf("Post's category count should be 1") - } - - // Replace - var category3 = Category{ - Name: "Category 3", - } - DB.Model(&post).Association("Category").Replace(&category3) - - if category3.ID == 0 { - t.Errorf("Category should has ID when created with Replace") - } - - var category31 Category - DB.Model(&post).Related(&category31) - if category31.Name != "Category 3" { - t.Errorf("Category should be updated with Replace") - } - - if DB.Model(&post).Association("Category").Count() != 1 { - t.Errorf("Post's category count should be 1") - } - - // Delete - DB.Model(&post).Association("Category").Delete(&category2) - if DB.Model(&post).Related(&Category{}).RecordNotFound() { - t.Errorf("Should not delete any category when Delete a unrelated Category") - } - - if post.Category.Name == "" { - t.Errorf("Post's category should not be reseted when Delete a unrelated Category") - } - - DB.Model(&post).Association("Category").Delete(&category3) - - if post.Category.Name != "" { - t.Errorf("Post's category should be reseted after Delete") - } - - var category41 Category - DB.Model(&post).Related(&category41) - if category41.Name != "" { - t.Errorf("Category should be deleted with Delete") - } - - if count := DB.Model(&post).Association("Category").Count(); count != 0 { - t.Errorf("Post's category count should be 0 after Delete, but got %v", count) - } - - // Clear - DB.Model(&post).Association("Category").Append(&Category{ - Name: "Category 2", - }) - - if DB.Model(&post).Related(&Category{}).RecordNotFound() { - t.Errorf("Should find category after append") - } - - if post.Category.Name == "" { - t.Errorf("Post's category should has value after Append") - } - - DB.Model(&post).Association("Category").Clear() - - if post.Category.Name != "" { - t.Errorf("Post's category should be cleared after Clear") - } - - if !DB.Model(&post).Related(&Category{}).RecordNotFound() { - t.Errorf("Should not find any category after Clear") - } - - if count := DB.Model(&post).Association("Category").Count(); count != 0 { - t.Errorf("Post's category count should be 0 after Clear, but got %v", count) - } - - // Check Association mode with soft delete - category6 := Category{ - Name: "Category 6", - } - DB.Model(&post).Association("Category").Append(&category6) - - if count := DB.Model(&post).Association("Category").Count(); count != 1 { - t.Errorf("Post's category count should be 1 after Append, but got %v", count) - } - - DB.Delete(&category6) - - if count := DB.Model(&post).Association("Category").Count(); count != 0 { - t.Errorf("Post's category count should be 0 after the category has been deleted, but got %v", count) - } - - if err := DB.Model(&post).Association("Category").Find(&Category{}).Error; err == nil { - t.Errorf("Post's category is not findable after Delete") - } - - if count := DB.Unscoped().Model(&post).Association("Category").Count(); count != 1 { - t.Errorf("Post's category count should be 1 when query with Unscoped, but got %v", count) - } - - if err := DB.Unscoped().Model(&post).Association("Category").Find(&Category{}).Error; err != nil { - t.Errorf("Post's category should be findable when query with Unscoped, got %v", err) - } -} - -func TestBelongsToOverrideForeignKey1(t *testing.T) { - type Profile struct { - gorm.Model - Name string - } - - type User struct { - gorm.Model - Profile Profile `gorm:"ForeignKey:ProfileRefer"` - ProfileRefer int - } - - if relation, ok := DB.NewScope(&User{}).FieldByName("Profile"); ok { - if relation.Relationship.Kind != "belongs_to" || - !reflect.DeepEqual(relation.Relationship.ForeignFieldNames, []string{"ProfileRefer"}) || - !reflect.DeepEqual(relation.Relationship.AssociationForeignFieldNames, []string{"ID"}) { - t.Errorf("Override belongs to foreign key with tag") - } - } -} - -func TestBelongsToOverrideForeignKey2(t *testing.T) { - type Profile struct { - gorm.Model - Refer string - Name string - } - - type User struct { - gorm.Model - Profile Profile `gorm:"ForeignKey:ProfileID;AssociationForeignKey:Refer"` - ProfileID int - } - - if relation, ok := DB.NewScope(&User{}).FieldByName("Profile"); ok { - if relation.Relationship.Kind != "belongs_to" || - !reflect.DeepEqual(relation.Relationship.ForeignFieldNames, []string{"ProfileID"}) || - !reflect.DeepEqual(relation.Relationship.AssociationForeignFieldNames, []string{"Refer"}) { - t.Errorf("Override belongs to foreign key with tag") - } - } -} - -func TestHasOne(t *testing.T) { - user := User{ - Name: "has one", - CreditCard: CreditCard{Number: "411111111111"}, - } - - if err := DB.Save(&user).Error; err != nil { - t.Error("Got errors when save user", err.Error()) - } - - if user.CreditCard.UserId.Int64 == 0 { - t.Errorf("CreditCard's foreign key should be updated") - } - - // Query - var creditCard1 CreditCard - DB.Model(&user).Related(&creditCard1) - - if creditCard1.Number != "411111111111" { - t.Errorf("Query has one relations with Related") - } - - var creditCard11 CreditCard - DB.Model(&user).Association("CreditCard").Find(&creditCard11) - - if creditCard11.Number != "411111111111" { - t.Errorf("Query has one relations with Related") - } - - if DB.Model(&user).Association("CreditCard").Count() != 1 { - t.Errorf("User's credit card count should be 1") - } - - // Append - var creditcard2 = CreditCard{ - Number: "411111111112", - } - DB.Model(&user).Association("CreditCard").Append(&creditcard2) - - if creditcard2.ID == 0 { - t.Errorf("Creditcard should has ID when created with Append") - } - - var creditcard21 CreditCard - DB.Model(&user).Related(&creditcard21) - if creditcard21.Number != "411111111112" { - t.Errorf("CreditCard should be updated with Append") - } - - if DB.Model(&user).Association("CreditCard").Count() != 1 { - t.Errorf("User's credit card count should be 1") - } - - // Replace - var creditcard3 = CreditCard{ - Number: "411111111113", - } - DB.Model(&user).Association("CreditCard").Replace(&creditcard3) - - if creditcard3.ID == 0 { - t.Errorf("Creditcard should has ID when created with Replace") - } - - var creditcard31 CreditCard - DB.Model(&user).Related(&creditcard31) - if creditcard31.Number != "411111111113" { - t.Errorf("CreditCard should be updated with Replace") - } - - if DB.Model(&user).Association("CreditCard").Count() != 1 { - t.Errorf("User's credit card count should be 1") - } - - // Delete - DB.Model(&user).Association("CreditCard").Delete(&creditcard2) - var creditcard4 CreditCard - DB.Model(&user).Related(&creditcard4) - if creditcard4.Number != "411111111113" { - t.Errorf("Should not delete credit card when Delete a unrelated CreditCard") - } - - if DB.Model(&user).Association("CreditCard").Count() != 1 { - t.Errorf("User's credit card count should be 1") - } - - DB.Model(&user).Association("CreditCard").Delete(&creditcard3) - if !DB.Model(&user).Related(&CreditCard{}).RecordNotFound() { - t.Errorf("Should delete credit card with Delete") - } - - if DB.Model(&user).Association("CreditCard").Count() != 0 { - t.Errorf("User's credit card count should be 0 after Delete") - } - - // Clear - var creditcard5 = CreditCard{ - Number: "411111111115", - } - DB.Model(&user).Association("CreditCard").Append(&creditcard5) - - if DB.Model(&user).Related(&CreditCard{}).RecordNotFound() { - t.Errorf("Should added credit card with Append") - } - - if DB.Model(&user).Association("CreditCard").Count() != 1 { - t.Errorf("User's credit card count should be 1") - } - - DB.Model(&user).Association("CreditCard").Clear() - if !DB.Model(&user).Related(&CreditCard{}).RecordNotFound() { - t.Errorf("Credit card should be deleted with Clear") - } - - if DB.Model(&user).Association("CreditCard").Count() != 0 { - t.Errorf("User's credit card count should be 0 after Clear") - } - - // Check Association mode with soft delete - var creditcard6 = CreditCard{ - Number: "411111111116", - } - DB.Model(&user).Association("CreditCard").Append(&creditcard6) - - if count := DB.Model(&user).Association("CreditCard").Count(); count != 1 { - t.Errorf("User's credit card count should be 1 after Append, but got %v", count) - } - - DB.Delete(&creditcard6) - - if count := DB.Model(&user).Association("CreditCard").Count(); count != 0 { - t.Errorf("User's credit card count should be 0 after credit card deleted, but got %v", count) - } - - if err := DB.Model(&user).Association("CreditCard").Find(&CreditCard{}).Error; err == nil { - t.Errorf("User's creditcard is not findable after Delete") - } - - if count := DB.Unscoped().Model(&user).Association("CreditCard").Count(); count != 1 { - t.Errorf("User's credit card count should be 1 when query with Unscoped, but got %v", count) - } - - if err := DB.Unscoped().Model(&user).Association("CreditCard").Find(&CreditCard{}).Error; err != nil { - t.Errorf("User's creditcard should be findable when query with Unscoped, got %v", err) - } -} - -func TestHasOneOverrideForeignKey1(t *testing.T) { - type Profile struct { - gorm.Model - Name string - UserRefer uint - } - - type User struct { - gorm.Model - Profile Profile `gorm:"ForeignKey:UserRefer"` - } - - if relation, ok := DB.NewScope(&User{}).FieldByName("Profile"); ok { - if relation.Relationship.Kind != "has_one" || - !reflect.DeepEqual(relation.Relationship.ForeignFieldNames, []string{"UserRefer"}) || - !reflect.DeepEqual(relation.Relationship.AssociationForeignFieldNames, []string{"ID"}) { - t.Errorf("Override belongs to foreign key with tag") - } - } -} - -func TestHasOneOverrideForeignKey2(t *testing.T) { - type Profile struct { - gorm.Model - Name string - UserID uint - } - - type User struct { - gorm.Model - Refer string - Profile Profile `gorm:"ForeignKey:UserID;AssociationForeignKey:Refer"` - } - - if relation, ok := DB.NewScope(&User{}).FieldByName("Profile"); ok { - if relation.Relationship.Kind != "has_one" || - !reflect.DeepEqual(relation.Relationship.ForeignFieldNames, []string{"UserID"}) || - !reflect.DeepEqual(relation.Relationship.AssociationForeignFieldNames, []string{"Refer"}) { - t.Errorf("Override belongs to foreign key with tag") - } - } -} - -func TestHasMany(t *testing.T) { - post := Post{ - Title: "post has many", - Body: "body has many", - Comments: []*Comment{{Content: "Comment 1"}, {Content: "Comment 2"}}, - } - - if err := DB.Save(&post).Error; err != nil { - t.Error("Got errors when save post", err) - } - - for _, comment := range post.Comments { - if comment.PostId == 0 { - t.Errorf("comment's PostID should be updated") - } - } - - var compareComments = func(comments []Comment, contents []string) bool { - var commentContents []string - for _, comment := range comments { - commentContents = append(commentContents, comment.Content) - } - sort.Strings(commentContents) - sort.Strings(contents) - return reflect.DeepEqual(commentContents, contents) - } - - // Query - if DB.First(&Comment{}, "content = ?", "Comment 1").Error != nil { - t.Errorf("Comment 1 should be saved") - } - - var comments1 []Comment - DB.Model(&post).Association("Comments").Find(&comments1) - if !compareComments(comments1, []string{"Comment 1", "Comment 2"}) { - t.Errorf("Query has many relations with Association") - } - - var comments11 []Comment - DB.Model(&post).Related(&comments11) - if !compareComments(comments11, []string{"Comment 1", "Comment 2"}) { - t.Errorf("Query has many relations with Related") - } - - if DB.Model(&post).Association("Comments").Count() != 2 { - t.Errorf("Post's comments count should be 2") - } - - // Append - DB.Model(&post).Association("Comments").Append(&Comment{Content: "Comment 3"}) - - var comments2 []Comment - DB.Model(&post).Related(&comments2) - if !compareComments(comments2, []string{"Comment 1", "Comment 2", "Comment 3"}) { - t.Errorf("Append new record to has many relations") - } - - if DB.Model(&post).Association("Comments").Count() != 3 { - t.Errorf("Post's comments count should be 3 after Append") - } - - // Delete - DB.Model(&post).Association("Comments").Delete(comments11) - - var comments3 []Comment - DB.Model(&post).Related(&comments3) - if !compareComments(comments3, []string{"Comment 3"}) { - t.Errorf("Delete an existing resource for has many relations") - } - - if DB.Model(&post).Association("Comments").Count() != 1 { - t.Errorf("Post's comments count should be 1 after Delete 2") - } - - // Replace - DB.Model(&Post{Id: 999}).Association("Comments").Replace() - - var comments4 []Comment - DB.Model(&post).Related(&comments4) - if len(comments4) == 0 { - t.Errorf("Replace for other resource should not clear all comments") - } - - DB.Model(&post).Association("Comments").Replace(&Comment{Content: "Comment 4"}, &Comment{Content: "Comment 5"}) - - var comments41 []Comment - DB.Model(&post).Related(&comments41) - if !compareComments(comments41, []string{"Comment 4", "Comment 5"}) { - t.Errorf("Replace has many relations") - } - - // Clear - DB.Model(&Post{Id: 999}).Association("Comments").Clear() - - var comments5 []Comment - DB.Model(&post).Related(&comments5) - if len(comments5) == 0 { - t.Errorf("Clear should not clear all comments") - } - - DB.Model(&post).Association("Comments").Clear() - - var comments51 []Comment - DB.Model(&post).Related(&comments51) - if len(comments51) != 0 { - t.Errorf("Clear has many relations") - } - - // Check Association mode with soft delete - var comment6 = Comment{ - Content: "comment 6", - } - DB.Model(&post).Association("Comments").Append(&comment6) - - if count := DB.Model(&post).Association("Comments").Count(); count != 1 { - t.Errorf("post's comments count should be 1 after Append, but got %v", count) - } - - DB.Delete(&comment6) - - if count := DB.Model(&post).Association("Comments").Count(); count != 0 { - t.Errorf("post's comments count should be 0 after comment been deleted, but got %v", count) - } - - var comments6 []Comment - if DB.Model(&post).Association("Comments").Find(&comments6); len(comments6) != 0 { - t.Errorf("post's comments count should be 0 when find with Find, but got %v", len(comments6)) - } - - if count := DB.Unscoped().Model(&post).Association("Comments").Count(); count != 1 { - t.Errorf("post's comments count should be 1 when query with Unscoped, but got %v", count) - } - - var comments61 []Comment - if DB.Unscoped().Model(&post).Association("Comments").Find(&comments61); len(comments61) != 1 { - t.Errorf("post's comments count should be 1 when query with Unscoped, but got %v", len(comments61)) - } -} - -func TestHasManyOverrideForeignKey1(t *testing.T) { - type Profile struct { - gorm.Model - Name string - UserRefer uint - } - - type User struct { - gorm.Model - Profile []Profile `gorm:"ForeignKey:UserRefer"` - } - - if relation, ok := DB.NewScope(&User{}).FieldByName("Profile"); ok { - if relation.Relationship.Kind != "has_many" || - !reflect.DeepEqual(relation.Relationship.ForeignFieldNames, []string{"UserRefer"}) || - !reflect.DeepEqual(relation.Relationship.AssociationForeignFieldNames, []string{"ID"}) { - t.Errorf("Override belongs to foreign key with tag") - } - } -} - -func TestHasManyOverrideForeignKey2(t *testing.T) { - type Profile struct { - gorm.Model - Name string - UserID uint - } - - type User struct { - gorm.Model - Refer string - Profile []Profile `gorm:"ForeignKey:UserID;AssociationForeignKey:Refer"` - } - - if relation, ok := DB.NewScope(&User{}).FieldByName("Profile"); ok { - if relation.Relationship.Kind != "has_many" || - !reflect.DeepEqual(relation.Relationship.ForeignFieldNames, []string{"UserID"}) || - !reflect.DeepEqual(relation.Relationship.AssociationForeignFieldNames, []string{"Refer"}) { - t.Errorf("Override belongs to foreign key with tag") - } - } -} - -func TestManyToMany(t *testing.T) { - DB.Raw("delete from languages") - var languages = []Language{{Name: "ZH"}, {Name: "EN"}} - user := User{Name: "Many2Many", Languages: languages} - DB.Save(&user) - - // Query - var newLanguages []Language - DB.Model(&user).Related(&newLanguages, "Languages") - if len(newLanguages) != len([]string{"ZH", "EN"}) { - t.Errorf("Query many to many relations") - } - - DB.Model(&user).Association("Languages").Find(&newLanguages) - if len(newLanguages) != len([]string{"ZH", "EN"}) { - t.Errorf("Should be able to find many to many relations") - } - - if DB.Model(&user).Association("Languages").Count() != len([]string{"ZH", "EN"}) { - t.Errorf("Count should return correct result") - } - - // Append - DB.Model(&user).Association("Languages").Append(&Language{Name: "DE"}) - if DB.Where("name = ?", "DE").First(&Language{}).RecordNotFound() { - t.Errorf("New record should be saved when append") - } - - languageA := Language{Name: "AA"} - DB.Save(&languageA) - DB.Model(&User{Id: user.Id}).Association("Languages").Append(&languageA) - - languageC := Language{Name: "CC"} - DB.Save(&languageC) - DB.Model(&user).Association("Languages").Append(&[]Language{{Name: "BB"}, languageC}) - - DB.Model(&User{Id: user.Id}).Association("Languages").Append(&[]Language{{Name: "DD"}, {Name: "EE"}}) - - totalLanguages := []string{"ZH", "EN", "DE", "AA", "BB", "CC", "DD", "EE"} - - if DB.Model(&user).Association("Languages").Count() != len(totalLanguages) { - t.Errorf("All appended languages should be saved") - } - - // Delete - user.Languages = []Language{} - DB.Model(&user).Association("Languages").Find(&user.Languages) - - var language Language - DB.Where("name = ?", "EE").First(&language) - DB.Model(&user).Association("Languages").Delete(language, &language) - - if DB.Model(&user).Association("Languages").Count() != len(totalLanguages)-1 || len(user.Languages) != len(totalLanguages)-1 { - t.Errorf("Relations should be deleted with Delete") - } - if DB.Where("name = ?", "EE").First(&Language{}).RecordNotFound() { - t.Errorf("Language EE should not be deleted") - } - - DB.Where("name IN (?)", []string{"CC", "DD"}).Find(&languages) - - user2 := User{Name: "Many2Many_User2", Languages: languages} - DB.Save(&user2) - - DB.Model(&user).Association("Languages").Delete(languages, &languages) - if DB.Model(&user).Association("Languages").Count() != len(totalLanguages)-3 || len(user.Languages) != len(totalLanguages)-3 { - t.Errorf("Relations should be deleted with Delete") - } - - if DB.Model(&user2).Association("Languages").Count() == 0 { - t.Errorf("Other user's relations should not be deleted") - } - - // Replace - var languageB Language - DB.Where("name = ?", "BB").First(&languageB) - DB.Model(&user).Association("Languages").Replace(languageB) - if len(user.Languages) != 1 || DB.Model(&user).Association("Languages").Count() != 1 { - t.Errorf("Relations should be replaced") - } - - DB.Model(&user).Association("Languages").Replace() - if len(user.Languages) != 0 || DB.Model(&user).Association("Languages").Count() != 0 { - t.Errorf("Relations should be replaced with empty") - } - - DB.Model(&user).Association("Languages").Replace(&[]Language{{Name: "FF"}, {Name: "JJ"}}) - if len(user.Languages) != 2 || DB.Model(&user).Association("Languages").Count() != len([]string{"FF", "JJ"}) { - t.Errorf("Relations should be replaced") - } - - // Clear - DB.Model(&user).Association("Languages").Clear() - if len(user.Languages) != 0 || DB.Model(&user).Association("Languages").Count() != 0 { - t.Errorf("Relations should be cleared") - } - - // Check Association mode with soft delete - var language6 = Language{ - Name: "language 6", - } - DB.Model(&user).Association("Languages").Append(&language6) - - if count := DB.Model(&user).Association("Languages").Count(); count != 1 { - t.Errorf("user's languages count should be 1 after Append, but got %v", count) - } - - DB.Delete(&language6) - - if count := DB.Model(&user).Association("Languages").Count(); count != 0 { - t.Errorf("user's languages count should be 0 after language been deleted, but got %v", count) - } - - var languages6 []Language - if DB.Model(&user).Association("Languages").Find(&languages6); len(languages6) != 0 { - t.Errorf("user's languages count should be 0 when find with Find, but got %v", len(languages6)) - } - - if count := DB.Unscoped().Model(&user).Association("Languages").Count(); count != 1 { - t.Errorf("user's languages count should be 1 when query with Unscoped, but got %v", count) - } - - var languages61 []Language - if DB.Unscoped().Model(&user).Association("Languages").Find(&languages61); len(languages61) != 1 { - t.Errorf("user's languages count should be 1 when query with Unscoped, but got %v", len(languages61)) - } -} - -func TestRelated(t *testing.T) { - user := User{ - Name: "jinzhu", - BillingAddress: Address{Address1: "Billing Address - Address 1"}, - ShippingAddress: Address{Address1: "Shipping Address - Address 1"}, - Emails: []Email{{Email: "jinzhu@example.com"}, {Email: "jinzhu-2@example@example.com"}}, - CreditCard: CreditCard{Number: "1234567890"}, - Company: Company{Name: "company1"}, - } - - if err := DB.Save(&user).Error; err != nil { - t.Errorf("No error should happen when saving user") - } - - if user.CreditCard.ID == 0 { - t.Errorf("After user save, credit card should have id") - } - - if user.BillingAddress.ID == 0 { - t.Errorf("After user save, billing address should have id") - } - - if user.Emails[0].Id == 0 { - t.Errorf("After user save, billing address should have id") - } - - var emails []Email - DB.Model(&user).Related(&emails) - if len(emails) != 2 { - t.Errorf("Should have two emails") - } - - var emails2 []Email - DB.Model(&user).Where("email = ?", "jinzhu@example.com").Related(&emails2) - if len(emails2) != 1 { - t.Errorf("Should have two emails") - } - - var emails3 []*Email - DB.Model(&user).Related(&emails3) - if len(emails3) != 2 { - t.Errorf("Should have two emails") - } - - var user1 User - DB.Model(&user).Related(&user1.Emails) - if len(user1.Emails) != 2 { - t.Errorf("Should have only one email match related condition") - } - - var address1 Address - DB.Model(&user).Related(&address1, "BillingAddressId") - if address1.Address1 != "Billing Address - Address 1" { - t.Errorf("Should get billing address from user correctly") - } - - user1 = User{} - DB.Model(&address1).Related(&user1, "BillingAddressId") - if DB.NewRecord(user1) { - t.Errorf("Should get user from address correctly") - } - - var user2 User - DB.Model(&emails[0]).Related(&user2) - if user2.Id != user.Id || user2.Name != user.Name { - t.Errorf("Should get user from email correctly") - } - - var creditcard CreditCard - var user3 User - DB.First(&creditcard, "number = ?", "1234567890") - DB.Model(&creditcard).Related(&user3) - if user3.Id != user.Id || user3.Name != user.Name { - t.Errorf("Should get user from credit card correctly") - } - - if !DB.Model(&CreditCard{}).Related(&User{}).RecordNotFound() { - t.Errorf("RecordNotFound for Related") - } - - var company Company - if DB.Model(&user).Related(&company, "Company").RecordNotFound() || company.Name != "company1" { - t.Errorf("RecordNotFound for Related") - } -} - -func TestForeignKey(t *testing.T) { - for _, structField := range DB.NewScope(&User{}).GetStructFields() { - for _, foreignKey := range []string{"BillingAddressID", "ShippingAddressId", "CompanyID"} { - if structField.Name == foreignKey && !structField.IsForeignKey { - t.Errorf(fmt.Sprintf("%v should be foreign key", foreignKey)) - } - } - } - - for _, structField := range DB.NewScope(&Email{}).GetStructFields() { - for _, foreignKey := range []string{"UserId"} { - if structField.Name == foreignKey && !structField.IsForeignKey { - t.Errorf(fmt.Sprintf("%v should be foreign key", foreignKey)) - } - } - } - - for _, structField := range DB.NewScope(&Post{}).GetStructFields() { - for _, foreignKey := range []string{"CategoryId", "MainCategoryId"} { - if structField.Name == foreignKey && !structField.IsForeignKey { - t.Errorf(fmt.Sprintf("%v should be foreign key", foreignKey)) - } - } - } - - for _, structField := range DB.NewScope(&Comment{}).GetStructFields() { - for _, foreignKey := range []string{"PostId"} { - if structField.Name == foreignKey && !structField.IsForeignKey { - t.Errorf(fmt.Sprintf("%v should be foreign key", foreignKey)) - } - } - } -} - -func testForeignKey(t *testing.T, source interface{}, sourceFieldName string, target interface{}, targetFieldName string) { - if dialect := os.Getenv("GORM_DIALECT"); dialect == "" || dialect == "sqlite" { - // sqlite does not support ADD CONSTRAINT in ALTER TABLE - return - } - targetScope := DB.NewScope(target) - targetTableName := targetScope.TableName() - modelScope := DB.NewScope(source) - modelField, ok := modelScope.FieldByName(sourceFieldName) - if !ok { - t.Fatalf(fmt.Sprintf("Failed to get field by name: %v", sourceFieldName)) - } - targetField, ok := targetScope.FieldByName(targetFieldName) - if !ok { - t.Fatalf(fmt.Sprintf("Failed to get field by name: %v", targetFieldName)) - } - dest := fmt.Sprintf("%v(%v)", targetTableName, targetField.DBName) - err := DB.Model(source).AddForeignKey(modelField.DBName, dest, "CASCADE", "CASCADE").Error - if err != nil { - t.Fatalf(fmt.Sprintf("Failed to create foreign key: %v", err)) - } -} - -func TestLongForeignKey(t *testing.T) { - testForeignKey(t, &NotSoLongTableName{}, "ReallyLongThingID", &ReallyLongTableNameToTestMySQLNameLengthLimit{}, "ID") -} - -func TestLongForeignKeyWithShortDest(t *testing.T) { - testForeignKey(t, &ReallyLongThingThatReferencesShort{}, "ShortID", &Short{}, "ID") -} - -func TestHasManyChildrenWithOneStruct(t *testing.T) { - category := Category{ - Name: "main", - Categories: []Category{ - {Name: "sub1"}, - {Name: "sub2"}, - }, - } - - DB.Save(&category) -} - -func TestSkipSaveAssociation(t *testing.T) { - type Company struct { - gorm.Model - Name string - } - - type User struct { - gorm.Model - Name string - CompanyID uint - Company Company `gorm:"save_associations:false"` - } - DB.AutoMigrate(&Company{}, &User{}) - - DB.Save(&User{Name: "jinzhu", Company: Company{Name: "skip_save_association"}}) - - if !DB.Where("name = ?", "skip_save_association").First(&Company{}).RecordNotFound() { - t.Errorf("Company skip_save_association should not been saved") - } -} diff --git a/vendor/github.com/jinzhu/gorm/callback_system_test.go b/vendor/github.com/jinzhu/gorm/callback_system_test.go deleted file mode 100644 index 13ca3f428305..000000000000 --- a/vendor/github.com/jinzhu/gorm/callback_system_test.go +++ /dev/null @@ -1,112 +0,0 @@ -package gorm - -import ( - "reflect" - "runtime" - "strings" - "testing" -) - -func equalFuncs(funcs []*func(s *Scope), fnames []string) bool { - var names []string - for _, f := range funcs { - fnames := strings.Split(runtime.FuncForPC(reflect.ValueOf(*f).Pointer()).Name(), ".") - names = append(names, fnames[len(fnames)-1]) - } - return reflect.DeepEqual(names, fnames) -} - -func create(s *Scope) {} -func beforeCreate1(s *Scope) {} -func beforeCreate2(s *Scope) {} -func afterCreate1(s *Scope) {} -func afterCreate2(s *Scope) {} - -func TestRegisterCallback(t *testing.T) { - var callback = &Callback{} - - callback.Create().Register("before_create1", beforeCreate1) - callback.Create().Register("before_create2", beforeCreate2) - callback.Create().Register("create", create) - callback.Create().Register("after_create1", afterCreate1) - callback.Create().Register("after_create2", afterCreate2) - - if !equalFuncs(callback.creates, []string{"beforeCreate1", "beforeCreate2", "create", "afterCreate1", "afterCreate2"}) { - t.Errorf("register callback") - } -} - -func TestRegisterCallbackWithOrder(t *testing.T) { - var callback1 = &Callback{} - callback1.Create().Register("before_create1", beforeCreate1) - callback1.Create().Register("create", create) - callback1.Create().Register("after_create1", afterCreate1) - callback1.Create().Before("after_create1").Register("after_create2", afterCreate2) - if !equalFuncs(callback1.creates, []string{"beforeCreate1", "create", "afterCreate2", "afterCreate1"}) { - t.Errorf("register callback with order") - } - - var callback2 = &Callback{} - - callback2.Update().Register("create", create) - callback2.Update().Before("create").Register("before_create1", beforeCreate1) - callback2.Update().After("after_create2").Register("after_create1", afterCreate1) - callback2.Update().Before("before_create1").Register("before_create2", beforeCreate2) - callback2.Update().Register("after_create2", afterCreate2) - - if !equalFuncs(callback2.updates, []string{"beforeCreate2", "beforeCreate1", "create", "afterCreate2", "afterCreate1"}) { - t.Errorf("register callback with order") - } -} - -func TestRegisterCallbackWithComplexOrder(t *testing.T) { - var callback1 = &Callback{} - - callback1.Query().Before("after_create1").After("before_create1").Register("create", create) - callback1.Query().Register("before_create1", beforeCreate1) - callback1.Query().Register("after_create1", afterCreate1) - - if !equalFuncs(callback1.queries, []string{"beforeCreate1", "create", "afterCreate1"}) { - t.Errorf("register callback with order") - } - - var callback2 = &Callback{} - - callback2.Delete().Before("after_create1").After("before_create1").Register("create", create) - callback2.Delete().Before("create").Register("before_create1", beforeCreate1) - callback2.Delete().After("before_create1").Register("before_create2", beforeCreate2) - callback2.Delete().Register("after_create1", afterCreate1) - callback2.Delete().After("after_create1").Register("after_create2", afterCreate2) - - if !equalFuncs(callback2.deletes, []string{"beforeCreate1", "beforeCreate2", "create", "afterCreate1", "afterCreate2"}) { - t.Errorf("register callback with order") - } -} - -func replaceCreate(s *Scope) {} - -func TestReplaceCallback(t *testing.T) { - var callback = &Callback{} - - callback.Create().Before("after_create1").After("before_create1").Register("create", create) - callback.Create().Register("before_create1", beforeCreate1) - callback.Create().Register("after_create1", afterCreate1) - callback.Create().Replace("create", replaceCreate) - - if !equalFuncs(callback.creates, []string{"beforeCreate1", "replaceCreate", "afterCreate1"}) { - t.Errorf("replace callback") - } -} - -func TestRemoveCallback(t *testing.T) { - var callback = &Callback{} - - callback.Create().Before("after_create1").After("before_create1").Register("create", create) - callback.Create().Register("before_create1", beforeCreate1) - callback.Create().Register("after_create1", afterCreate1) - callback.Create().Remove("create") - - if !equalFuncs(callback.creates, []string{"beforeCreate1", "afterCreate1"}) { - t.Errorf("remove callback") - } -} diff --git a/vendor/github.com/jinzhu/gorm/callbacks_test.go b/vendor/github.com/jinzhu/gorm/callbacks_test.go deleted file mode 100644 index a58913d767de..000000000000 --- a/vendor/github.com/jinzhu/gorm/callbacks_test.go +++ /dev/null @@ -1,177 +0,0 @@ -package gorm_test - -import ( - "errors" - - "github.com/jinzhu/gorm" - - "reflect" - "testing" -) - -func (s *Product) BeforeCreate() (err error) { - if s.Code == "Invalid" { - err = errors.New("invalid product") - } - s.BeforeCreateCallTimes = s.BeforeCreateCallTimes + 1 - return -} - -func (s *Product) BeforeUpdate() (err error) { - if s.Code == "dont_update" { - err = errors.New("can't update") - } - s.BeforeUpdateCallTimes = s.BeforeUpdateCallTimes + 1 - return -} - -func (s *Product) BeforeSave() (err error) { - if s.Code == "dont_save" { - err = errors.New("can't save") - } - s.BeforeSaveCallTimes = s.BeforeSaveCallTimes + 1 - return -} - -func (s *Product) AfterFind() { - s.AfterFindCallTimes = s.AfterFindCallTimes + 1 -} - -func (s *Product) AfterCreate(tx *gorm.DB) { - tx.Model(s).UpdateColumn(Product{AfterCreateCallTimes: s.AfterCreateCallTimes + 1}) -} - -func (s *Product) AfterUpdate() { - s.AfterUpdateCallTimes = s.AfterUpdateCallTimes + 1 -} - -func (s *Product) AfterSave() (err error) { - if s.Code == "after_save_error" { - err = errors.New("can't save") - } - s.AfterSaveCallTimes = s.AfterSaveCallTimes + 1 - return -} - -func (s *Product) BeforeDelete() (err error) { - if s.Code == "dont_delete" { - err = errors.New("can't delete") - } - s.BeforeDeleteCallTimes = s.BeforeDeleteCallTimes + 1 - return -} - -func (s *Product) AfterDelete() (err error) { - if s.Code == "after_delete_error" { - err = errors.New("can't delete") - } - s.AfterDeleteCallTimes = s.AfterDeleteCallTimes + 1 - return -} - -func (s *Product) GetCallTimes() []int64 { - return []int64{s.BeforeCreateCallTimes, s.BeforeSaveCallTimes, s.BeforeUpdateCallTimes, s.AfterCreateCallTimes, s.AfterSaveCallTimes, s.AfterUpdateCallTimes, s.BeforeDeleteCallTimes, s.AfterDeleteCallTimes, s.AfterFindCallTimes} -} - -func TestRunCallbacks(t *testing.T) { - p := Product{Code: "unique_code", Price: 100} - DB.Save(&p) - - if !reflect.DeepEqual(p.GetCallTimes(), []int64{1, 1, 0, 1, 1, 0, 0, 0, 0}) { - t.Errorf("Callbacks should be invoked successfully, %v", p.GetCallTimes()) - } - - DB.Where("Code = ?", "unique_code").First(&p) - if !reflect.DeepEqual(p.GetCallTimes(), []int64{1, 1, 0, 1, 0, 0, 0, 0, 1}) { - t.Errorf("After callbacks values are not saved, %v", p.GetCallTimes()) - } - - p.Price = 200 - DB.Save(&p) - if !reflect.DeepEqual(p.GetCallTimes(), []int64{1, 2, 1, 1, 1, 1, 0, 0, 1}) { - t.Errorf("After update callbacks should be invoked successfully, %v", p.GetCallTimes()) - } - - var products []Product - DB.Find(&products, "code = ?", "unique_code") - if products[0].AfterFindCallTimes != 2 { - t.Errorf("AfterFind callbacks should work with slice") - } - - DB.Where("Code = ?", "unique_code").First(&p) - if !reflect.DeepEqual(p.GetCallTimes(), []int64{1, 2, 1, 1, 0, 0, 0, 0, 2}) { - t.Errorf("After update callbacks values are not saved, %v", p.GetCallTimes()) - } - - DB.Delete(&p) - if !reflect.DeepEqual(p.GetCallTimes(), []int64{1, 2, 1, 1, 0, 0, 1, 1, 2}) { - t.Errorf("After delete callbacks should be invoked successfully, %v", p.GetCallTimes()) - } - - if DB.Where("Code = ?", "unique_code").First(&p).Error == nil { - t.Errorf("Can't find a deleted record") - } -} - -func TestCallbacksWithErrors(t *testing.T) { - p := Product{Code: "Invalid", Price: 100} - if DB.Save(&p).Error == nil { - t.Errorf("An error from before create callbacks happened when create with invalid value") - } - - if DB.Where("code = ?", "Invalid").First(&Product{}).Error == nil { - t.Errorf("Should not save record that have errors") - } - - if DB.Save(&Product{Code: "dont_save", Price: 100}).Error == nil { - t.Errorf("An error from after create callbacks happened when create with invalid value") - } - - p2 := Product{Code: "update_callback", Price: 100} - DB.Save(&p2) - - p2.Code = "dont_update" - if DB.Save(&p2).Error == nil { - t.Errorf("An error from before update callbacks happened when update with invalid value") - } - - if DB.Where("code = ?", "update_callback").First(&Product{}).Error != nil { - t.Errorf("Record Should not be updated due to errors happened in before update callback") - } - - if DB.Where("code = ?", "dont_update").First(&Product{}).Error == nil { - t.Errorf("Record Should not be updated due to errors happened in before update callback") - } - - p2.Code = "dont_save" - if DB.Save(&p2).Error == nil { - t.Errorf("An error from before save callbacks happened when update with invalid value") - } - - p3 := Product{Code: "dont_delete", Price: 100} - DB.Save(&p3) - if DB.Delete(&p3).Error == nil { - t.Errorf("An error from before delete callbacks happened when delete") - } - - if DB.Where("Code = ?", "dont_delete").First(&p3).Error != nil { - t.Errorf("An error from before delete callbacks happened") - } - - p4 := Product{Code: "after_save_error", Price: 100} - DB.Save(&p4) - if err := DB.First(&Product{}, "code = ?", "after_save_error").Error; err == nil { - t.Errorf("Record should be reverted if get an error in after save callback") - } - - p5 := Product{Code: "after_delete_error", Price: 100} - DB.Save(&p5) - if err := DB.First(&Product{}, "code = ?", "after_delete_error").Error; err != nil { - t.Errorf("Record should be found") - } - - DB.Delete(&p5) - if err := DB.First(&Product{}, "code = ?", "after_delete_error").Error; err != nil { - t.Errorf("Record shouldn't be deleted because of an error happened in after delete callback") - } -} diff --git a/vendor/github.com/jinzhu/gorm/create_test.go b/vendor/github.com/jinzhu/gorm/create_test.go deleted file mode 100644 index d67d34fc782a..000000000000 --- a/vendor/github.com/jinzhu/gorm/create_test.go +++ /dev/null @@ -1,180 +0,0 @@ -package gorm_test - -import ( - "os" - "reflect" - "testing" - "time" -) - -func TestCreate(t *testing.T) { - float := 35.03554004971999 - now := time.Now() - user := User{Name: "CreateUser", Age: 18, Birthday: &now, UserNum: Num(111), PasswordHash: []byte{'f', 'a', 'k', '4'}, Latitude: float} - - if !DB.NewRecord(user) || !DB.NewRecord(&user) { - t.Error("User should be new record before create") - } - - if count := DB.Save(&user).RowsAffected; count != 1 { - t.Error("There should be one record be affected when create record") - } - - if DB.NewRecord(user) || DB.NewRecord(&user) { - t.Error("User should not new record after save") - } - - var newUser User - DB.First(&newUser, user.Id) - - if !reflect.DeepEqual(newUser.PasswordHash, []byte{'f', 'a', 'k', '4'}) { - t.Errorf("User's PasswordHash should be saved ([]byte)") - } - - if newUser.Age != 18 { - t.Errorf("User's Age should be saved (int)") - } - - if newUser.UserNum != Num(111) { - t.Errorf("User's UserNum should be saved (custom type)") - } - - if newUser.Latitude != float { - t.Errorf("Float64 should not be changed after save") - } - - if user.CreatedAt.IsZero() { - t.Errorf("Should have created_at after create") - } - - if newUser.CreatedAt.IsZero() { - t.Errorf("Should have created_at after create") - } - - DB.Model(user).Update("name", "create_user_new_name") - DB.First(&user, user.Id) - if user.CreatedAt.Format(time.RFC3339Nano) != newUser.CreatedAt.Format(time.RFC3339Nano) { - t.Errorf("CreatedAt should not be changed after update") - } -} - -func TestCreateWithAutoIncrement(t *testing.T) { - if dialect := os.Getenv("GORM_DIALECT"); dialect != "postgres" { - t.Skip("Skipping this because only postgres properly support auto_increment on a non-primary_key column") - } - user1 := User{} - user2 := User{} - - DB.Create(&user1) - DB.Create(&user2) - - if user2.Sequence-user1.Sequence != 1 { - t.Errorf("Auto increment should apply on Sequence") - } -} - -func TestCreateWithNoGORMPrimayKey(t *testing.T) { - if dialect := os.Getenv("GORM_DIALECT"); dialect == "mssql" { - t.Skip("Skipping this because MSSQL will return identity only if the table has an Id column") - } - - jt := JoinTable{From: 1, To: 2} - err := DB.Create(&jt).Error - if err != nil { - t.Errorf("No error should happen when create a record without a GORM primary key. But in the database this primary key exists and is the union of 2 or more fields\n But got: %s", err) - } -} - -func TestCreateWithNoStdPrimaryKeyAndDefaultValues(t *testing.T) { - animal := Animal{Name: "Ferdinand"} - if DB.Save(&animal).Error != nil { - t.Errorf("No error should happen when create a record without std primary key") - } - - if animal.Counter == 0 { - t.Errorf("No std primary key should be filled value after create") - } - - if animal.Name != "Ferdinand" { - t.Errorf("Default value should be overrided") - } - - // Test create with default value not overrided - an := Animal{From: "nerdz"} - - if DB.Save(&an).Error != nil { - t.Errorf("No error should happen when create an record without std primary key") - } - - // We must fetch the value again, to have the default fields updated - // (We can't do this in the update statements, since sql default can be expressions - // And be different from the fields' type (eg. a time.Time fields has a default value of "now()" - DB.Model(Animal{}).Where(&Animal{Counter: an.Counter}).First(&an) - - if an.Name != "galeone" { - t.Errorf("Default value should fill the field. But got %v", an.Name) - } -} - -func TestAnonymousScanner(t *testing.T) { - user := User{Name: "anonymous_scanner", Role: Role{Name: "admin"}} - DB.Save(&user) - - var user2 User - DB.First(&user2, "name = ?", "anonymous_scanner") - if user2.Role.Name != "admin" { - t.Errorf("Should be able to get anonymous scanner") - } - - if !user2.IsAdmin() { - t.Errorf("Should be able to get anonymous scanner") - } -} - -func TestAnonymousField(t *testing.T) { - user := User{Name: "anonymous_field", Company: Company{Name: "company"}} - DB.Save(&user) - - var user2 User - DB.First(&user2, "name = ?", "anonymous_field") - DB.Model(&user2).Related(&user2.Company) - if user2.Company.Name != "company" { - t.Errorf("Should be able to get anonymous field") - } -} - -func TestSelectWithCreate(t *testing.T) { - user := getPreparedUser("select_user", "select_with_create") - DB.Select("Name", "BillingAddress", "CreditCard", "Company", "Emails").Create(user) - - var queryuser User - DB.Preload("BillingAddress").Preload("ShippingAddress"). - Preload("CreditCard").Preload("Emails").Preload("Company").First(&queryuser, user.Id) - - if queryuser.Name != user.Name || queryuser.Age == user.Age { - t.Errorf("Should only create users with name column") - } - - if queryuser.BillingAddressID.Int64 == 0 || queryuser.ShippingAddressId != 0 || - queryuser.CreditCard.ID == 0 || len(queryuser.Emails) == 0 { - t.Errorf("Should only create selected relationships") - } -} - -func TestOmitWithCreate(t *testing.T) { - user := getPreparedUser("omit_user", "omit_with_create") - DB.Omit("Name", "BillingAddress", "CreditCard", "Company", "Emails").Create(user) - - var queryuser User - DB.Preload("BillingAddress").Preload("ShippingAddress"). - Preload("CreditCard").Preload("Emails").Preload("Company").First(&queryuser, user.Id) - - if queryuser.Name == user.Name || queryuser.Age != user.Age { - t.Errorf("Should only create users with age column") - } - - if queryuser.BillingAddressID.Int64 != 0 || queryuser.ShippingAddressId == 0 || - queryuser.CreditCard.ID != 0 || len(queryuser.Emails) != 0 { - t.Errorf("Should not create omitted relationships") - } -} diff --git a/vendor/github.com/jinzhu/gorm/customize_column_test.go b/vendor/github.com/jinzhu/gorm/customize_column_test.go deleted file mode 100644 index ddb536b870c8..000000000000 --- a/vendor/github.com/jinzhu/gorm/customize_column_test.go +++ /dev/null @@ -1,281 +0,0 @@ -package gorm_test - -import ( - "testing" - "time" - - "github.com/jinzhu/gorm" -) - -type CustomizeColumn struct { - ID int64 `gorm:"column:mapped_id; primary_key:yes"` - Name string `gorm:"column:mapped_name"` - Date *time.Time `gorm:"column:mapped_time"` -} - -// Make sure an ignored field does not interfere with another field's custom -// column name that matches the ignored field. -type CustomColumnAndIgnoredFieldClash struct { - Body string `sql:"-"` - RawBody string `gorm:"column:body"` -} - -func TestCustomizeColumn(t *testing.T) { - col := "mapped_name" - DB.DropTable(&CustomizeColumn{}) - DB.AutoMigrate(&CustomizeColumn{}) - - scope := DB.NewScope(&CustomizeColumn{}) - if !scope.Dialect().HasColumn(scope.TableName(), col) { - t.Errorf("CustomizeColumn should have column %s", col) - } - - col = "mapped_id" - if scope.PrimaryKey() != col { - t.Errorf("CustomizeColumn should have primary key %s, but got %q", col, scope.PrimaryKey()) - } - - expected := "foo" - now := time.Now() - cc := CustomizeColumn{ID: 666, Name: expected, Date: &now} - - if count := DB.Create(&cc).RowsAffected; count != 1 { - t.Error("There should be one record be affected when create record") - } - - var cc1 CustomizeColumn - DB.First(&cc1, 666) - - if cc1.Name != expected { - t.Errorf("Failed to query CustomizeColumn") - } - - cc.Name = "bar" - DB.Save(&cc) - - var cc2 CustomizeColumn - DB.First(&cc2, 666) - if cc2.Name != "bar" { - t.Errorf("Failed to query CustomizeColumn") - } -} - -func TestCustomColumnAndIgnoredFieldClash(t *testing.T) { - DB.DropTable(&CustomColumnAndIgnoredFieldClash{}) - if err := DB.AutoMigrate(&CustomColumnAndIgnoredFieldClash{}).Error; err != nil { - t.Errorf("Should not raise error: %s", err) - } -} - -type CustomizePerson struct { - IdPerson string `gorm:"column:idPerson;primary_key:true"` - Accounts []CustomizeAccount `gorm:"many2many:PersonAccount;associationforeignkey:idAccount;foreignkey:idPerson"` -} - -type CustomizeAccount struct { - IdAccount string `gorm:"column:idAccount;primary_key:true"` - Name string -} - -func TestManyToManyWithCustomizedColumn(t *testing.T) { - DB.DropTable(&CustomizePerson{}, &CustomizeAccount{}, "PersonAccount") - DB.AutoMigrate(&CustomizePerson{}, &CustomizeAccount{}) - - account := CustomizeAccount{IdAccount: "account", Name: "id1"} - person := CustomizePerson{ - IdPerson: "person", - Accounts: []CustomizeAccount{account}, - } - - if err := DB.Create(&account).Error; err != nil { - t.Errorf("no error should happen, but got %v", err) - } - - if err := DB.Create(&person).Error; err != nil { - t.Errorf("no error should happen, but got %v", err) - } - - var person1 CustomizePerson - scope := DB.NewScope(nil) - if err := DB.Preload("Accounts").First(&person1, scope.Quote("idPerson")+" = ?", person.IdPerson).Error; err != nil { - t.Errorf("no error should happen when preloading customized column many2many relations, but got %v", err) - } - - if len(person1.Accounts) != 1 || person1.Accounts[0].IdAccount != "account" { - t.Errorf("should preload correct accounts") - } -} - -type CustomizeUser struct { - gorm.Model - Email string `sql:"column:email_address"` -} - -type CustomizeInvitation struct { - gorm.Model - Address string `sql:"column:invitation"` - Person *CustomizeUser `gorm:"foreignkey:Email;associationforeignkey:invitation"` -} - -func TestOneToOneWithCustomizedColumn(t *testing.T) { - DB.DropTable(&CustomizeUser{}, &CustomizeInvitation{}) - DB.AutoMigrate(&CustomizeUser{}, &CustomizeInvitation{}) - - user := CustomizeUser{ - Email: "hello@example.com", - } - invitation := CustomizeInvitation{ - Address: "hello@example.com", - } - - DB.Create(&user) - DB.Create(&invitation) - - var invitation2 CustomizeInvitation - if err := DB.Preload("Person").Find(&invitation2, invitation.ID).Error; err != nil { - t.Errorf("no error should happen, but got %v", err) - } - - if invitation2.Person.Email != user.Email { - t.Errorf("Should preload one to one relation with customize foreign keys") - } -} - -type PromotionDiscount struct { - gorm.Model - Name string - Coupons []*PromotionCoupon `gorm:"ForeignKey:discount_id"` - Rule *PromotionRule `gorm:"ForeignKey:discount_id"` - Benefits []PromotionBenefit `gorm:"ForeignKey:promotion_id"` -} - -type PromotionBenefit struct { - gorm.Model - Name string - PromotionID uint - Discount PromotionDiscount `gorm:"ForeignKey:promotion_id"` -} - -type PromotionCoupon struct { - gorm.Model - Code string - DiscountID uint - Discount PromotionDiscount -} - -type PromotionRule struct { - gorm.Model - Name string - Begin *time.Time - End *time.Time - DiscountID uint - Discount *PromotionDiscount -} - -func TestOneToManyWithCustomizedColumn(t *testing.T) { - DB.DropTable(&PromotionDiscount{}, &PromotionCoupon{}) - DB.AutoMigrate(&PromotionDiscount{}, &PromotionCoupon{}) - - discount := PromotionDiscount{ - Name: "Happy New Year", - Coupons: []*PromotionCoupon{ - {Code: "newyear1"}, - {Code: "newyear2"}, - }, - } - - if err := DB.Create(&discount).Error; err != nil { - t.Errorf("no error should happen but got %v", err) - } - - var discount1 PromotionDiscount - if err := DB.Preload("Coupons").First(&discount1, "id = ?", discount.ID).Error; err != nil { - t.Errorf("no error should happen but got %v", err) - } - - if len(discount.Coupons) != 2 { - t.Errorf("should find two coupons") - } - - var coupon PromotionCoupon - if err := DB.Preload("Discount").First(&coupon, "code = ?", "newyear1").Error; err != nil { - t.Errorf("no error should happen but got %v", err) - } - - if coupon.Discount.Name != "Happy New Year" { - t.Errorf("should preload discount from coupon") - } -} - -func TestHasOneWithPartialCustomizedColumn(t *testing.T) { - DB.DropTable(&PromotionDiscount{}, &PromotionRule{}) - DB.AutoMigrate(&PromotionDiscount{}, &PromotionRule{}) - - var begin = time.Now() - var end = time.Now().Add(24 * time.Hour) - discount := PromotionDiscount{ - Name: "Happy New Year 2", - Rule: &PromotionRule{ - Name: "time_limited", - Begin: &begin, - End: &end, - }, - } - - if err := DB.Create(&discount).Error; err != nil { - t.Errorf("no error should happen but got %v", err) - } - - var discount1 PromotionDiscount - if err := DB.Preload("Rule").First(&discount1, "id = ?", discount.ID).Error; err != nil { - t.Errorf("no error should happen but got %v", err) - } - - if discount.Rule.Begin.Format(time.RFC3339Nano) != begin.Format(time.RFC3339Nano) { - t.Errorf("Should be able to preload Rule") - } - - var rule PromotionRule - if err := DB.Preload("Discount").First(&rule, "name = ?", "time_limited").Error; err != nil { - t.Errorf("no error should happen but got %v", err) - } - - if rule.Discount.Name != "Happy New Year 2" { - t.Errorf("should preload discount from rule") - } -} - -func TestBelongsToWithPartialCustomizedColumn(t *testing.T) { - DB.DropTable(&PromotionDiscount{}, &PromotionBenefit{}) - DB.AutoMigrate(&PromotionDiscount{}, &PromotionBenefit{}) - - discount := PromotionDiscount{ - Name: "Happy New Year 3", - Benefits: []PromotionBenefit{ - {Name: "free cod"}, - {Name: "free shipping"}, - }, - } - - if err := DB.Create(&discount).Error; err != nil { - t.Errorf("no error should happen but got %v", err) - } - - var discount1 PromotionDiscount - if err := DB.Preload("Benefits").First(&discount1, "id = ?", discount.ID).Error; err != nil { - t.Errorf("no error should happen but got %v", err) - } - - if len(discount.Benefits) != 2 { - t.Errorf("should find two benefits") - } - - var benefit PromotionBenefit - if err := DB.Preload("Discount").First(&benefit, "name = ?", "free cod").Error; err != nil { - t.Errorf("no error should happen but got %v", err) - } - - if benefit.Discount.Name != "Happy New Year 3" { - t.Errorf("should preload discount from coupon") - } -} diff --git a/vendor/github.com/jinzhu/gorm/delete_test.go b/vendor/github.com/jinzhu/gorm/delete_test.go deleted file mode 100644 index 043641f70e09..000000000000 --- a/vendor/github.com/jinzhu/gorm/delete_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package gorm_test - -import ( - "testing" - "time" -) - -func TestDelete(t *testing.T) { - user1, user2 := User{Name: "delete1"}, User{Name: "delete2"} - DB.Save(&user1) - DB.Save(&user2) - - if err := DB.Delete(&user1).Error; err != nil { - t.Errorf("No error should happen when delete a record, err=%s", err) - } - - if !DB.Where("name = ?", user1.Name).First(&User{}).RecordNotFound() { - t.Errorf("User can't be found after delete") - } - - if DB.Where("name = ?", user2.Name).First(&User{}).RecordNotFound() { - t.Errorf("Other users that not deleted should be found-able") - } -} - -func TestInlineDelete(t *testing.T) { - user1, user2 := User{Name: "inline_delete1"}, User{Name: "inline_delete2"} - DB.Save(&user1) - DB.Save(&user2) - - if DB.Delete(&User{}, user1.Id).Error != nil { - t.Errorf("No error should happen when delete a record") - } else if !DB.Where("name = ?", user1.Name).First(&User{}).RecordNotFound() { - t.Errorf("User can't be found after delete") - } - - if err := DB.Delete(&User{}, "name = ?", user2.Name).Error; err != nil { - t.Errorf("No error should happen when delete a record, err=%s", err) - } else if !DB.Where("name = ?", user2.Name).First(&User{}).RecordNotFound() { - t.Errorf("User can't be found after delete") - } -} - -func TestSoftDelete(t *testing.T) { - type User struct { - Id int64 - Name string - DeletedAt *time.Time - } - DB.AutoMigrate(&User{}) - - user := User{Name: "soft_delete"} - DB.Save(&user) - DB.Delete(&user) - - if DB.First(&User{}, "name = ?", user.Name).Error == nil { - t.Errorf("Can't find a soft deleted record") - } - - if err := DB.Unscoped().First(&User{}, "name = ?", user.Name).Error; err != nil { - t.Errorf("Should be able to find soft deleted record with Unscoped, but err=%s", err) - } - - DB.Unscoped().Delete(&user) - if !DB.Unscoped().First(&User{}, "name = ?", user.Name).RecordNotFound() { - t.Errorf("Can't find permanently deleted record") - } -} - -func TestSoftDeleteWithCustomizedDeletedAtColumnName(t *testing.T) { - creditCard := CreditCard{Number: "411111111234567"} - DB.Save(&creditCard) - DB.Delete(&creditCard) - - if deletedAtField, ok := DB.NewScope(&CreditCard{}).FieldByName("DeletedAt"); !ok || deletedAtField.DBName != "deleted_time" { - t.Errorf("CreditCard's DeletedAt's column name should be `deleted_time`") - } - - if DB.First(&CreditCard{}, "number = ?", creditCard.Number).Error == nil { - t.Errorf("Can't find a soft deleted record") - } - - if err := DB.Unscoped().First(&CreditCard{}, "number = ?", creditCard.Number).Error; err != nil { - t.Errorf("Should be able to find soft deleted record with Unscoped, but err=%s", err) - } - - DB.Unscoped().Delete(&creditCard) - if !DB.Unscoped().First(&CreditCard{}, "number = ?", creditCard.Number).RecordNotFound() { - t.Errorf("Can't find permanently deleted record") - } -} diff --git a/vendor/github.com/jinzhu/gorm/embedded_struct_test.go b/vendor/github.com/jinzhu/gorm/embedded_struct_test.go deleted file mode 100644 index 91dd05633df8..000000000000 --- a/vendor/github.com/jinzhu/gorm/embedded_struct_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package gorm_test - -import "testing" - -type BasePost struct { - Id int64 - Title string - URL string -} - -type Author struct { - ID string - Name string - Email string -} - -type HNPost struct { - BasePost - Author `gorm:"embedded_prefix:user_"` // Embedded struct - Upvotes int32 -} - -type EngadgetPost struct { - BasePost BasePost `gorm:"embedded"` - Author Author `gorm:"embedded;embedded_prefix:author_"` // Embedded struct - ImageUrl string -} - -func TestPrefixColumnNameForEmbeddedStruct(t *testing.T) { - dialect := DB.NewScope(&EngadgetPost{}).Dialect() - engadgetPostScope := DB.NewScope(&EngadgetPost{}) - if !dialect.HasColumn(engadgetPostScope.TableName(), "author_id") || !dialect.HasColumn(engadgetPostScope.TableName(), "author_name") || !dialect.HasColumn(engadgetPostScope.TableName(), "author_email") { - t.Errorf("should has prefix for embedded columns") - } - - if len(engadgetPostScope.PrimaryFields()) != 1 { - t.Errorf("should have only one primary field with embedded struct, but got %v", len(engadgetPostScope.PrimaryFields())) - } - - hnScope := DB.NewScope(&HNPost{}) - if !dialect.HasColumn(hnScope.TableName(), "user_id") || !dialect.HasColumn(hnScope.TableName(), "user_name") || !dialect.HasColumn(hnScope.TableName(), "user_email") { - t.Errorf("should has prefix for embedded columns") - } -} - -func TestSaveAndQueryEmbeddedStruct(t *testing.T) { - DB.Save(&HNPost{BasePost: BasePost{Title: "news"}}) - DB.Save(&HNPost{BasePost: BasePost{Title: "hn_news"}}) - var news HNPost - if err := DB.First(&news, "title = ?", "hn_news").Error; err != nil { - t.Errorf("no error should happen when query with embedded struct, but got %v", err) - } else if news.Title != "hn_news" { - t.Errorf("embedded struct's value should be scanned correctly") - } - - DB.Save(&EngadgetPost{BasePost: BasePost{Title: "engadget_news"}}) - var egNews EngadgetPost - if err := DB.First(&egNews, "title = ?", "engadget_news").Error; err != nil { - t.Errorf("no error should happen when query with embedded struct, but got %v", err) - } else if egNews.BasePost.Title != "engadget_news" { - t.Errorf("embedded struct's value should be scanned correctly") - } - - if DB.NewScope(&HNPost{}).PrimaryField() == nil { - t.Errorf("primary key with embedded struct should works") - } - - for _, field := range DB.NewScope(&HNPost{}).Fields() { - if field.Name == "BasePost" { - t.Errorf("scope Fields should not contain embedded struct") - } - } -} diff --git a/vendor/github.com/jinzhu/gorm/errors_test.go b/vendor/github.com/jinzhu/gorm/errors_test.go deleted file mode 100644 index 9a428dec01fb..000000000000 --- a/vendor/github.com/jinzhu/gorm/errors_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package gorm_test - -import ( - "errors" - "testing" - - "github.com/jinzhu/gorm" -) - -func TestErrorsCanBeUsedOutsideGorm(t *testing.T) { - errs := []error{errors.New("First"), errors.New("Second")} - - gErrs := gorm.Errors(errs) - gErrs = gErrs.Add(errors.New("Third")) - gErrs = gErrs.Add(gErrs) - - if gErrs.Error() != "First; Second; Third" { - t.Fatalf("Gave wrong error, got %s", gErrs.Error()) - } -} diff --git a/vendor/github.com/jinzhu/gorm/field_test.go b/vendor/github.com/jinzhu/gorm/field_test.go deleted file mode 100644 index 30e9a778d209..000000000000 --- a/vendor/github.com/jinzhu/gorm/field_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package gorm_test - -import ( - "testing" - - "github.com/jinzhu/gorm" -) - -type CalculateField struct { - gorm.Model - Name string - Children []CalculateFieldChild - Category CalculateFieldCategory - EmbeddedField -} - -type EmbeddedField struct { - EmbeddedName string `sql:"NOT NULL;DEFAULT:'hello'"` -} - -type CalculateFieldChild struct { - gorm.Model - CalculateFieldID uint - Name string -} - -type CalculateFieldCategory struct { - gorm.Model - CalculateFieldID uint - Name string -} - -func TestCalculateField(t *testing.T) { - var field CalculateField - var scope = DB.NewScope(&field) - if field, ok := scope.FieldByName("Children"); !ok || field.Relationship == nil { - t.Errorf("Should calculate fields correctly for the first time") - } - - if field, ok := scope.FieldByName("Category"); !ok || field.Relationship == nil { - t.Errorf("Should calculate fields correctly for the first time") - } - - if field, ok := scope.FieldByName("embedded_name"); !ok { - t.Errorf("should find embedded field") - } else if _, ok := field.TagSettings["NOT NULL"]; !ok { - t.Errorf("should find embedded field's tag settings") - } -} diff --git a/vendor/github.com/jinzhu/gorm/join_table_test.go b/vendor/github.com/jinzhu/gorm/join_table_test.go deleted file mode 100644 index 1a83a9c87034..000000000000 --- a/vendor/github.com/jinzhu/gorm/join_table_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package gorm_test - -import ( - "fmt" - "testing" - "time" - - "github.com/jinzhu/gorm" -) - -type Person struct { - Id int - Name string - Addresses []*Address `gorm:"many2many:person_addresses;"` -} - -type PersonAddress struct { - gorm.JoinTableHandler - PersonID int - AddressID int - DeletedAt *time.Time - CreatedAt time.Time -} - -func (*PersonAddress) Add(handler gorm.JoinTableHandlerInterface, db *gorm.DB, foreignValue interface{}, associationValue interface{}) error { - return db.Where(map[string]interface{}{ - "person_id": db.NewScope(foreignValue).PrimaryKeyValue(), - "address_id": db.NewScope(associationValue).PrimaryKeyValue(), - }).Assign(map[string]interface{}{ - "person_id": foreignValue, - "address_id": associationValue, - "deleted_at": gorm.Expr("NULL"), - }).FirstOrCreate(&PersonAddress{}).Error -} - -func (*PersonAddress) Delete(handler gorm.JoinTableHandlerInterface, db *gorm.DB, sources ...interface{}) error { - return db.Delete(&PersonAddress{}).Error -} - -func (pa *PersonAddress) JoinWith(handler gorm.JoinTableHandlerInterface, db *gorm.DB, source interface{}) *gorm.DB { - table := pa.Table(db) - return db.Joins("INNER JOIN person_addresses ON person_addresses.address_id = addresses.id").Where(fmt.Sprintf("%v.deleted_at IS NULL OR %v.deleted_at <= '0001-01-02'", table, table)) -} - -func TestJoinTable(t *testing.T) { - DB.Exec("drop table person_addresses;") - DB.AutoMigrate(&Person{}) - DB.SetJoinTableHandler(&Person{}, "Addresses", &PersonAddress{}) - - address1 := &Address{Address1: "address 1"} - address2 := &Address{Address1: "address 2"} - person := &Person{Name: "person", Addresses: []*Address{address1, address2}} - DB.Save(person) - - DB.Model(person).Association("Addresses").Delete(address1) - - if DB.Find(&[]PersonAddress{}, "person_id = ?", person.Id).RowsAffected != 1 { - t.Errorf("Should found one address") - } - - if DB.Model(person).Association("Addresses").Count() != 1 { - t.Errorf("Should found one address") - } - - if DB.Unscoped().Find(&[]PersonAddress{}, "person_id = ?", person.Id).RowsAffected != 2 { - t.Errorf("Found two addresses with Unscoped") - } - - if DB.Model(person).Association("Addresses").Clear(); DB.Model(person).Association("Addresses").Count() != 0 { - t.Errorf("Should deleted all addresses") - } -} diff --git a/vendor/github.com/jinzhu/gorm/main_test.go b/vendor/github.com/jinzhu/gorm/main_test.go deleted file mode 100644 index f76988d2aea6..000000000000 --- a/vendor/github.com/jinzhu/gorm/main_test.go +++ /dev/null @@ -1,860 +0,0 @@ -package gorm_test - -import ( - "database/sql" - "database/sql/driver" - "fmt" - "os" - "path/filepath" - "reflect" - "strconv" - "testing" - "time" - - "github.com/erikstmartin/go-testdb" - "github.com/jinzhu/gorm" - _ "github.com/jinzhu/gorm/dialects/mssql" - _ "github.com/jinzhu/gorm/dialects/mysql" - "github.com/jinzhu/gorm/dialects/postgres" - _ "github.com/jinzhu/gorm/dialects/sqlite" - "github.com/jinzhu/now" -) - -var ( - DB *gorm.DB - t1, t2, t3, t4, t5 time.Time -) - -func init() { - var err error - - if DB, err = OpenTestConnection(); err != nil { - panic(fmt.Sprintf("No error should happen when connecting to test database, but got err=%+v", err)) - } - - runMigration() -} - -func OpenTestConnection() (db *gorm.DB, err error) { - switch os.Getenv("GORM_DIALECT") { - case "mysql": - // CREATE USER 'gorm'@'localhost' IDENTIFIED BY 'gorm'; - // CREATE DATABASE gorm; - // GRANT ALL ON gorm.* TO 'gorm'@'localhost'; - fmt.Println("testing mysql...") - dbhost := os.Getenv("GORM_DBADDRESS") - if dbhost != "" { - dbhost = fmt.Sprintf("tcp(%v)", dbhost) - } - db, err = gorm.Open("mysql", fmt.Sprintf("gorm:gorm@%v/gorm?charset=utf8&parseTime=True", dbhost)) - case "postgres": - fmt.Println("testing postgres...") - dbhost := os.Getenv("GORM_DBHOST") - if dbhost != "" { - dbhost = fmt.Sprintf("host=%v ", dbhost) - } - db, err = gorm.Open("postgres", fmt.Sprintf("%vuser=gorm password=gorm DB.name=gorm sslmode=disable", dbhost)) - case "foundation": - fmt.Println("testing foundation...") - db, err = gorm.Open("foundation", "dbname=gorm port=15432 sslmode=disable") - case "mssql": - fmt.Println("testing mssql...") - db, err = gorm.Open("mssql", "server=SERVER_HERE;database=rogue;user id=USER_HERE;password=PW_HERE;port=1433") - default: - fmt.Println("testing sqlite3...") - db, err = gorm.Open("sqlite3", filepath.Join(os.TempDir(), "gorm.db")) - } - - // db.SetLogger(Logger{log.New(os.Stdout, "\r\n", 0)}) - // db.SetLogger(log.New(os.Stdout, "\r\n", 0)) - if os.Getenv("DEBUG") == "true" { - db.LogMode(true) - } - - db.DB().SetMaxIdleConns(10) - - return -} - -func TestStringPrimaryKey(t *testing.T) { - type UUIDStruct struct { - ID string `gorm:"primary_key"` - Name string - } - DB.DropTable(&UUIDStruct{}) - DB.AutoMigrate(&UUIDStruct{}) - - data := UUIDStruct{ID: "uuid", Name: "hello"} - if err := DB.Save(&data).Error; err != nil || data.ID != "uuid" || data.Name != "hello" { - t.Errorf("string primary key should not be populated") - } - - data = UUIDStruct{ID: "uuid", Name: "hello world"} - if err := DB.Save(&data).Error; err != nil || data.ID != "uuid" || data.Name != "hello world" { - t.Errorf("string primary key should not be populated") - } -} - -func TestExceptionsWithInvalidSql(t *testing.T) { - var columns []string - if DB.Where("sdsd.zaaa = ?", "sd;;;aa").Pluck("aaa", &columns).Error == nil { - t.Errorf("Should got error with invalid SQL") - } - - if DB.Model(&User{}).Where("sdsd.zaaa = ?", "sd;;;aa").Pluck("aaa", &columns).Error == nil { - t.Errorf("Should got error with invalid SQL") - } - - if DB.Where("sdsd.zaaa = ?", "sd;;;aa").Find(&User{}).Error == nil { - t.Errorf("Should got error with invalid SQL") - } - - var count1, count2 int64 - DB.Model(&User{}).Count(&count1) - if count1 <= 0 { - t.Errorf("Should find some users") - } - - if DB.Where("name = ?", "jinzhu; delete * from users").First(&User{}).Error == nil { - t.Errorf("Should got error with invalid SQL") - } - - DB.Model(&User{}).Count(&count2) - if count1 != count2 { - t.Errorf("No user should not be deleted by invalid SQL") - } -} - -func TestSetTable(t *testing.T) { - DB.Create(getPreparedUser("pluck_user1", "pluck_user")) - DB.Create(getPreparedUser("pluck_user2", "pluck_user")) - DB.Create(getPreparedUser("pluck_user3", "pluck_user")) - - if err := DB.Table("users").Where("role = ?", "pluck_user").Pluck("age", &[]int{}).Error; err != nil { - t.Error("No errors should happen if set table for pluck", err) - } - - var users []User - if DB.Table("users").Find(&[]User{}).Error != nil { - t.Errorf("No errors should happen if set table for find") - } - - if DB.Table("invalid_table").Find(&users).Error == nil { - t.Errorf("Should got error when table is set to an invalid table") - } - - DB.Exec("drop table deleted_users;") - if DB.Table("deleted_users").CreateTable(&User{}).Error != nil { - t.Errorf("Create table with specified table") - } - - DB.Table("deleted_users").Save(&User{Name: "DeletedUser"}) - - var deletedUsers []User - DB.Table("deleted_users").Find(&deletedUsers) - if len(deletedUsers) != 1 { - t.Errorf("Query from specified table") - } - - DB.Save(getPreparedUser("normal_user", "reset_table")) - DB.Table("deleted_users").Save(getPreparedUser("deleted_user", "reset_table")) - var user1, user2, user3 User - DB.Where("role = ?", "reset_table").First(&user1).Table("deleted_users").First(&user2).Table("").First(&user3) - if (user1.Name != "normal_user") || (user2.Name != "deleted_user") || (user3.Name != "normal_user") { - t.Errorf("unset specified table with blank string") - } -} - -type Order struct { -} - -type Cart struct { -} - -func (c Cart) TableName() string { - return "shopping_cart" -} - -func TestHasTable(t *testing.T) { - type Foo struct { - Id int - Stuff string - } - DB.DropTable(&Foo{}) - - // Table should not exist at this point, HasTable should return false - if ok := DB.HasTable("foos"); ok { - t.Errorf("Table should not exist, but does") - } - if ok := DB.HasTable(&Foo{}); ok { - t.Errorf("Table should not exist, but does") - } - - // We create the table - if err := DB.CreateTable(&Foo{}).Error; err != nil { - t.Errorf("Table should be created") - } - - // And now it should exits, and HasTable should return true - if ok := DB.HasTable("foos"); !ok { - t.Errorf("Table should exist, but HasTable informs it does not") - } - if ok := DB.HasTable(&Foo{}); !ok { - t.Errorf("Table should exist, but HasTable informs it does not") - } -} - -func TestTableName(t *testing.T) { - DB := DB.Model("") - if DB.NewScope(Order{}).TableName() != "orders" { - t.Errorf("Order's table name should be orders") - } - - if DB.NewScope(&Order{}).TableName() != "orders" { - t.Errorf("&Order's table name should be orders") - } - - if DB.NewScope([]Order{}).TableName() != "orders" { - t.Errorf("[]Order's table name should be orders") - } - - if DB.NewScope(&[]Order{}).TableName() != "orders" { - t.Errorf("&[]Order's table name should be orders") - } - - DB.SingularTable(true) - if DB.NewScope(Order{}).TableName() != "order" { - t.Errorf("Order's singular table name should be order") - } - - if DB.NewScope(&Order{}).TableName() != "order" { - t.Errorf("&Order's singular table name should be order") - } - - if DB.NewScope([]Order{}).TableName() != "order" { - t.Errorf("[]Order's singular table name should be order") - } - - if DB.NewScope(&[]Order{}).TableName() != "order" { - t.Errorf("&[]Order's singular table name should be order") - } - - if DB.NewScope(&Cart{}).TableName() != "shopping_cart" { - t.Errorf("&Cart's singular table name should be shopping_cart") - } - - if DB.NewScope(Cart{}).TableName() != "shopping_cart" { - t.Errorf("Cart's singular table name should be shopping_cart") - } - - if DB.NewScope(&[]Cart{}).TableName() != "shopping_cart" { - t.Errorf("&[]Cart's singular table name should be shopping_cart") - } - - if DB.NewScope([]Cart{}).TableName() != "shopping_cart" { - t.Errorf("[]Cart's singular table name should be shopping_cart") - } - DB.SingularTable(false) -} - -func TestNullValues(t *testing.T) { - DB.DropTable(&NullValue{}) - DB.AutoMigrate(&NullValue{}) - - if err := DB.Save(&NullValue{ - Name: sql.NullString{String: "hello", Valid: true}, - Gender: &sql.NullString{String: "M", Valid: true}, - Age: sql.NullInt64{Int64: 18, Valid: true}, - Male: sql.NullBool{Bool: true, Valid: true}, - Height: sql.NullFloat64{Float64: 100.11, Valid: true}, - AddedAt: NullTime{Time: time.Now(), Valid: true}, - }).Error; err != nil { - t.Errorf("Not error should raise when test null value") - } - - var nv NullValue - DB.First(&nv, "name = ?", "hello") - - if nv.Name.String != "hello" || nv.Gender.String != "M" || nv.Age.Int64 != 18 || nv.Male.Bool != true || nv.Height.Float64 != 100.11 || nv.AddedAt.Valid != true { - t.Errorf("Should be able to fetch null value") - } - - if err := DB.Save(&NullValue{ - Name: sql.NullString{String: "hello-2", Valid: true}, - Gender: &sql.NullString{String: "F", Valid: true}, - Age: sql.NullInt64{Int64: 18, Valid: false}, - Male: sql.NullBool{Bool: true, Valid: true}, - Height: sql.NullFloat64{Float64: 100.11, Valid: true}, - AddedAt: NullTime{Time: time.Now(), Valid: false}, - }).Error; err != nil { - t.Errorf("Not error should raise when test null value") - } - - var nv2 NullValue - DB.First(&nv2, "name = ?", "hello-2") - if nv2.Name.String != "hello-2" || nv2.Gender.String != "F" || nv2.Age.Int64 != 0 || nv2.Male.Bool != true || nv2.Height.Float64 != 100.11 || nv2.AddedAt.Valid != false { - t.Errorf("Should be able to fetch null value") - } - - if err := DB.Save(&NullValue{ - Name: sql.NullString{String: "hello-3", Valid: false}, - Gender: &sql.NullString{String: "M", Valid: true}, - Age: sql.NullInt64{Int64: 18, Valid: false}, - Male: sql.NullBool{Bool: true, Valid: true}, - Height: sql.NullFloat64{Float64: 100.11, Valid: true}, - AddedAt: NullTime{Time: time.Now(), Valid: false}, - }).Error; err == nil { - t.Errorf("Can't save because of name can't be null") - } -} - -func TestNullValuesWithFirstOrCreate(t *testing.T) { - var nv1 = NullValue{ - Name: sql.NullString{String: "first_or_create", Valid: true}, - Gender: &sql.NullString{String: "M", Valid: true}, - } - - var nv2 NullValue - result := DB.Where(nv1).FirstOrCreate(&nv2) - - if result.RowsAffected != 1 { - t.Errorf("RowsAffected should be 1 after create some record") - } - - if result.Error != nil { - t.Errorf("Should not raise any error, but got %v", result.Error) - } - - if nv2.Name.String != "first_or_create" || nv2.Gender.String != "M" { - t.Errorf("first or create with nullvalues") - } - - if err := DB.Where(nv1).Assign(NullValue{Age: sql.NullInt64{Int64: 18, Valid: true}}).FirstOrCreate(&nv2).Error; err != nil { - t.Errorf("Should not raise any error, but got %v", err) - } - - if nv2.Age.Int64 != 18 { - t.Errorf("should update age to 18") - } -} - -func TestTransaction(t *testing.T) { - tx := DB.Begin() - u := User{Name: "transcation"} - if err := tx.Save(&u).Error; err != nil { - t.Errorf("No error should raise") - } - - if err := tx.First(&User{}, "name = ?", "transcation").Error; err != nil { - t.Errorf("Should find saved record") - } - - if sqlTx, ok := tx.CommonDB().(*sql.Tx); !ok || sqlTx == nil { - t.Errorf("Should return the underlying sql.Tx") - } - - tx.Rollback() - - if err := tx.First(&User{}, "name = ?", "transcation").Error; err == nil { - t.Errorf("Should not find record after rollback") - } - - tx2 := DB.Begin() - u2 := User{Name: "transcation-2"} - if err := tx2.Save(&u2).Error; err != nil { - t.Errorf("No error should raise") - } - - if err := tx2.First(&User{}, "name = ?", "transcation-2").Error; err != nil { - t.Errorf("Should find saved record") - } - - tx2.Commit() - - if err := DB.First(&User{}, "name = ?", "transcation-2").Error; err != nil { - t.Errorf("Should be able to find committed record") - } -} - -func TestRow(t *testing.T) { - user1 := User{Name: "RowUser1", Age: 1, Birthday: parseTime("2000-1-1")} - user2 := User{Name: "RowUser2", Age: 10, Birthday: parseTime("2010-1-1")} - user3 := User{Name: "RowUser3", Age: 20, Birthday: parseTime("2020-1-1")} - DB.Save(&user1).Save(&user2).Save(&user3) - - row := DB.Table("users").Where("name = ?", user2.Name).Select("age").Row() - var age int64 - row.Scan(&age) - if age != 10 { - t.Errorf("Scan with Row") - } -} - -func TestRows(t *testing.T) { - user1 := User{Name: "RowsUser1", Age: 1, Birthday: parseTime("2000-1-1")} - user2 := User{Name: "RowsUser2", Age: 10, Birthday: parseTime("2010-1-1")} - user3 := User{Name: "RowsUser3", Age: 20, Birthday: parseTime("2020-1-1")} - DB.Save(&user1).Save(&user2).Save(&user3) - - rows, err := DB.Table("users").Where("name = ? or name = ?", user2.Name, user3.Name).Select("name, age").Rows() - if err != nil { - t.Errorf("Not error should happen, got %v", err) - } - - count := 0 - for rows.Next() { - var name string - var age int64 - rows.Scan(&name, &age) - count++ - } - - if count != 2 { - t.Errorf("Should found two records") - } -} - -func TestScanRows(t *testing.T) { - user1 := User{Name: "ScanRowsUser1", Age: 1, Birthday: parseTime("2000-1-1")} - user2 := User{Name: "ScanRowsUser2", Age: 10, Birthday: parseTime("2010-1-1")} - user3 := User{Name: "ScanRowsUser3", Age: 20, Birthday: parseTime("2020-1-1")} - DB.Save(&user1).Save(&user2).Save(&user3) - - rows, err := DB.Table("users").Where("name = ? or name = ?", user2.Name, user3.Name).Select("name, age").Rows() - if err != nil { - t.Errorf("Not error should happen, got %v", err) - } - - type Result struct { - Name string - Age int - } - - var results []Result - for rows.Next() { - var result Result - if err := DB.ScanRows(rows, &result); err != nil { - t.Errorf("should get no error, but got %v", err) - } - results = append(results, result) - } - - if !reflect.DeepEqual(results, []Result{{Name: "ScanRowsUser2", Age: 10}, {Name: "ScanRowsUser3", Age: 20}}) { - t.Errorf("Should find expected results") - } -} - -func TestScan(t *testing.T) { - user1 := User{Name: "ScanUser1", Age: 1, Birthday: parseTime("2000-1-1")} - user2 := User{Name: "ScanUser2", Age: 10, Birthday: parseTime("2010-1-1")} - user3 := User{Name: "ScanUser3", Age: 20, Birthday: parseTime("2020-1-1")} - DB.Save(&user1).Save(&user2).Save(&user3) - - type result struct { - Name string - Age int - } - - var res result - DB.Table("users").Select("name, age").Where("name = ?", user3.Name).Scan(&res) - if res.Name != user3.Name { - t.Errorf("Scan into struct should work") - } - - var doubleAgeRes = &result{} - if err := DB.Table("users").Select("age + age as age").Where("name = ?", user3.Name).Scan(&doubleAgeRes).Error; err != nil { - t.Errorf("Scan to pointer of pointer") - } - if doubleAgeRes.Age != res.Age*2 { - t.Errorf("Scan double age as age") - } - - var ress []result - DB.Table("users").Select("name, age").Where("name in (?)", []string{user2.Name, user3.Name}).Scan(&ress) - if len(ress) != 2 || ress[0].Name != user2.Name || ress[1].Name != user3.Name { - t.Errorf("Scan into struct map") - } -} - -func TestRaw(t *testing.T) { - user1 := User{Name: "ExecRawSqlUser1", Age: 1, Birthday: parseTime("2000-1-1")} - user2 := User{Name: "ExecRawSqlUser2", Age: 10, Birthday: parseTime("2010-1-1")} - user3 := User{Name: "ExecRawSqlUser3", Age: 20, Birthday: parseTime("2020-1-1")} - DB.Save(&user1).Save(&user2).Save(&user3) - - type result struct { - Name string - Email string - } - - var ress []result - DB.Raw("SELECT name, age FROM users WHERE name = ? or name = ?", user2.Name, user3.Name).Scan(&ress) - if len(ress) != 2 || ress[0].Name != user2.Name || ress[1].Name != user3.Name { - t.Errorf("Raw with scan") - } - - rows, _ := DB.Raw("select name, age from users where name = ?", user3.Name).Rows() - count := 0 - for rows.Next() { - count++ - } - if count != 1 { - t.Errorf("Raw with Rows should find one record with name 3") - } - - DB.Exec("update users set name=? where name in (?)", "jinzhu", []string{user1.Name, user2.Name, user3.Name}) - if DB.Where("name in (?)", []string{user1.Name, user2.Name, user3.Name}).First(&User{}).Error != gorm.ErrRecordNotFound { - t.Error("Raw sql to update records") - } -} - -func TestGroup(t *testing.T) { - rows, err := DB.Select("name").Table("users").Group("name").Rows() - - if err == nil { - defer rows.Close() - for rows.Next() { - var name string - rows.Scan(&name) - } - } else { - t.Errorf("Should not raise any error") - } -} - -func TestJoins(t *testing.T) { - var user = User{ - Name: "joins", - CreditCard: CreditCard{Number: "411111111111"}, - Emails: []Email{{Email: "join1@example.com"}, {Email: "join2@example.com"}}, - } - DB.Save(&user) - - var users1 []User - DB.Joins("left join emails on emails.user_id = users.id").Where("name = ?", "joins").Find(&users1) - if len(users1) != 2 { - t.Errorf("should find two users using left join") - } - - var users2 []User - DB.Joins("left join emails on emails.user_id = users.id AND emails.email = ?", "join1@example.com").Where("name = ?", "joins").First(&users2) - if len(users2) != 1 { - t.Errorf("should find one users using left join with conditions") - } - - var users3 []User - DB.Joins("join emails on emails.user_id = users.id AND emails.email = ?", "join1@example.com").Joins("join credit_cards on credit_cards.user_id = users.id AND credit_cards.number = ?", "411111111111").Where("name = ?", "joins").First(&users3) - if len(users3) != 1 { - t.Errorf("should find one users using multiple left join conditions") - } - - var users4 []User - DB.Joins("join emails on emails.user_id = users.id AND emails.email = ?", "join1@example.com").Joins("join credit_cards on credit_cards.user_id = users.id AND credit_cards.number = ?", "422222222222").Where("name = ?", "joins").First(&users4) - if len(users4) != 0 { - t.Errorf("should find no user when searching with unexisting credit card") - } - - var users5 []User - db5 := DB.Joins("join emails on emails.user_id = users.id AND emails.email = ?", "join1@example.com").Joins("join credit_cards on credit_cards.user_id = users.id AND credit_cards.number = ?", "411111111111").Where(User{Id: 1}).Where(Email{Id: 1}).Not(Email{Id: 10}).First(&users5) - if db5.Error != nil { - t.Errorf("Should not raise error for join where identical fields in different tables. Error: %s", db5.Error.Error()) - } -} - -func TestJoinsWithSelect(t *testing.T) { - type result struct { - Name string - Email string - } - - user := User{ - Name: "joins_with_select", - Emails: []Email{{Email: "join1@example.com"}, {Email: "join2@example.com"}}, - } - DB.Save(&user) - - var results []result - DB.Table("users").Select("name, emails.email").Joins("left join emails on emails.user_id = users.id").Where("name = ?", "joins_with_select").Scan(&results) - if len(results) != 2 || results[0].Email != "join1@example.com" || results[1].Email != "join2@example.com" { - t.Errorf("Should find all two emails with Join select") - } -} - -func TestHaving(t *testing.T) { - rows, err := DB.Select("name, count(*) as total").Table("users").Group("name").Having("name IN (?)", []string{"2", "3"}).Rows() - - if err == nil { - defer rows.Close() - for rows.Next() { - var name string - var total int64 - rows.Scan(&name, &total) - - if name == "2" && total != 1 { - t.Errorf("Should have one user having name 2") - } - if name == "3" && total != 2 { - t.Errorf("Should have two users having name 3") - } - } - } else { - t.Errorf("Should not raise any error") - } -} - -func DialectHasTzSupport() bool { - // NB: mssql and FoundationDB do not support time zones. - if dialect := os.Getenv("GORM_DIALECT"); dialect == "mssql" || dialect == "foundation" { - return false - } - return true -} - -func TestTimeWithZone(t *testing.T) { - var format = "2006-01-02 15:04:05 -0700" - var times []time.Time - GMT8, _ := time.LoadLocation("Asia/Shanghai") - times = append(times, time.Date(2013, 02, 19, 1, 51, 49, 123456789, GMT8)) - times = append(times, time.Date(2013, 02, 18, 17, 51, 49, 123456789, time.UTC)) - - for index, vtime := range times { - name := "time_with_zone_" + strconv.Itoa(index) - user := User{Name: name, Birthday: &vtime} - - if !DialectHasTzSupport() { - // If our driver dialect doesn't support TZ's, just use UTC for everything here. - utcBirthday := user.Birthday.UTC() - user.Birthday = &utcBirthday - } - - DB.Save(&user) - expectedBirthday := "2013-02-18 17:51:49 +0000" - foundBirthday := user.Birthday.UTC().Format(format) - if foundBirthday != expectedBirthday { - t.Errorf("User's birthday should not be changed after save for name=%s, expected bday=%+v but actual value=%+v", name, expectedBirthday, foundBirthday) - } - - var findUser, findUser2, findUser3 User - DB.First(&findUser, "name = ?", name) - foundBirthday = findUser.Birthday.UTC().Format(format) - if foundBirthday != expectedBirthday { - t.Errorf("User's birthday should not be changed after find for name=%s, expected bday=%+v but actual value=%+v", name, expectedBirthday, foundBirthday) - } - - if DB.Where("id = ? AND birthday >= ?", findUser.Id, user.Birthday.Add(-time.Minute)).First(&findUser2).RecordNotFound() { - t.Errorf("User should be found") - } - - if !DB.Where("id = ? AND birthday >= ?", findUser.Id, user.Birthday.Add(time.Minute)).First(&findUser3).RecordNotFound() { - t.Errorf("User should not be found") - } - } -} - -func TestHstore(t *testing.T) { - type Details struct { - Id int64 - Bulk postgres.Hstore - } - - if dialect := os.Getenv("GORM_DIALECT"); dialect != "postgres" { - t.Skip() - } - - if err := DB.Exec("CREATE EXTENSION IF NOT EXISTS hstore").Error; err != nil { - fmt.Println("\033[31mHINT: Must be superuser to create hstore extension (ALTER USER gorm WITH SUPERUSER;)\033[0m") - panic(fmt.Sprintf("No error should happen when create hstore extension, but got %+v", err)) - } - - DB.Exec("drop table details") - - if err := DB.CreateTable(&Details{}).Error; err != nil { - panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) - } - - bankAccountId, phoneNumber, opinion := "123456", "14151321232", "sharkbait" - bulk := map[string]*string{ - "bankAccountId": &bankAccountId, - "phoneNumber": &phoneNumber, - "opinion": &opinion, - } - d := Details{Bulk: bulk} - DB.Save(&d) - - var d2 Details - if err := DB.First(&d2).Error; err != nil { - t.Errorf("Got error when tried to fetch details: %+v", err) - } - - for k := range bulk { - if r, ok := d2.Bulk[k]; ok { - if res, _ := bulk[k]; *res != *r { - t.Errorf("Details should be equal") - } - } else { - t.Errorf("Details should be existed") - } - } -} - -func TestSetAndGet(t *testing.T) { - if value, ok := DB.Set("hello", "world").Get("hello"); !ok { - t.Errorf("Should be able to get setting after set") - } else { - if value.(string) != "world" { - t.Errorf("Setted value should not be changed") - } - } - - if _, ok := DB.Get("non_existing"); ok { - t.Errorf("Get non existing key should return error") - } -} - -func TestCompatibilityMode(t *testing.T) { - DB, _ := gorm.Open("testdb", "") - testdb.SetQueryFunc(func(query string) (driver.Rows, error) { - columns := []string{"id", "name", "age"} - result := ` - 1,Tim,20 - 2,Joe,25 - 3,Bob,30 - ` - return testdb.RowsFromCSVString(columns, result), nil - }) - - var users []User - DB.Find(&users) - if (users[0].Name != "Tim") || len(users) != 3 { - t.Errorf("Unexcepted result returned") - } -} - -func TestOpenExistingDB(t *testing.T) { - DB.Save(&User{Name: "jnfeinstein"}) - dialect := os.Getenv("GORM_DIALECT") - - db, err := gorm.Open(dialect, DB.DB()) - if err != nil { - t.Errorf("Should have wrapped the existing DB connection") - } - - var user User - if db.Where("name = ?", "jnfeinstein").First(&user).Error == gorm.ErrRecordNotFound { - t.Errorf("Should have found existing record") - } -} - -func TestDdlErrors(t *testing.T) { - var err error - - if err = DB.Close(); err != nil { - t.Errorf("Closing DDL test db connection err=%s", err) - } - defer func() { - // Reopen DB connection. - if DB, err = OpenTestConnection(); err != nil { - t.Fatalf("Failed re-opening db connection: %s", err) - } - }() - - if err := DB.Find(&User{}).Error; err == nil { - t.Errorf("Expected operation on closed db to produce an error, but err was nil") - } -} - -func TestOpenWithOneParameter(t *testing.T) { - db, err := gorm.Open("dialect") - if db != nil { - t.Error("Open with one parameter returned non nil for db") - } - if err == nil { - t.Error("Open with one parameter returned err as nil") - } -} - -func TestBlockGlobalUpdate(t *testing.T) { - db := DB.New() - db.Create(&Toy{Name: "Stuffed Animal", OwnerType: "Nobody"}) - - err := db.Model(&Toy{}).Update("OwnerType", "Human").Error - if err != nil { - t.Error("Unexpected error on global update") - } - - err = db.Delete(&Toy{}).Error - if err != nil { - t.Error("Unexpected error on global delete") - } - - db.BlockGlobalUpdate(true) - - db.Create(&Toy{Name: "Stuffed Animal", OwnerType: "Nobody"}) - - err = db.Model(&Toy{}).Update("OwnerType", "Human").Error - if err == nil { - t.Error("Expected error on global update") - } - - err = db.Model(&Toy{}).Where(&Toy{OwnerType: "Martian"}).Update("OwnerType", "Astronaut").Error - if err != nil { - t.Error("Unxpected error on conditional update") - } - - err = db.Delete(&Toy{}).Error - if err == nil { - t.Error("Expected error on global delete") - } - err = db.Where(&Toy{OwnerType: "Martian"}).Delete(&Toy{}).Error - if err != nil { - t.Error("Unexpected error on conditional delete") - } -} - -func BenchmarkGorm(b *testing.B) { - b.N = 2000 - for x := 0; x < b.N; x++ { - e := strconv.Itoa(x) + "benchmark@example.org" - now := time.Now() - email := BigEmail{Email: e, UserAgent: "pc", RegisteredAt: &now} - // Insert - DB.Save(&email) - // Query - DB.First(&BigEmail{}, "email = ?", e) - // Update - DB.Model(&email).UpdateColumn("email", "new-"+e) - // Delete - DB.Delete(&email) - } -} - -func BenchmarkRawSql(b *testing.B) { - DB, _ := sql.Open("postgres", "user=gorm DB.ame=gorm sslmode=disable") - DB.SetMaxIdleConns(10) - insertSql := "INSERT INTO emails (user_id,email,user_agent,registered_at,created_at,updated_at) VALUES ($1,$2,$3,$4,$5,$6) RETURNING id" - querySql := "SELECT * FROM emails WHERE email = $1 ORDER BY id LIMIT 1" - updateSql := "UPDATE emails SET email = $1, updated_at = $2 WHERE id = $3" - deleteSql := "DELETE FROM orders WHERE id = $1" - - b.N = 2000 - for x := 0; x < b.N; x++ { - var id int64 - e := strconv.Itoa(x) + "benchmark@example.org" - now := time.Now() - email := BigEmail{Email: e, UserAgent: "pc", RegisteredAt: &now} - // Insert - DB.QueryRow(insertSql, email.UserId, email.Email, email.UserAgent, email.RegisteredAt, time.Now(), time.Now()).Scan(&id) - // Query - rows, _ := DB.Query(querySql, email.Email) - rows.Close() - // Update - DB.Exec(updateSql, "new-"+e, time.Now(), id) - // Delete - DB.Exec(deleteSql, id) - } -} - -func parseTime(str string) *time.Time { - t := now.MustParse(str) - return &t -} diff --git a/vendor/github.com/jinzhu/gorm/migration_test.go b/vendor/github.com/jinzhu/gorm/migration_test.go deleted file mode 100644 index 95c2c57146de..000000000000 --- a/vendor/github.com/jinzhu/gorm/migration_test.go +++ /dev/null @@ -1,438 +0,0 @@ -package gorm_test - -import ( - "database/sql" - "database/sql/driver" - "errors" - "fmt" - "reflect" - "testing" - "time" - - "github.com/jinzhu/gorm" -) - -type User struct { - Id int64 - Age int64 - UserNum Num - Name string `sql:"size:255"` - Email string - Birthday *time.Time // Time - CreatedAt time.Time // CreatedAt: Time of record is created, will be insert automatically - UpdatedAt time.Time // UpdatedAt: Time of record is updated, will be updated automatically - Emails []Email // Embedded structs - BillingAddress Address // Embedded struct - BillingAddressID sql.NullInt64 // Embedded struct's foreign key - ShippingAddress Address // Embedded struct - ShippingAddressId int64 // Embedded struct's foreign key - CreditCard CreditCard - Latitude float64 - Languages []Language `gorm:"many2many:user_languages;"` - CompanyID *int - Company Company - Role - PasswordHash []byte - Sequence uint `gorm:"AUTO_INCREMENT"` - IgnoreMe int64 `sql:"-"` - IgnoreStringSlice []string `sql:"-"` - Ignored struct{ Name string } `sql:"-"` - IgnoredPointer *User `sql:"-"` -} - -type NotSoLongTableName struct { - Id int64 - ReallyLongThingID int64 - ReallyLongThing ReallyLongTableNameToTestMySQLNameLengthLimit -} - -type ReallyLongTableNameToTestMySQLNameLengthLimit struct { - Id int64 -} - -type ReallyLongThingThatReferencesShort struct { - Id int64 - ShortID int64 - Short Short -} - -type Short struct { - Id int64 -} - -type CreditCard struct { - ID int8 - Number string - UserId sql.NullInt64 - CreatedAt time.Time `sql:"not null"` - UpdatedAt time.Time - DeletedAt *time.Time `sql:"column:deleted_time"` -} - -type Email struct { - Id int16 - UserId int - Email string `sql:"type:varchar(100);"` - CreatedAt time.Time - UpdatedAt time.Time -} - -type Address struct { - ID int - Address1 string - Address2 string - Post string - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt *time.Time -} - -type Language struct { - gorm.Model - Name string - Users []User `gorm:"many2many:user_languages;"` -} - -type Product struct { - Id int64 - Code string - Price int64 - CreatedAt time.Time - UpdatedAt time.Time - AfterFindCallTimes int64 - BeforeCreateCallTimes int64 - AfterCreateCallTimes int64 - BeforeUpdateCallTimes int64 - AfterUpdateCallTimes int64 - BeforeSaveCallTimes int64 - AfterSaveCallTimes int64 - BeforeDeleteCallTimes int64 - AfterDeleteCallTimes int64 -} - -type Company struct { - Id int64 - Name string - Owner *User `sql:"-"` -} - -type Role struct { - Name string `gorm:"size:256"` -} - -func (role *Role) Scan(value interface{}) error { - if b, ok := value.([]uint8); ok { - role.Name = string(b) - } else { - role.Name = value.(string) - } - return nil -} - -func (role Role) Value() (driver.Value, error) { - return role.Name, nil -} - -func (role Role) IsAdmin() bool { - return role.Name == "admin" -} - -type Num int64 - -func (i *Num) Scan(src interface{}) error { - switch s := src.(type) { - case []byte: - case int64: - *i = Num(s) - default: - return errors.New("Cannot scan NamedInt from " + reflect.ValueOf(src).String()) - } - return nil -} - -type Animal struct { - Counter uint64 `gorm:"primary_key:yes"` - Name string `sql:"DEFAULT:'galeone'"` - From string //test reserved sql keyword as field name - Age time.Time `sql:"DEFAULT:current_timestamp"` - unexported string // unexported value - CreatedAt time.Time - UpdatedAt time.Time -} - -type JoinTable struct { - From uint64 - To uint64 - Time time.Time `sql:"default: null"` -} - -type Post struct { - Id int64 - CategoryId sql.NullInt64 - MainCategoryId int64 - Title string - Body string - Comments []*Comment - Category Category - MainCategory Category -} - -type Category struct { - gorm.Model - Name string - - Categories []Category - CategoryID *uint -} - -type Comment struct { - gorm.Model - PostId int64 - Content string - Post Post -} - -// Scanner -type NullValue struct { - Id int64 - Name sql.NullString `sql:"not null"` - Gender *sql.NullString `sql:"not null"` - Age sql.NullInt64 - Male sql.NullBool - Height sql.NullFloat64 - AddedAt NullTime -} - -type NullTime struct { - Time time.Time - Valid bool -} - -func (nt *NullTime) Scan(value interface{}) error { - if value == nil { - nt.Valid = false - return nil - } - nt.Time, nt.Valid = value.(time.Time), true - return nil -} - -func (nt NullTime) Value() (driver.Value, error) { - if !nt.Valid { - return nil, nil - } - return nt.Time, nil -} - -func getPreparedUser(name string, role string) *User { - var company Company - DB.Where(Company{Name: role}).FirstOrCreate(&company) - - return &User{ - Name: name, - Age: 20, - Role: Role{role}, - BillingAddress: Address{Address1: fmt.Sprintf("Billing Address %v", name)}, - ShippingAddress: Address{Address1: fmt.Sprintf("Shipping Address %v", name)}, - CreditCard: CreditCard{Number: fmt.Sprintf("123456%v", name)}, - Emails: []Email{ - {Email: fmt.Sprintf("user_%v@example1.com", name)}, {Email: fmt.Sprintf("user_%v@example2.com", name)}, - }, - Company: company, - Languages: []Language{ - {Name: fmt.Sprintf("lang_1_%v", name)}, - {Name: fmt.Sprintf("lang_2_%v", name)}, - }, - } -} - -func runMigration() { - if err := DB.DropTableIfExists(&User{}).Error; err != nil { - fmt.Printf("Got error when try to delete table users, %+v\n", err) - } - - for _, table := range []string{"animals", "user_languages"} { - DB.Exec(fmt.Sprintf("drop table %v;", table)) - } - - values := []interface{}{&Short{}, &ReallyLongThingThatReferencesShort{}, &ReallyLongTableNameToTestMySQLNameLengthLimit{}, &NotSoLongTableName{}, &Product{}, &Email{}, &Address{}, &CreditCard{}, &Company{}, &Role{}, &Language{}, &HNPost{}, &EngadgetPost{}, &Animal{}, &User{}, &JoinTable{}, &Post{}, &Category{}, &Comment{}, &Cat{}, &Dog{}, &Hamster{}, &Toy{}, &ElementWithIgnoredField{}} - for _, value := range values { - DB.DropTable(value) - } - if err := DB.AutoMigrate(values...).Error; err != nil { - panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) - } -} - -func TestIndexes(t *testing.T) { - if err := DB.Model(&Email{}).AddIndex("idx_email_email", "email").Error; err != nil { - t.Errorf("Got error when tried to create index: %+v", err) - } - - scope := DB.NewScope(&Email{}) - if !scope.Dialect().HasIndex(scope.TableName(), "idx_email_email") { - t.Errorf("Email should have index idx_email_email") - } - - if err := DB.Model(&Email{}).RemoveIndex("idx_email_email").Error; err != nil { - t.Errorf("Got error when tried to remove index: %+v", err) - } - - if scope.Dialect().HasIndex(scope.TableName(), "idx_email_email") { - t.Errorf("Email's index idx_email_email should be deleted") - } - - if err := DB.Model(&Email{}).AddIndex("idx_email_email_and_user_id", "user_id", "email").Error; err != nil { - t.Errorf("Got error when tried to create index: %+v", err) - } - - if !scope.Dialect().HasIndex(scope.TableName(), "idx_email_email_and_user_id") { - t.Errorf("Email should have index idx_email_email_and_user_id") - } - - if err := DB.Model(&Email{}).RemoveIndex("idx_email_email_and_user_id").Error; err != nil { - t.Errorf("Got error when tried to remove index: %+v", err) - } - - if scope.Dialect().HasIndex(scope.TableName(), "idx_email_email_and_user_id") { - t.Errorf("Email's index idx_email_email_and_user_id should be deleted") - } - - if err := DB.Model(&Email{}).AddUniqueIndex("idx_email_email_and_user_id", "user_id", "email").Error; err != nil { - t.Errorf("Got error when tried to create index: %+v", err) - } - - if !scope.Dialect().HasIndex(scope.TableName(), "idx_email_email_and_user_id") { - t.Errorf("Email should have index idx_email_email_and_user_id") - } - - if DB.Save(&User{Name: "unique_indexes", Emails: []Email{{Email: "user1@example.comiii"}, {Email: "user1@example.com"}, {Email: "user1@example.com"}}}).Error == nil { - t.Errorf("Should get to create duplicate record when having unique index") - } - - var user = User{Name: "sample_user"} - DB.Save(&user) - if DB.Model(&user).Association("Emails").Append(Email{Email: "not-1duplicated@gmail.com"}, Email{Email: "not-duplicated2@gmail.com"}).Error != nil { - t.Errorf("Should get no error when append two emails for user") - } - - if DB.Model(&user).Association("Emails").Append(Email{Email: "duplicated@gmail.com"}, Email{Email: "duplicated@gmail.com"}).Error == nil { - t.Errorf("Should get no duplicated email error when insert duplicated emails for a user") - } - - if err := DB.Model(&Email{}).RemoveIndex("idx_email_email_and_user_id").Error; err != nil { - t.Errorf("Got error when tried to remove index: %+v", err) - } - - if scope.Dialect().HasIndex(scope.TableName(), "idx_email_email_and_user_id") { - t.Errorf("Email's index idx_email_email_and_user_id should be deleted") - } - - if DB.Save(&User{Name: "unique_indexes", Emails: []Email{{Email: "user1@example.com"}, {Email: "user1@example.com"}}}).Error != nil { - t.Errorf("Should be able to create duplicated emails after remove unique index") - } -} - -type BigEmail struct { - Id int64 - UserId int64 - Email string `sql:"index:idx_email_agent"` - UserAgent string `sql:"index:idx_email_agent"` - RegisteredAt *time.Time `sql:"unique_index"` - CreatedAt time.Time - UpdatedAt time.Time -} - -func (b BigEmail) TableName() string { - return "emails" -} - -func TestAutoMigration(t *testing.T) { - DB.AutoMigrate(&Address{}) - if err := DB.Table("emails").AutoMigrate(&BigEmail{}).Error; err != nil { - t.Errorf("Auto Migrate should not raise any error") - } - - now := time.Now() - DB.Save(&BigEmail{Email: "jinzhu@example.org", UserAgent: "pc", RegisteredAt: &now}) - - scope := DB.NewScope(&BigEmail{}) - if !scope.Dialect().HasIndex(scope.TableName(), "idx_email_agent") { - t.Errorf("Failed to create index") - } - - if !scope.Dialect().HasIndex(scope.TableName(), "uix_emails_registered_at") { - t.Errorf("Failed to create index") - } - - var bigemail BigEmail - DB.First(&bigemail, "user_agent = ?", "pc") - if bigemail.Email != "jinzhu@example.org" || bigemail.UserAgent != "pc" || bigemail.RegisteredAt.IsZero() { - t.Error("Big Emails should be saved and fetched correctly") - } -} - -type MultipleIndexes struct { - ID int64 - UserID int64 `sql:"unique_index:uix_multipleindexes_user_name,uix_multipleindexes_user_email;index:idx_multipleindexes_user_other"` - Name string `sql:"unique_index:uix_multipleindexes_user_name"` - Email string `sql:"unique_index:,uix_multipleindexes_user_email"` - Other string `sql:"index:,idx_multipleindexes_user_other"` -} - -func TestMultipleIndexes(t *testing.T) { - if err := DB.DropTableIfExists(&MultipleIndexes{}).Error; err != nil { - fmt.Printf("Got error when try to delete table multiple_indexes, %+v\n", err) - } - - DB.AutoMigrate(&MultipleIndexes{}) - if err := DB.AutoMigrate(&BigEmail{}).Error; err != nil { - t.Errorf("Auto Migrate should not raise any error") - } - - DB.Save(&MultipleIndexes{UserID: 1, Name: "jinzhu", Email: "jinzhu@example.org", Other: "foo"}) - - scope := DB.NewScope(&MultipleIndexes{}) - if !scope.Dialect().HasIndex(scope.TableName(), "uix_multipleindexes_user_name") { - t.Errorf("Failed to create index") - } - - if !scope.Dialect().HasIndex(scope.TableName(), "uix_multipleindexes_user_email") { - t.Errorf("Failed to create index") - } - - if !scope.Dialect().HasIndex(scope.TableName(), "uix_multiple_indexes_email") { - t.Errorf("Failed to create index") - } - - if !scope.Dialect().HasIndex(scope.TableName(), "idx_multipleindexes_user_other") { - t.Errorf("Failed to create index") - } - - if !scope.Dialect().HasIndex(scope.TableName(), "idx_multiple_indexes_other") { - t.Errorf("Failed to create index") - } - - var mutipleIndexes MultipleIndexes - DB.First(&mutipleIndexes, "name = ?", "jinzhu") - if mutipleIndexes.Email != "jinzhu@example.org" || mutipleIndexes.Name != "jinzhu" { - t.Error("MutipleIndexes should be saved and fetched correctly") - } - - // Check unique constraints - if err := DB.Save(&MultipleIndexes{UserID: 1, Name: "name1", Email: "jinzhu@example.org", Other: "foo"}).Error; err == nil { - t.Error("MultipleIndexes unique index failed") - } - - if err := DB.Save(&MultipleIndexes{UserID: 1, Name: "name1", Email: "foo@example.org", Other: "foo"}).Error; err != nil { - t.Error("MultipleIndexes unique index failed") - } - - if err := DB.Save(&MultipleIndexes{UserID: 2, Name: "name1", Email: "jinzhu@example.org", Other: "foo"}).Error; err == nil { - t.Error("MultipleIndexes unique index failed") - } - - if err := DB.Save(&MultipleIndexes{UserID: 2, Name: "name1", Email: "foo2@example.org", Other: "foo"}).Error; err != nil { - t.Error("MultipleIndexes unique index failed") - } -} diff --git a/vendor/github.com/jinzhu/gorm/multi_primary_keys_test.go b/vendor/github.com/jinzhu/gorm/multi_primary_keys_test.go deleted file mode 100644 index 8b275d182b27..000000000000 --- a/vendor/github.com/jinzhu/gorm/multi_primary_keys_test.go +++ /dev/null @@ -1,381 +0,0 @@ -package gorm_test - -import ( - "os" - "reflect" - "sort" - "testing" -) - -type Blog struct { - ID uint `gorm:"primary_key"` - Locale string `gorm:"primary_key"` - Subject string - Body string - Tags []Tag `gorm:"many2many:blog_tags;"` - SharedTags []Tag `gorm:"many2many:shared_blog_tags;ForeignKey:id;AssociationForeignKey:id"` - LocaleTags []Tag `gorm:"many2many:locale_blog_tags;ForeignKey:id,locale;AssociationForeignKey:id"` -} - -type Tag struct { - ID uint `gorm:"primary_key"` - Locale string `gorm:"primary_key"` - Value string - Blogs []*Blog `gorm:"many2many:blogs_tags"` -} - -func compareTags(tags []Tag, contents []string) bool { - var tagContents []string - for _, tag := range tags { - tagContents = append(tagContents, tag.Value) - } - sort.Strings(tagContents) - sort.Strings(contents) - return reflect.DeepEqual(tagContents, contents) -} - -func TestManyToManyWithMultiPrimaryKeys(t *testing.T) { - if dialect := os.Getenv("GORM_DIALECT"); dialect != "" && dialect != "sqlite" { - DB.DropTable(&Blog{}, &Tag{}) - DB.DropTable("blog_tags") - DB.CreateTable(&Blog{}, &Tag{}) - blog := Blog{ - Locale: "ZH", - Subject: "subject", - Body: "body", - Tags: []Tag{ - {Locale: "ZH", Value: "tag1"}, - {Locale: "ZH", Value: "tag2"}, - }, - } - - DB.Save(&blog) - if !compareTags(blog.Tags, []string{"tag1", "tag2"}) { - t.Errorf("Blog should has two tags") - } - - // Append - var tag3 = &Tag{Locale: "ZH", Value: "tag3"} - DB.Model(&blog).Association("Tags").Append([]*Tag{tag3}) - if !compareTags(blog.Tags, []string{"tag1", "tag2", "tag3"}) { - t.Errorf("Blog should has three tags after Append") - } - - if DB.Model(&blog).Association("Tags").Count() != 3 { - t.Errorf("Blog should has three tags after Append") - } - - var tags []Tag - DB.Model(&blog).Related(&tags, "Tags") - if !compareTags(tags, []string{"tag1", "tag2", "tag3"}) { - t.Errorf("Should find 3 tags with Related") - } - - var blog1 Blog - DB.Preload("Tags").Find(&blog1) - if !compareTags(blog1.Tags, []string{"tag1", "tag2", "tag3"}) { - t.Errorf("Preload many2many relations") - } - - // Replace - var tag5 = &Tag{Locale: "ZH", Value: "tag5"} - var tag6 = &Tag{Locale: "ZH", Value: "tag6"} - DB.Model(&blog).Association("Tags").Replace(tag5, tag6) - var tags2 []Tag - DB.Model(&blog).Related(&tags2, "Tags") - if !compareTags(tags2, []string{"tag5", "tag6"}) { - t.Errorf("Should find 2 tags after Replace") - } - - if DB.Model(&blog).Association("Tags").Count() != 2 { - t.Errorf("Blog should has three tags after Replace") - } - - // Delete - DB.Model(&blog).Association("Tags").Delete(tag5) - var tags3 []Tag - DB.Model(&blog).Related(&tags3, "Tags") - if !compareTags(tags3, []string{"tag6"}) { - t.Errorf("Should find 1 tags after Delete") - } - - if DB.Model(&blog).Association("Tags").Count() != 1 { - t.Errorf("Blog should has three tags after Delete") - } - - DB.Model(&blog).Association("Tags").Delete(tag3) - var tags4 []Tag - DB.Model(&blog).Related(&tags4, "Tags") - if !compareTags(tags4, []string{"tag6"}) { - t.Errorf("Tag should not be deleted when Delete with a unrelated tag") - } - - // Clear - DB.Model(&blog).Association("Tags").Clear() - if DB.Model(&blog).Association("Tags").Count() != 0 { - t.Errorf("All tags should be cleared") - } - } -} - -func TestManyToManyWithCustomizedForeignKeys(t *testing.T) { - if dialect := os.Getenv("GORM_DIALECT"); dialect != "" && dialect != "sqlite" { - DB.DropTable(&Blog{}, &Tag{}) - DB.DropTable("shared_blog_tags") - DB.CreateTable(&Blog{}, &Tag{}) - blog := Blog{ - Locale: "ZH", - Subject: "subject", - Body: "body", - SharedTags: []Tag{ - {Locale: "ZH", Value: "tag1"}, - {Locale: "ZH", Value: "tag2"}, - }, - } - DB.Save(&blog) - - blog2 := Blog{ - ID: blog.ID, - Locale: "EN", - } - DB.Create(&blog2) - - if !compareTags(blog.SharedTags, []string{"tag1", "tag2"}) { - t.Errorf("Blog should has two tags") - } - - // Append - var tag3 = &Tag{Locale: "ZH", Value: "tag3"} - DB.Model(&blog).Association("SharedTags").Append([]*Tag{tag3}) - if !compareTags(blog.SharedTags, []string{"tag1", "tag2", "tag3"}) { - t.Errorf("Blog should has three tags after Append") - } - - if DB.Model(&blog).Association("SharedTags").Count() != 3 { - t.Errorf("Blog should has three tags after Append") - } - - if DB.Model(&blog2).Association("SharedTags").Count() != 3 { - t.Errorf("Blog should has three tags after Append") - } - - var tags []Tag - DB.Model(&blog).Related(&tags, "SharedTags") - if !compareTags(tags, []string{"tag1", "tag2", "tag3"}) { - t.Errorf("Should find 3 tags with Related") - } - - DB.Model(&blog2).Related(&tags, "SharedTags") - if !compareTags(tags, []string{"tag1", "tag2", "tag3"}) { - t.Errorf("Should find 3 tags with Related") - } - - var blog1 Blog - DB.Preload("SharedTags").Find(&blog1) - if !compareTags(blog1.SharedTags, []string{"tag1", "tag2", "tag3"}) { - t.Errorf("Preload many2many relations") - } - - var tag4 = &Tag{Locale: "ZH", Value: "tag4"} - DB.Model(&blog2).Association("SharedTags").Append(tag4) - - DB.Model(&blog).Related(&tags, "SharedTags") - if !compareTags(tags, []string{"tag1", "tag2", "tag3", "tag4"}) { - t.Errorf("Should find 3 tags with Related") - } - - DB.Model(&blog2).Related(&tags, "SharedTags") - if !compareTags(tags, []string{"tag1", "tag2", "tag3", "tag4"}) { - t.Errorf("Should find 3 tags with Related") - } - - // Replace - var tag5 = &Tag{Locale: "ZH", Value: "tag5"} - var tag6 = &Tag{Locale: "ZH", Value: "tag6"} - DB.Model(&blog2).Association("SharedTags").Replace(tag5, tag6) - var tags2 []Tag - DB.Model(&blog).Related(&tags2, "SharedTags") - if !compareTags(tags2, []string{"tag5", "tag6"}) { - t.Errorf("Should find 2 tags after Replace") - } - - DB.Model(&blog2).Related(&tags2, "SharedTags") - if !compareTags(tags2, []string{"tag5", "tag6"}) { - t.Errorf("Should find 2 tags after Replace") - } - - if DB.Model(&blog).Association("SharedTags").Count() != 2 { - t.Errorf("Blog should has three tags after Replace") - } - - // Delete - DB.Model(&blog).Association("SharedTags").Delete(tag5) - var tags3 []Tag - DB.Model(&blog).Related(&tags3, "SharedTags") - if !compareTags(tags3, []string{"tag6"}) { - t.Errorf("Should find 1 tags after Delete") - } - - if DB.Model(&blog).Association("SharedTags").Count() != 1 { - t.Errorf("Blog should has three tags after Delete") - } - - DB.Model(&blog2).Association("SharedTags").Delete(tag3) - var tags4 []Tag - DB.Model(&blog).Related(&tags4, "SharedTags") - if !compareTags(tags4, []string{"tag6"}) { - t.Errorf("Tag should not be deleted when Delete with a unrelated tag") - } - - // Clear - DB.Model(&blog2).Association("SharedTags").Clear() - if DB.Model(&blog).Association("SharedTags").Count() != 0 { - t.Errorf("All tags should be cleared") - } - } -} - -func TestManyToManyWithCustomizedForeignKeys2(t *testing.T) { - if dialect := os.Getenv("GORM_DIALECT"); dialect != "" && dialect != "sqlite" { - DB.DropTable(&Blog{}, &Tag{}) - DB.DropTable("locale_blog_tags") - DB.CreateTable(&Blog{}, &Tag{}) - blog := Blog{ - Locale: "ZH", - Subject: "subject", - Body: "body", - LocaleTags: []Tag{ - {Locale: "ZH", Value: "tag1"}, - {Locale: "ZH", Value: "tag2"}, - }, - } - DB.Save(&blog) - - blog2 := Blog{ - ID: blog.ID, - Locale: "EN", - } - DB.Create(&blog2) - - // Append - var tag3 = &Tag{Locale: "ZH", Value: "tag3"} - DB.Model(&blog).Association("LocaleTags").Append([]*Tag{tag3}) - if !compareTags(blog.LocaleTags, []string{"tag1", "tag2", "tag3"}) { - t.Errorf("Blog should has three tags after Append") - } - - if DB.Model(&blog).Association("LocaleTags").Count() != 3 { - t.Errorf("Blog should has three tags after Append") - } - - if DB.Model(&blog2).Association("LocaleTags").Count() != 0 { - t.Errorf("EN Blog should has 0 tags after ZH Blog Append") - } - - var tags []Tag - DB.Model(&blog).Related(&tags, "LocaleTags") - if !compareTags(tags, []string{"tag1", "tag2", "tag3"}) { - t.Errorf("Should find 3 tags with Related") - } - - DB.Model(&blog2).Related(&tags, "LocaleTags") - if len(tags) != 0 { - t.Errorf("Should find 0 tags with Related for EN Blog") - } - - var blog1 Blog - DB.Preload("LocaleTags").Find(&blog1, "locale = ? AND id = ?", "ZH", blog.ID) - if !compareTags(blog1.LocaleTags, []string{"tag1", "tag2", "tag3"}) { - t.Errorf("Preload many2many relations") - } - - var tag4 = &Tag{Locale: "ZH", Value: "tag4"} - DB.Model(&blog2).Association("LocaleTags").Append(tag4) - - DB.Model(&blog).Related(&tags, "LocaleTags") - if !compareTags(tags, []string{"tag1", "tag2", "tag3"}) { - t.Errorf("Should find 3 tags with Related for EN Blog") - } - - DB.Model(&blog2).Related(&tags, "LocaleTags") - if !compareTags(tags, []string{"tag4"}) { - t.Errorf("Should find 1 tags with Related for EN Blog") - } - - // Replace - var tag5 = &Tag{Locale: "ZH", Value: "tag5"} - var tag6 = &Tag{Locale: "ZH", Value: "tag6"} - DB.Model(&blog2).Association("LocaleTags").Replace(tag5, tag6) - - var tags2 []Tag - DB.Model(&blog).Related(&tags2, "LocaleTags") - if !compareTags(tags2, []string{"tag1", "tag2", "tag3"}) { - t.Errorf("CN Blog's tags should not be changed after EN Blog Replace") - } - - var blog11 Blog - DB.Preload("LocaleTags").First(&blog11, "id = ? AND locale = ?", blog.ID, blog.Locale) - if !compareTags(blog11.LocaleTags, []string{"tag1", "tag2", "tag3"}) { - t.Errorf("CN Blog's tags should not be changed after EN Blog Replace") - } - - DB.Model(&blog2).Related(&tags2, "LocaleTags") - if !compareTags(tags2, []string{"tag5", "tag6"}) { - t.Errorf("Should find 2 tags after Replace") - } - - var blog21 Blog - DB.Preload("LocaleTags").First(&blog21, "id = ? AND locale = ?", blog2.ID, blog2.Locale) - if !compareTags(blog21.LocaleTags, []string{"tag5", "tag6"}) { - t.Errorf("EN Blog's tags should be changed after Replace") - } - - if DB.Model(&blog).Association("LocaleTags").Count() != 3 { - t.Errorf("ZH Blog should has three tags after Replace") - } - - if DB.Model(&blog2).Association("LocaleTags").Count() != 2 { - t.Errorf("EN Blog should has two tags after Replace") - } - - // Delete - DB.Model(&blog).Association("LocaleTags").Delete(tag5) - - if DB.Model(&blog).Association("LocaleTags").Count() != 3 { - t.Errorf("ZH Blog should has three tags after Delete with EN's tag") - } - - if DB.Model(&blog2).Association("LocaleTags").Count() != 2 { - t.Errorf("EN Blog should has two tags after ZH Blog Delete with EN's tag") - } - - DB.Model(&blog2).Association("LocaleTags").Delete(tag5) - - if DB.Model(&blog).Association("LocaleTags").Count() != 3 { - t.Errorf("ZH Blog should has three tags after EN Blog Delete with EN's tag") - } - - if DB.Model(&blog2).Association("LocaleTags").Count() != 1 { - t.Errorf("EN Blog should has 1 tags after EN Blog Delete with EN's tag") - } - - // Clear - DB.Model(&blog2).Association("LocaleTags").Clear() - if DB.Model(&blog).Association("LocaleTags").Count() != 3 { - t.Errorf("ZH Blog's tags should not be cleared when clear EN Blog's tags") - } - - if DB.Model(&blog2).Association("LocaleTags").Count() != 0 { - t.Errorf("EN Blog's tags should be cleared when clear EN Blog's tags") - } - - DB.Model(&blog).Association("LocaleTags").Clear() - if DB.Model(&blog).Association("LocaleTags").Count() != 0 { - t.Errorf("ZH Blog's tags should be cleared when clear ZH Blog's tags") - } - - if DB.Model(&blog2).Association("LocaleTags").Count() != 0 { - t.Errorf("EN Blog's tags should be cleared") - } - } -} diff --git a/vendor/github.com/jinzhu/gorm/pointer_test.go b/vendor/github.com/jinzhu/gorm/pointer_test.go deleted file mode 100644 index 2a68a5ab249a..000000000000 --- a/vendor/github.com/jinzhu/gorm/pointer_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package gorm_test - -import "testing" - -type PointerStruct struct { - ID int64 - Name *string - Num *int -} - -type NormalStruct struct { - ID int64 - Name string - Num int -} - -func TestPointerFields(t *testing.T) { - DB.DropTable(&PointerStruct{}) - DB.AutoMigrate(&PointerStruct{}) - var name = "pointer struct 1" - var num = 100 - pointerStruct := PointerStruct{Name: &name, Num: &num} - if DB.Create(&pointerStruct).Error != nil { - t.Errorf("Failed to save pointer struct") - } - - var pointerStructResult PointerStruct - if err := DB.First(&pointerStructResult, "id = ?", pointerStruct.ID).Error; err != nil || *pointerStructResult.Name != name || *pointerStructResult.Num != num { - t.Errorf("Failed to query saved pointer struct") - } - - var tableName = DB.NewScope(&PointerStruct{}).TableName() - - var normalStruct NormalStruct - DB.Table(tableName).First(&normalStruct) - if normalStruct.Name != name || normalStruct.Num != num { - t.Errorf("Failed to query saved Normal struct") - } - - var nilPointerStruct = PointerStruct{} - if err := DB.Create(&nilPointerStruct).Error; err != nil { - t.Error("Failed to save nil pointer struct", err) - } - - var pointerStruct2 PointerStruct - if err := DB.First(&pointerStruct2, "id = ?", nilPointerStruct.ID).Error; err != nil { - t.Error("Failed to query saved nil pointer struct", err) - } - - var normalStruct2 NormalStruct - if err := DB.Table(tableName).First(&normalStruct2, "id = ?", nilPointerStruct.ID).Error; err != nil { - t.Error("Failed to query saved nil pointer struct", err) - } - - var partialNilPointerStruct1 = PointerStruct{Num: &num} - if err := DB.Create(&partialNilPointerStruct1).Error; err != nil { - t.Error("Failed to save partial nil pointer struct", err) - } - - var pointerStruct3 PointerStruct - if err := DB.First(&pointerStruct3, "id = ?", partialNilPointerStruct1.ID).Error; err != nil || *pointerStruct3.Num != num { - t.Error("Failed to query saved partial nil pointer struct", err) - } - - var normalStruct3 NormalStruct - if err := DB.Table(tableName).First(&normalStruct3, "id = ?", partialNilPointerStruct1.ID).Error; err != nil || normalStruct3.Num != num { - t.Error("Failed to query saved partial pointer struct", err) - } - - var partialNilPointerStruct2 = PointerStruct{Name: &name} - if err := DB.Create(&partialNilPointerStruct2).Error; err != nil { - t.Error("Failed to save partial nil pointer struct", err) - } - - var pointerStruct4 PointerStruct - if err := DB.First(&pointerStruct4, "id = ?", partialNilPointerStruct2.ID).Error; err != nil || *pointerStruct4.Name != name { - t.Error("Failed to query saved partial nil pointer struct", err) - } - - var normalStruct4 NormalStruct - if err := DB.Table(tableName).First(&normalStruct4, "id = ?", partialNilPointerStruct2.ID).Error; err != nil || normalStruct4.Name != name { - t.Error("Failed to query saved partial pointer struct", err) - } -} diff --git a/vendor/github.com/jinzhu/gorm/polymorphic_test.go b/vendor/github.com/jinzhu/gorm/polymorphic_test.go deleted file mode 100644 index d1ecfbbb6497..000000000000 --- a/vendor/github.com/jinzhu/gorm/polymorphic_test.go +++ /dev/null @@ -1,366 +0,0 @@ -package gorm_test - -import ( - "reflect" - "sort" - "testing" -) - -type Cat struct { - Id int - Name string - Toy Toy `gorm:"polymorphic:Owner;"` -} - -type Dog struct { - Id int - Name string - Toys []Toy `gorm:"polymorphic:Owner;"` -} - -type Hamster struct { - Id int - Name string - PreferredToy Toy `gorm:"polymorphic:Owner;polymorphic_value:hamster_preferred"` - OtherToy Toy `gorm:"polymorphic:Owner;polymorphic_value:hamster_other"` -} - -type Toy struct { - Id int - Name string - OwnerId int - OwnerType string -} - -var compareToys = func(toys []Toy, contents []string) bool { - var toyContents []string - for _, toy := range toys { - toyContents = append(toyContents, toy.Name) - } - sort.Strings(toyContents) - sort.Strings(contents) - return reflect.DeepEqual(toyContents, contents) -} - -func TestPolymorphic(t *testing.T) { - cat := Cat{Name: "Mr. Bigglesworth", Toy: Toy{Name: "cat toy"}} - dog := Dog{Name: "Pluto", Toys: []Toy{{Name: "dog toy 1"}, {Name: "dog toy 2"}}} - DB.Save(&cat).Save(&dog) - - if DB.Model(&cat).Association("Toy").Count() != 1 { - t.Errorf("Cat's toys count should be 1") - } - - if DB.Model(&dog).Association("Toys").Count() != 2 { - t.Errorf("Dog's toys count should be 2") - } - - // Query - var catToys []Toy - if DB.Model(&cat).Related(&catToys, "Toy").RecordNotFound() { - t.Errorf("Did not find any has one polymorphic association") - } else if len(catToys) != 1 { - t.Errorf("Should have found only one polymorphic has one association") - } else if catToys[0].Name != cat.Toy.Name { - t.Errorf("Should have found the proper has one polymorphic association") - } - - var dogToys []Toy - if DB.Model(&dog).Related(&dogToys, "Toys").RecordNotFound() { - t.Errorf("Did not find any polymorphic has many associations") - } else if len(dogToys) != len(dog.Toys) { - t.Errorf("Should have found all polymorphic has many associations") - } - - var catToy Toy - DB.Model(&cat).Association("Toy").Find(&catToy) - if catToy.Name != cat.Toy.Name { - t.Errorf("Should find has one polymorphic association") - } - - var dogToys1 []Toy - DB.Model(&dog).Association("Toys").Find(&dogToys1) - if !compareToys(dogToys1, []string{"dog toy 1", "dog toy 2"}) { - t.Errorf("Should find has many polymorphic association") - } - - // Append - DB.Model(&cat).Association("Toy").Append(&Toy{ - Name: "cat toy 2", - }) - - var catToy2 Toy - DB.Model(&cat).Association("Toy").Find(&catToy2) - if catToy2.Name != "cat toy 2" { - t.Errorf("Should update has one polymorphic association with Append") - } - - if DB.Model(&cat).Association("Toy").Count() != 1 { - t.Errorf("Cat's toys count should be 1 after Append") - } - - if DB.Model(&dog).Association("Toys").Count() != 2 { - t.Errorf("Should return two polymorphic has many associations") - } - - DB.Model(&dog).Association("Toys").Append(&Toy{ - Name: "dog toy 3", - }) - - var dogToys2 []Toy - DB.Model(&dog).Association("Toys").Find(&dogToys2) - if !compareToys(dogToys2, []string{"dog toy 1", "dog toy 2", "dog toy 3"}) { - t.Errorf("Dog's toys should be updated with Append") - } - - if DB.Model(&dog).Association("Toys").Count() != 3 { - t.Errorf("Should return three polymorphic has many associations") - } - - // Replace - DB.Model(&cat).Association("Toy").Replace(&Toy{ - Name: "cat toy 3", - }) - - var catToy3 Toy - DB.Model(&cat).Association("Toy").Find(&catToy3) - if catToy3.Name != "cat toy 3" { - t.Errorf("Should update has one polymorphic association with Replace") - } - - if DB.Model(&cat).Association("Toy").Count() != 1 { - t.Errorf("Cat's toys count should be 1 after Replace") - } - - if DB.Model(&dog).Association("Toys").Count() != 3 { - t.Errorf("Should return three polymorphic has many associations") - } - - DB.Model(&dog).Association("Toys").Replace(&Toy{ - Name: "dog toy 4", - }, []Toy{ - {Name: "dog toy 5"}, {Name: "dog toy 6"}, {Name: "dog toy 7"}, - }) - - var dogToys3 []Toy - DB.Model(&dog).Association("Toys").Find(&dogToys3) - if !compareToys(dogToys3, []string{"dog toy 4", "dog toy 5", "dog toy 6", "dog toy 7"}) { - t.Errorf("Dog's toys should be updated with Replace") - } - - if DB.Model(&dog).Association("Toys").Count() != 4 { - t.Errorf("Should return three polymorphic has many associations") - } - - // Delete - DB.Model(&cat).Association("Toy").Delete(&catToy2) - - var catToy4 Toy - DB.Model(&cat).Association("Toy").Find(&catToy4) - if catToy4.Name != "cat toy 3" { - t.Errorf("Should not update has one polymorphic association when Delete a unrelated Toy") - } - - if DB.Model(&cat).Association("Toy").Count() != 1 { - t.Errorf("Cat's toys count should be 1") - } - - if DB.Model(&dog).Association("Toys").Count() != 4 { - t.Errorf("Dog's toys count should be 4") - } - - DB.Model(&cat).Association("Toy").Delete(&catToy3) - - if !DB.Model(&cat).Related(&Toy{}, "Toy").RecordNotFound() { - t.Errorf("Toy should be deleted with Delete") - } - - if DB.Model(&cat).Association("Toy").Count() != 0 { - t.Errorf("Cat's toys count should be 0 after Delete") - } - - if DB.Model(&dog).Association("Toys").Count() != 4 { - t.Errorf("Dog's toys count should not be changed when delete cat's toy") - } - - DB.Model(&dog).Association("Toys").Delete(&dogToys2) - - if DB.Model(&dog).Association("Toys").Count() != 4 { - t.Errorf("Dog's toys count should not be changed when delete unrelated toys") - } - - DB.Model(&dog).Association("Toys").Delete(&dogToys3) - - if DB.Model(&dog).Association("Toys").Count() != 0 { - t.Errorf("Dog's toys count should be deleted with Delete") - } - - // Clear - DB.Model(&cat).Association("Toy").Append(&Toy{ - Name: "cat toy 2", - }) - - if DB.Model(&cat).Association("Toy").Count() != 1 { - t.Errorf("Cat's toys should be added with Append") - } - - DB.Model(&cat).Association("Toy").Clear() - - if DB.Model(&cat).Association("Toy").Count() != 0 { - t.Errorf("Cat's toys should be cleared with Clear") - } - - DB.Model(&dog).Association("Toys").Append(&Toy{ - Name: "dog toy 8", - }) - - if DB.Model(&dog).Association("Toys").Count() != 1 { - t.Errorf("Dog's toys should be added with Append") - } - - DB.Model(&dog).Association("Toys").Clear() - - if DB.Model(&dog).Association("Toys").Count() != 0 { - t.Errorf("Dog's toys should be cleared with Clear") - } -} - -func TestNamedPolymorphic(t *testing.T) { - hamster := Hamster{Name: "Mr. Hammond", PreferredToy: Toy{Name: "bike"}, OtherToy: Toy{Name: "treadmill"}} - DB.Save(&hamster) - - hamster2 := Hamster{} - DB.Preload("PreferredToy").Preload("OtherToy").Find(&hamster2, hamster.Id) - if hamster2.PreferredToy.Id != hamster.PreferredToy.Id || hamster2.PreferredToy.Name != hamster.PreferredToy.Name { - t.Errorf("Hamster's preferred toy couldn't be preloaded") - } - if hamster2.OtherToy.Id != hamster.OtherToy.Id || hamster2.OtherToy.Name != hamster.OtherToy.Name { - t.Errorf("Hamster's other toy couldn't be preloaded") - } - - // clear to omit Toy.Id in count - hamster2.PreferredToy = Toy{} - hamster2.OtherToy = Toy{} - - if DB.Model(&hamster2).Association("PreferredToy").Count() != 1 { - t.Errorf("Hamster's preferred toy count should be 1") - } - - if DB.Model(&hamster2).Association("OtherToy").Count() != 1 { - t.Errorf("Hamster's other toy count should be 1") - } - - // Query - var hamsterToys []Toy - if DB.Model(&hamster).Related(&hamsterToys, "PreferredToy").RecordNotFound() { - t.Errorf("Did not find any has one polymorphic association") - } else if len(hamsterToys) != 1 { - t.Errorf("Should have found only one polymorphic has one association") - } else if hamsterToys[0].Name != hamster.PreferredToy.Name { - t.Errorf("Should have found the proper has one polymorphic association") - } - - if DB.Model(&hamster).Related(&hamsterToys, "OtherToy").RecordNotFound() { - t.Errorf("Did not find any has one polymorphic association") - } else if len(hamsterToys) != 1 { - t.Errorf("Should have found only one polymorphic has one association") - } else if hamsterToys[0].Name != hamster.OtherToy.Name { - t.Errorf("Should have found the proper has one polymorphic association") - } - - hamsterToy := Toy{} - DB.Model(&hamster).Association("PreferredToy").Find(&hamsterToy) - if hamsterToy.Name != hamster.PreferredToy.Name { - t.Errorf("Should find has one polymorphic association") - } - hamsterToy = Toy{} - DB.Model(&hamster).Association("OtherToy").Find(&hamsterToy) - if hamsterToy.Name != hamster.OtherToy.Name { - t.Errorf("Should find has one polymorphic association") - } - - // Append - DB.Model(&hamster).Association("PreferredToy").Append(&Toy{ - Name: "bike 2", - }) - DB.Model(&hamster).Association("OtherToy").Append(&Toy{ - Name: "treadmill 2", - }) - - hamsterToy = Toy{} - DB.Model(&hamster).Association("PreferredToy").Find(&hamsterToy) - if hamsterToy.Name != "bike 2" { - t.Errorf("Should update has one polymorphic association with Append") - } - - hamsterToy = Toy{} - DB.Model(&hamster).Association("OtherToy").Find(&hamsterToy) - if hamsterToy.Name != "treadmill 2" { - t.Errorf("Should update has one polymorphic association with Append") - } - - if DB.Model(&hamster2).Association("PreferredToy").Count() != 1 { - t.Errorf("Hamster's toys count should be 1 after Append") - } - - if DB.Model(&hamster2).Association("OtherToy").Count() != 1 { - t.Errorf("Hamster's toys count should be 1 after Append") - } - - // Replace - DB.Model(&hamster).Association("PreferredToy").Replace(&Toy{ - Name: "bike 3", - }) - DB.Model(&hamster).Association("OtherToy").Replace(&Toy{ - Name: "treadmill 3", - }) - - hamsterToy = Toy{} - DB.Model(&hamster).Association("PreferredToy").Find(&hamsterToy) - if hamsterToy.Name != "bike 3" { - t.Errorf("Should update has one polymorphic association with Replace") - } - - hamsterToy = Toy{} - DB.Model(&hamster).Association("OtherToy").Find(&hamsterToy) - if hamsterToy.Name != "treadmill 3" { - t.Errorf("Should update has one polymorphic association with Replace") - } - - if DB.Model(&hamster2).Association("PreferredToy").Count() != 1 { - t.Errorf("hamster's toys count should be 1 after Replace") - } - - if DB.Model(&hamster2).Association("OtherToy").Count() != 1 { - t.Errorf("hamster's toys count should be 1 after Replace") - } - - // Clear - DB.Model(&hamster).Association("PreferredToy").Append(&Toy{ - Name: "bike 2", - }) - DB.Model(&hamster).Association("OtherToy").Append(&Toy{ - Name: "treadmill 2", - }) - - if DB.Model(&hamster).Association("PreferredToy").Count() != 1 { - t.Errorf("Hamster's toys should be added with Append") - } - if DB.Model(&hamster).Association("OtherToy").Count() != 1 { - t.Errorf("Hamster's toys should be added with Append") - } - - DB.Model(&hamster).Association("PreferredToy").Clear() - - if DB.Model(&hamster2).Association("PreferredToy").Count() != 0 { - t.Errorf("Hamster's preferred toy should be cleared with Clear") - } - if DB.Model(&hamster2).Association("OtherToy").Count() != 1 { - t.Errorf("Hamster's other toy should be still available") - } - - DB.Model(&hamster).Association("OtherToy").Clear() - if DB.Model(&hamster).Association("OtherToy").Count() != 0 { - t.Errorf("Hamster's other toy should be cleared with Clear") - } -} diff --git a/vendor/github.com/jinzhu/gorm/preload_test.go b/vendor/github.com/jinzhu/gorm/preload_test.go deleted file mode 100644 index 8b8b39b82384..000000000000 --- a/vendor/github.com/jinzhu/gorm/preload_test.go +++ /dev/null @@ -1,1606 +0,0 @@ -package gorm_test - -import ( - "database/sql" - "encoding/json" - "os" - "reflect" - "testing" - - "github.com/jinzhu/gorm" -) - -func getPreloadUser(name string) *User { - return getPreparedUser(name, "Preload") -} - -func checkUserHasPreloadData(user User, t *testing.T) { - u := getPreloadUser(user.Name) - if user.BillingAddress.Address1 != u.BillingAddress.Address1 { - t.Error("Failed to preload user's BillingAddress") - } - - if user.ShippingAddress.Address1 != u.ShippingAddress.Address1 { - t.Error("Failed to preload user's ShippingAddress") - } - - if user.CreditCard.Number != u.CreditCard.Number { - t.Error("Failed to preload user's CreditCard") - } - - if user.Company.Name != u.Company.Name { - t.Error("Failed to preload user's Company") - } - - if len(user.Emails) != len(u.Emails) { - t.Error("Failed to preload user's Emails") - } else { - var found int - for _, e1 := range u.Emails { - for _, e2 := range user.Emails { - if e1.Email == e2.Email { - found++ - break - } - } - } - if found != len(u.Emails) { - t.Error("Failed to preload user's email details") - } - } -} - -func TestPreload(t *testing.T) { - user1 := getPreloadUser("user1") - DB.Save(user1) - - preloadDB := DB.Where("role = ?", "Preload").Preload("BillingAddress").Preload("ShippingAddress"). - Preload("CreditCard").Preload("Emails").Preload("Company") - var user User - preloadDB.Find(&user) - checkUserHasPreloadData(user, t) - - user2 := getPreloadUser("user2") - DB.Save(user2) - - user3 := getPreloadUser("user3") - DB.Save(user3) - - var users []User - preloadDB.Find(&users) - - for _, user := range users { - checkUserHasPreloadData(user, t) - } - - var users2 []*User - preloadDB.Find(&users2) - - for _, user := range users2 { - checkUserHasPreloadData(*user, t) - } - - var users3 []*User - preloadDB.Preload("Emails", "email = ?", user3.Emails[0].Email).Find(&users3) - - for _, user := range users3 { - if user.Name == user3.Name { - if len(user.Emails) != 1 { - t.Errorf("should only preload one emails for user3 when with condition") - } - } else if len(user.Emails) != 0 { - t.Errorf("should not preload any emails for other users when with condition") - } else if user.Emails == nil { - t.Errorf("should return an empty slice to indicate zero results") - } - } -} - -func TestNestedPreload1(t *testing.T) { - type ( - Level1 struct { - ID uint - Value string - Level2ID uint - } - Level2 struct { - ID uint - Level1 Level1 - Level3ID uint - } - Level3 struct { - ID uint - Name string - Level2 Level2 - } - ) - DB.DropTableIfExists(&Level3{}) - DB.DropTableIfExists(&Level2{}) - DB.DropTableIfExists(&Level1{}) - if err := DB.AutoMigrate(&Level3{}, &Level2{}, &Level1{}).Error; err != nil { - t.Error(err) - } - - want := Level3{Level2: Level2{Level1: Level1{Value: "value"}}} - if err := DB.Create(&want).Error; err != nil { - t.Error(err) - } - - var got Level3 - if err := DB.Preload("Level2").Preload("Level2.Level1").Find(&got).Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) - } - - if err := DB.Preload("Level2").Preload("Level2.Level1").Find(&got, "name = ?", "not_found").Error; err != gorm.ErrRecordNotFound { - t.Error(err) - } -} - -func TestNestedPreload2(t *testing.T) { - type ( - Level1 struct { - ID uint - Value string - Level2ID uint - } - Level2 struct { - ID uint - Level1s []*Level1 - Level3ID uint - } - Level3 struct { - ID uint - Name string - Level2s []Level2 - } - ) - DB.DropTableIfExists(&Level3{}) - DB.DropTableIfExists(&Level2{}) - DB.DropTableIfExists(&Level1{}) - if err := DB.AutoMigrate(&Level3{}, &Level2{}, &Level1{}).Error; err != nil { - t.Error(err) - } - - want := Level3{ - Level2s: []Level2{ - { - Level1s: []*Level1{ - {Value: "value1"}, - {Value: "value2"}, - }, - }, - { - Level1s: []*Level1{ - {Value: "value3"}, - }, - }, - }, - } - if err := DB.Create(&want).Error; err != nil { - t.Error(err) - } - - var got Level3 - if err := DB.Preload("Level2s.Level1s").Find(&got).Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) - } -} - -func TestNestedPreload3(t *testing.T) { - type ( - Level1 struct { - ID uint - Value string - Level2ID uint - } - Level2 struct { - ID uint - Level1 Level1 - Level3ID uint - } - Level3 struct { - Name string - ID uint - Level2s []Level2 - } - ) - DB.DropTableIfExists(&Level3{}) - DB.DropTableIfExists(&Level2{}) - DB.DropTableIfExists(&Level1{}) - if err := DB.AutoMigrate(&Level3{}, &Level2{}, &Level1{}).Error; err != nil { - t.Error(err) - } - - want := Level3{ - Level2s: []Level2{ - {Level1: Level1{Value: "value1"}}, - {Level1: Level1{Value: "value2"}}, - }, - } - if err := DB.Create(&want).Error; err != nil { - t.Error(err) - } - - var got Level3 - if err := DB.Preload("Level2s.Level1").Find(&got).Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) - } -} - -func TestNestedPreload4(t *testing.T) { - type ( - Level1 struct { - ID uint - Value string - Level2ID uint - } - Level2 struct { - ID uint - Level1s []Level1 - Level3ID uint - } - Level3 struct { - ID uint - Name string - Level2 Level2 - } - ) - DB.DropTableIfExists(&Level3{}) - DB.DropTableIfExists(&Level2{}) - DB.DropTableIfExists(&Level1{}) - if err := DB.AutoMigrate(&Level3{}, &Level2{}, &Level1{}).Error; err != nil { - t.Error(err) - } - - want := Level3{ - Level2: Level2{ - Level1s: []Level1{ - {Value: "value1"}, - {Value: "value2"}, - }, - }, - } - if err := DB.Create(&want).Error; err != nil { - t.Error(err) - } - - var got Level3 - if err := DB.Preload("Level2.Level1s").Find(&got).Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) - } -} - -// Slice: []Level3 -func TestNestedPreload5(t *testing.T) { - type ( - Level1 struct { - ID uint - Value string - Level2ID uint - } - Level2 struct { - ID uint - Level1 Level1 - Level3ID uint - } - Level3 struct { - ID uint - Name string - Level2 Level2 - } - ) - DB.DropTableIfExists(&Level3{}) - DB.DropTableIfExists(&Level2{}) - DB.DropTableIfExists(&Level1{}) - if err := DB.AutoMigrate(&Level3{}, &Level2{}, &Level1{}).Error; err != nil { - t.Error(err) - } - - want := make([]Level3, 2) - want[0] = Level3{Level2: Level2{Level1: Level1{Value: "value"}}} - if err := DB.Create(&want[0]).Error; err != nil { - t.Error(err) - } - want[1] = Level3{Level2: Level2{Level1: Level1{Value: "value2"}}} - if err := DB.Create(&want[1]).Error; err != nil { - t.Error(err) - } - - var got []Level3 - if err := DB.Preload("Level2").Preload("Level2.Level1").Find(&got).Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) - } -} - -func TestNestedPreload6(t *testing.T) { - type ( - Level1 struct { - ID uint - Value string - Level2ID uint - } - Level2 struct { - ID uint - Level1s []Level1 - Level3ID uint - } - Level3 struct { - ID uint - Name string - Level2s []Level2 - } - ) - DB.DropTableIfExists(&Level3{}) - DB.DropTableIfExists(&Level2{}) - DB.DropTableIfExists(&Level1{}) - if err := DB.AutoMigrate(&Level3{}, &Level2{}, &Level1{}).Error; err != nil { - t.Error(err) - } - - want := make([]Level3, 2) - want[0] = Level3{ - Level2s: []Level2{ - { - Level1s: []Level1{ - {Value: "value1"}, - {Value: "value2"}, - }, - }, - { - Level1s: []Level1{ - {Value: "value3"}, - }, - }, - }, - } - if err := DB.Create(&want[0]).Error; err != nil { - t.Error(err) - } - - want[1] = Level3{ - Level2s: []Level2{ - { - Level1s: []Level1{ - {Value: "value3"}, - {Value: "value4"}, - }, - }, - { - Level1s: []Level1{ - {Value: "value5"}, - }, - }, - }, - } - if err := DB.Create(&want[1]).Error; err != nil { - t.Error(err) - } - - var got []Level3 - if err := DB.Preload("Level2s.Level1s").Find(&got).Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) - } -} - -func TestNestedPreload7(t *testing.T) { - type ( - Level1 struct { - ID uint - Value string - Level2ID uint - } - Level2 struct { - ID uint - Level1 Level1 - Level3ID uint - } - Level3 struct { - ID uint - Name string - Level2s []Level2 - } - ) - DB.DropTableIfExists(&Level3{}) - DB.DropTableIfExists(&Level2{}) - DB.DropTableIfExists(&Level1{}) - if err := DB.AutoMigrate(&Level3{}, &Level2{}, &Level1{}).Error; err != nil { - t.Error(err) - } - - want := make([]Level3, 2) - want[0] = Level3{ - Level2s: []Level2{ - {Level1: Level1{Value: "value1"}}, - {Level1: Level1{Value: "value2"}}, - }, - } - if err := DB.Create(&want[0]).Error; err != nil { - t.Error(err) - } - - want[1] = Level3{ - Level2s: []Level2{ - {Level1: Level1{Value: "value3"}}, - {Level1: Level1{Value: "value4"}}, - }, - } - if err := DB.Create(&want[1]).Error; err != nil { - t.Error(err) - } - - var got []Level3 - if err := DB.Preload("Level2s.Level1").Find(&got).Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) - } -} - -func TestNestedPreload8(t *testing.T) { - type ( - Level1 struct { - ID uint - Value string - Level2ID uint - } - Level2 struct { - ID uint - Level1s []Level1 - Level3ID uint - } - Level3 struct { - ID uint - Name string - Level2 Level2 - } - ) - DB.DropTableIfExists(&Level3{}) - DB.DropTableIfExists(&Level2{}) - DB.DropTableIfExists(&Level1{}) - if err := DB.AutoMigrate(&Level3{}, &Level2{}, &Level1{}).Error; err != nil { - t.Error(err) - } - - want := make([]Level3, 2) - want[0] = Level3{ - Level2: Level2{ - Level1s: []Level1{ - {Value: "value1"}, - {Value: "value2"}, - }, - }, - } - if err := DB.Create(&want[0]).Error; err != nil { - t.Error(err) - } - want[1] = Level3{ - Level2: Level2{ - Level1s: []Level1{ - {Value: "value3"}, - {Value: "value4"}, - }, - }, - } - if err := DB.Create(&want[1]).Error; err != nil { - t.Error(err) - } - - var got []Level3 - if err := DB.Preload("Level2.Level1s").Find(&got).Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) - } -} - -func TestNestedPreload9(t *testing.T) { - type ( - Level0 struct { - ID uint - Value string - Level1ID uint - } - Level1 struct { - ID uint - Value string - Level2ID uint - Level2_1ID uint - Level0s []Level0 - } - Level2 struct { - ID uint - Level1s []Level1 - Level3ID uint - } - Level2_1 struct { - ID uint - Level1s []Level1 - Level3ID uint - } - Level3 struct { - ID uint - Name string - Level2 Level2 - Level2_1 Level2_1 - } - ) - DB.DropTableIfExists(&Level3{}) - DB.DropTableIfExists(&Level2{}) - DB.DropTableIfExists(&Level2_1{}) - DB.DropTableIfExists(&Level1{}) - DB.DropTableIfExists(&Level0{}) - if err := DB.AutoMigrate(&Level3{}, &Level2{}, &Level1{}, &Level2_1{}, &Level0{}).Error; err != nil { - t.Error(err) - } - - want := make([]Level3, 2) - want[0] = Level3{ - Level2: Level2{ - Level1s: []Level1{ - {Value: "value1"}, - {Value: "value2"}, - }, - }, - Level2_1: Level2_1{ - Level1s: []Level1{ - { - Value: "value1-1", - Level0s: []Level0{{Value: "Level0-1"}}, - }, - { - Value: "value2-2", - Level0s: []Level0{{Value: "Level0-2"}}, - }, - }, - }, - } - if err := DB.Create(&want[0]).Error; err != nil { - t.Error(err) - } - want[1] = Level3{ - Level2: Level2{ - Level1s: []Level1{ - {Value: "value3"}, - {Value: "value4"}, - }, - }, - Level2_1: Level2_1{ - Level1s: []Level1{ - { - Value: "value3-3", - Level0s: []Level0{}, - }, - { - Value: "value4-4", - Level0s: []Level0{}, - }, - }, - }, - } - if err := DB.Create(&want[1]).Error; err != nil { - t.Error(err) - } - - var got []Level3 - if err := DB.Preload("Level2").Preload("Level2.Level1s").Preload("Level2_1").Preload("Level2_1.Level1s").Preload("Level2_1.Level1s.Level0s").Find(&got).Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) - } -} - -type LevelA1 struct { - ID uint - Value string -} - -type LevelA2 struct { - ID uint - Value string - LevelA3s []*LevelA3 -} - -type LevelA3 struct { - ID uint - Value string - LevelA1ID sql.NullInt64 - LevelA1 *LevelA1 - LevelA2ID sql.NullInt64 - LevelA2 *LevelA2 -} - -func TestNestedPreload10(t *testing.T) { - DB.DropTableIfExists(&LevelA3{}) - DB.DropTableIfExists(&LevelA2{}) - DB.DropTableIfExists(&LevelA1{}) - - if err := DB.AutoMigrate(&LevelA1{}, &LevelA2{}, &LevelA3{}).Error; err != nil { - t.Error(err) - } - - levelA1 := &LevelA1{Value: "foo"} - if err := DB.Save(levelA1).Error; err != nil { - t.Error(err) - } - - want := []*LevelA2{ - { - Value: "bar", - LevelA3s: []*LevelA3{ - { - Value: "qux", - LevelA1: levelA1, - }, - }, - }, - { - Value: "bar 2", - LevelA3s: []*LevelA3{}, - }, - } - for _, levelA2 := range want { - if err := DB.Save(levelA2).Error; err != nil { - t.Error(err) - } - } - - var got []*LevelA2 - if err := DB.Preload("LevelA3s.LevelA1").Find(&got).Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) - } -} - -type LevelB1 struct { - ID uint - Value string - LevelB3s []*LevelB3 -} - -type LevelB2 struct { - ID uint - Value string -} - -type LevelB3 struct { - ID uint - Value string - LevelB1ID sql.NullInt64 - LevelB1 *LevelB1 - LevelB2s []*LevelB2 `gorm:"many2many:levelb1_levelb3_levelb2s"` -} - -func TestNestedPreload11(t *testing.T) { - DB.DropTableIfExists(&LevelB2{}) - DB.DropTableIfExists(&LevelB3{}) - DB.DropTableIfExists(&LevelB1{}) - if err := DB.AutoMigrate(&LevelB1{}, &LevelB2{}, &LevelB3{}).Error; err != nil { - t.Error(err) - } - - levelB1 := &LevelB1{Value: "foo"} - if err := DB.Create(levelB1).Error; err != nil { - t.Error(err) - } - - levelB3 := &LevelB3{ - Value: "bar", - LevelB1ID: sql.NullInt64{Valid: true, Int64: int64(levelB1.ID)}, - } - if err := DB.Create(levelB3).Error; err != nil { - t.Error(err) - } - levelB1.LevelB3s = []*LevelB3{levelB3} - - want := []*LevelB1{levelB1} - var got []*LevelB1 - if err := DB.Preload("LevelB3s.LevelB2s").Find(&got).Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) - } -} - -type LevelC1 struct { - ID uint - Value string - LevelC2ID uint -} - -type LevelC2 struct { - ID uint - Value string - LevelC1 LevelC1 -} - -type LevelC3 struct { - ID uint - Value string - LevelC2ID uint - LevelC2 LevelC2 -} - -func TestNestedPreload12(t *testing.T) { - DB.DropTableIfExists(&LevelC2{}) - DB.DropTableIfExists(&LevelC3{}) - DB.DropTableIfExists(&LevelC1{}) - if err := DB.AutoMigrate(&LevelC1{}, &LevelC2{}, &LevelC3{}).Error; err != nil { - t.Error(err) - } - - level2 := LevelC2{ - Value: "c2", - LevelC1: LevelC1{ - Value: "c1", - }, - } - DB.Create(&level2) - - want := []LevelC3{ - { - Value: "c3-1", - LevelC2: level2, - }, { - Value: "c3-2", - LevelC2: level2, - }, - } - - for i := range want { - if err := DB.Create(&want[i]).Error; err != nil { - t.Error(err) - } - } - - var got []LevelC3 - if err := DB.Preload("LevelC2").Preload("LevelC2.LevelC1").Find(&got).Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) - } -} - -func TestManyToManyPreloadWithMultiPrimaryKeys(t *testing.T) { - if dialect := os.Getenv("GORM_DIALECT"); dialect == "" || dialect == "sqlite" { - return - } - - type ( - Level1 struct { - ID uint `gorm:"primary_key;"` - LanguageCode string `gorm:"primary_key"` - Value string - } - Level2 struct { - ID uint `gorm:"primary_key;"` - LanguageCode string `gorm:"primary_key"` - Value string - Level1s []Level1 `gorm:"many2many:levels;"` - } - ) - - DB.DropTableIfExists(&Level2{}) - DB.DropTableIfExists(&Level1{}) - DB.DropTableIfExists("levels") - - if err := DB.AutoMigrate(&Level2{}, &Level1{}).Error; err != nil { - t.Error(err) - } - - want := Level2{Value: "Bob", LanguageCode: "ru", Level1s: []Level1{ - {Value: "ru", LanguageCode: "ru"}, - {Value: "en", LanguageCode: "en"}, - }} - if err := DB.Save(&want).Error; err != nil { - t.Error(err) - } - - want2 := Level2{Value: "Tom", LanguageCode: "zh", Level1s: []Level1{ - {Value: "zh", LanguageCode: "zh"}, - {Value: "de", LanguageCode: "de"}, - }} - if err := DB.Save(&want2).Error; err != nil { - t.Error(err) - } - - var got Level2 - if err := DB.Preload("Level1s").Find(&got, "value = ?", "Bob").Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) - } - - var got2 Level2 - if err := DB.Preload("Level1s").Find(&got2, "value = ?", "Tom").Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got2, want2) { - t.Errorf("got %s; want %s", toJSONString(got2), toJSONString(want2)) - } - - var got3 []Level2 - if err := DB.Preload("Level1s").Find(&got3, "value IN (?)", []string{"Bob", "Tom"}).Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got3, []Level2{got, got2}) { - t.Errorf("got %s; want %s", toJSONString(got3), toJSONString([]Level2{got, got2})) - } - - var got4 []Level2 - if err := DB.Preload("Level1s", "value IN (?)", []string{"zh", "ru"}).Find(&got4, "value IN (?)", []string{"Bob", "Tom"}).Error; err != nil { - t.Error(err) - } - - var ruLevel1 Level1 - var zhLevel1 Level1 - DB.First(&ruLevel1, "value = ?", "ru") - DB.First(&zhLevel1, "value = ?", "zh") - - got.Level1s = []Level1{ruLevel1} - got2.Level1s = []Level1{zhLevel1} - if !reflect.DeepEqual(got4, []Level2{got, got2}) { - t.Errorf("got %s; want %s", toJSONString(got4), toJSONString([]Level2{got, got2})) - } - - if err := DB.Preload("Level1s").Find(&got4, "value IN (?)", []string{"non-existing"}).Error; err != nil { - t.Error(err) - } -} - -func TestManyToManyPreloadForNestedPointer(t *testing.T) { - type ( - Level1 struct { - ID uint - Value string - } - Level2 struct { - ID uint - Value string - Level1s []*Level1 `gorm:"many2many:levels;"` - } - Level3 struct { - ID uint - Value string - Level2ID sql.NullInt64 - Level2 *Level2 - } - ) - - DB.DropTableIfExists(&Level3{}) - DB.DropTableIfExists(&Level2{}) - DB.DropTableIfExists(&Level1{}) - DB.DropTableIfExists("levels") - - if err := DB.AutoMigrate(&Level3{}, &Level2{}, &Level1{}).Error; err != nil { - t.Error(err) - } - - want := Level3{ - Value: "Bob", - Level2: &Level2{ - Value: "Foo", - Level1s: []*Level1{ - {Value: "ru"}, - {Value: "en"}, - }, - }, - } - if err := DB.Save(&want).Error; err != nil { - t.Error(err) - } - - want2 := Level3{ - Value: "Tom", - Level2: &Level2{ - Value: "Bar", - Level1s: []*Level1{ - {Value: "zh"}, - {Value: "de"}, - }, - }, - } - if err := DB.Save(&want2).Error; err != nil { - t.Error(err) - } - - var got Level3 - if err := DB.Preload("Level2.Level1s").Find(&got, "value = ?", "Bob").Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) - } - - var got2 Level3 - if err := DB.Preload("Level2.Level1s").Find(&got2, "value = ?", "Tom").Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got2, want2) { - t.Errorf("got %s; want %s", toJSONString(got2), toJSONString(want2)) - } - - var got3 []Level3 - if err := DB.Preload("Level2.Level1s").Find(&got3, "value IN (?)", []string{"Bob", "Tom"}).Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got3, []Level3{got, got2}) { - t.Errorf("got %s; want %s", toJSONString(got3), toJSONString([]Level3{got, got2})) - } - - var got4 []Level3 - if err := DB.Preload("Level2.Level1s", "value IN (?)", []string{"zh", "ru"}).Find(&got4, "value IN (?)", []string{"Bob", "Tom"}).Error; err != nil { - t.Error(err) - } - - var got5 Level3 - DB.Preload("Level2.Level1s").Find(&got5, "value = ?", "bogus") - - var ruLevel1 Level1 - var zhLevel1 Level1 - DB.First(&ruLevel1, "value = ?", "ru") - DB.First(&zhLevel1, "value = ?", "zh") - - got.Level2.Level1s = []*Level1{&ruLevel1} - got2.Level2.Level1s = []*Level1{&zhLevel1} - if !reflect.DeepEqual(got4, []Level3{got, got2}) { - t.Errorf("got %s; want %s", toJSONString(got4), toJSONString([]Level3{got, got2})) - } -} - -func TestNestedManyToManyPreload(t *testing.T) { - type ( - Level1 struct { - ID uint - Value string - } - Level2 struct { - ID uint - Value string - Level1s []*Level1 `gorm:"many2many:level1_level2;"` - } - Level3 struct { - ID uint - Value string - Level2s []Level2 `gorm:"many2many:level2_level3;"` - } - ) - - DB.DropTableIfExists(&Level1{}) - DB.DropTableIfExists(&Level2{}) - DB.DropTableIfExists(&Level3{}) - DB.DropTableIfExists("level1_level2") - DB.DropTableIfExists("level2_level3") - - if err := DB.AutoMigrate(&Level3{}, &Level2{}, &Level1{}).Error; err != nil { - t.Error(err) - } - - want := Level3{ - Value: "Level3", - Level2s: []Level2{ - { - Value: "Bob", - Level1s: []*Level1{ - {Value: "ru"}, - {Value: "en"}, - }, - }, { - Value: "Tom", - Level1s: []*Level1{ - {Value: "zh"}, - {Value: "de"}, - }, - }, - }, - } - - if err := DB.Save(&want).Error; err != nil { - t.Error(err) - } - - var got Level3 - if err := DB.Preload("Level2s").Preload("Level2s.Level1s").Find(&got, "value = ?", "Level3").Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) - } - - if err := DB.Preload("Level2s.Level1s").Find(&got, "value = ?", "not_found").Error; err != gorm.ErrRecordNotFound { - t.Error(err) - } -} - -func TestNestedManyToManyPreload2(t *testing.T) { - type ( - Level1 struct { - ID uint - Value string - } - Level2 struct { - ID uint - Value string - Level1s []*Level1 `gorm:"many2many:level1_level2;"` - } - Level3 struct { - ID uint - Value string - Level2ID sql.NullInt64 - Level2 *Level2 - } - ) - - DB.DropTableIfExists(&Level1{}) - DB.DropTableIfExists(&Level2{}) - DB.DropTableIfExists(&Level3{}) - DB.DropTableIfExists("level1_level2") - - if err := DB.AutoMigrate(&Level3{}, &Level2{}, &Level1{}).Error; err != nil { - t.Error(err) - } - - want := Level3{ - Value: "Level3", - Level2: &Level2{ - Value: "Bob", - Level1s: []*Level1{ - {Value: "ru"}, - {Value: "en"}, - }, - }, - } - - if err := DB.Save(&want).Error; err != nil { - t.Error(err) - } - - var got Level3 - if err := DB.Preload("Level2.Level1s").Find(&got, "value = ?", "Level3").Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) - } - - if err := DB.Preload("Level2.Level1s").Find(&got, "value = ?", "not_found").Error; err != gorm.ErrRecordNotFound { - t.Error(err) - } -} - -func TestNestedManyToManyPreload3(t *testing.T) { - type ( - Level1 struct { - ID uint - Value string - } - Level2 struct { - ID uint - Value string - Level1s []*Level1 `gorm:"many2many:level1_level2;"` - } - Level3 struct { - ID uint - Value string - Level2ID sql.NullInt64 - Level2 *Level2 - } - ) - - DB.DropTableIfExists(&Level1{}) - DB.DropTableIfExists(&Level2{}) - DB.DropTableIfExists(&Level3{}) - DB.DropTableIfExists("level1_level2") - - if err := DB.AutoMigrate(&Level3{}, &Level2{}, &Level1{}).Error; err != nil { - t.Error(err) - } - - level1Zh := &Level1{Value: "zh"} - level1Ru := &Level1{Value: "ru"} - level1En := &Level1{Value: "en"} - - level21 := &Level2{ - Value: "Level2-1", - Level1s: []*Level1{level1Zh, level1Ru}, - } - - level22 := &Level2{ - Value: "Level2-2", - Level1s: []*Level1{level1Zh, level1En}, - } - - wants := []*Level3{ - { - Value: "Level3-1", - Level2: level21, - }, - { - Value: "Level3-2", - Level2: level22, - }, - { - Value: "Level3-3", - Level2: level21, - }, - } - - for _, want := range wants { - if err := DB.Save(&want).Error; err != nil { - t.Error(err) - } - } - - var gots []*Level3 - if err := DB.Preload("Level2.Level1s", func(db *gorm.DB) *gorm.DB { - return db.Order("level1.id ASC") - }).Find(&gots).Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(gots, wants) { - t.Errorf("got %s; want %s", toJSONString(gots), toJSONString(wants)) - } -} - -func TestNestedManyToManyPreload3ForStruct(t *testing.T) { - type ( - Level1 struct { - ID uint - Value string - } - Level2 struct { - ID uint - Value string - Level1s []Level1 `gorm:"many2many:level1_level2;"` - } - Level3 struct { - ID uint - Value string - Level2ID sql.NullInt64 - Level2 Level2 - } - ) - - DB.DropTableIfExists(&Level1{}) - DB.DropTableIfExists(&Level2{}) - DB.DropTableIfExists(&Level3{}) - DB.DropTableIfExists("level1_level2") - - if err := DB.AutoMigrate(&Level3{}, &Level2{}, &Level1{}).Error; err != nil { - t.Error(err) - } - - level1Zh := Level1{Value: "zh"} - level1Ru := Level1{Value: "ru"} - level1En := Level1{Value: "en"} - - level21 := Level2{ - Value: "Level2-1", - Level1s: []Level1{level1Zh, level1Ru}, - } - - level22 := Level2{ - Value: "Level2-2", - Level1s: []Level1{level1Zh, level1En}, - } - - wants := []*Level3{ - { - Value: "Level3-1", - Level2: level21, - }, - { - Value: "Level3-2", - Level2: level22, - }, - { - Value: "Level3-3", - Level2: level21, - }, - } - - for _, want := range wants { - if err := DB.Save(&want).Error; err != nil { - t.Error(err) - } - } - - var gots []*Level3 - if err := DB.Preload("Level2.Level1s", func(db *gorm.DB) *gorm.DB { - return db.Order("level1.id ASC") - }).Find(&gots).Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(gots, wants) { - t.Errorf("got %s; want %s", toJSONString(gots), toJSONString(wants)) - } -} - -func TestNestedManyToManyPreload4(t *testing.T) { - type ( - Level4 struct { - ID uint - Value string - Level3ID uint - } - Level3 struct { - ID uint - Value string - Level4s []*Level4 - } - Level2 struct { - ID uint - Value string - Level3s []*Level3 `gorm:"many2many:level2_level3;"` - } - Level1 struct { - ID uint - Value string - Level2s []*Level2 `gorm:"many2many:level1_level2;"` - } - ) - - DB.DropTableIfExists(&Level1{}) - DB.DropTableIfExists(&Level2{}) - DB.DropTableIfExists(&Level3{}) - DB.DropTableIfExists(&Level4{}) - DB.DropTableIfExists("level1_level2") - DB.DropTableIfExists("level2_level3") - - dummy := Level1{ - Value: "Level1", - Level2s: []*Level2{{ - Value: "Level2", - Level3s: []*Level3{{ - Value: "Level3", - Level4s: []*Level4{{ - Value: "Level4", - }}, - }}, - }}, - } - - if err := DB.AutoMigrate(&Level4{}, &Level3{}, &Level2{}, &Level1{}).Error; err != nil { - t.Error(err) - } - - if err := DB.Save(&dummy).Error; err != nil { - t.Error(err) - } - - var level1 Level1 - if err := DB.Preload("Level2s").Preload("Level2s.Level3s").Preload("Level2s.Level3s.Level4s").First(&level1).Error; err != nil { - t.Error(err) - } -} - -func TestManyToManyPreloadForPointer(t *testing.T) { - type ( - Level1 struct { - ID uint - Value string - } - Level2 struct { - ID uint - Value string - Level1s []*Level1 `gorm:"many2many:levels;"` - } - ) - - DB.DropTableIfExists(&Level2{}) - DB.DropTableIfExists(&Level1{}) - DB.DropTableIfExists("levels") - - if err := DB.AutoMigrate(&Level2{}, &Level1{}).Error; err != nil { - t.Error(err) - } - - want := Level2{Value: "Bob", Level1s: []*Level1{ - {Value: "ru"}, - {Value: "en"}, - }} - if err := DB.Save(&want).Error; err != nil { - t.Error(err) - } - - want2 := Level2{Value: "Tom", Level1s: []*Level1{ - {Value: "zh"}, - {Value: "de"}, - }} - if err := DB.Save(&want2).Error; err != nil { - t.Error(err) - } - - var got Level2 - if err := DB.Preload("Level1s").Find(&got, "value = ?", "Bob").Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) - } - - var got2 Level2 - if err := DB.Preload("Level1s").Find(&got2, "value = ?", "Tom").Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got2, want2) { - t.Errorf("got %s; want %s", toJSONString(got2), toJSONString(want2)) - } - - var got3 []Level2 - if err := DB.Preload("Level1s").Find(&got3, "value IN (?)", []string{"Bob", "Tom"}).Error; err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got3, []Level2{got, got2}) { - t.Errorf("got %s; want %s", toJSONString(got3), toJSONString([]Level2{got, got2})) - } - - var got4 []Level2 - if err := DB.Preload("Level1s", "value IN (?)", []string{"zh", "ru"}).Find(&got4, "value IN (?)", []string{"Bob", "Tom"}).Error; err != nil { - t.Error(err) - } - - var got5 Level2 - DB.Preload("Level1s").First(&got5, "value = ?", "bogus") - - var ruLevel1 Level1 - var zhLevel1 Level1 - DB.First(&ruLevel1, "value = ?", "ru") - DB.First(&zhLevel1, "value = ?", "zh") - - got.Level1s = []*Level1{&ruLevel1} - got2.Level1s = []*Level1{&zhLevel1} - if !reflect.DeepEqual(got4, []Level2{got, got2}) { - t.Errorf("got %s; want %s", toJSONString(got4), toJSONString([]Level2{got, got2})) - } -} - -func TestNilPointerSlice(t *testing.T) { - type ( - Level3 struct { - ID uint - Value string - } - Level2 struct { - ID uint - Value string - Level3ID uint - Level3 *Level3 - } - Level1 struct { - ID uint - Value string - Level2ID uint - Level2 *Level2 - } - ) - - DB.DropTableIfExists(&Level3{}) - DB.DropTableIfExists(&Level2{}) - DB.DropTableIfExists(&Level1{}) - - if err := DB.AutoMigrate(&Level3{}, &Level2{}, &Level1{}).Error; err != nil { - t.Error(err) - } - - want := Level1{ - Value: "Bob", - Level2: &Level2{ - Value: "en", - Level3: &Level3{ - Value: "native", - }, - }, - } - if err := DB.Save(&want).Error; err != nil { - t.Error(err) - } - - want2 := Level1{ - Value: "Tom", - Level2: nil, - } - if err := DB.Save(&want2).Error; err != nil { - t.Error(err) - } - - var got []Level1 - if err := DB.Preload("Level2").Preload("Level2.Level3").Find(&got).Error; err != nil { - t.Error(err) - } - - if len(got) != 2 { - t.Errorf("got %v items, expected 2", len(got)) - } - - if !reflect.DeepEqual(got[0], want) && !reflect.DeepEqual(got[1], want) { - t.Errorf("got %s; want array containing %s", toJSONString(got), toJSONString(want)) - } - - if !reflect.DeepEqual(got[0], want2) && !reflect.DeepEqual(got[1], want2) { - t.Errorf("got %s; want array containing %s", toJSONString(got), toJSONString(want2)) - } -} - -func TestNilPointerSlice2(t *testing.T) { - type ( - Level4 struct { - ID uint - } - Level3 struct { - ID uint - Level4ID sql.NullInt64 `sql:"index"` - Level4 *Level4 - } - Level2 struct { - ID uint - Level3s []*Level3 `gorm:"many2many:level2_level3s"` - } - Level1 struct { - ID uint - Level2ID sql.NullInt64 `sql:"index"` - Level2 *Level2 - } - ) - - DB.DropTableIfExists(new(Level4)) - DB.DropTableIfExists(new(Level3)) - DB.DropTableIfExists(new(Level2)) - DB.DropTableIfExists(new(Level1)) - - if err := DB.AutoMigrate(new(Level4), new(Level3), new(Level2), new(Level1)).Error; err != nil { - t.Error(err) - } - - want := new(Level1) - if err := DB.Save(want).Error; err != nil { - t.Error(err) - } - - got := new(Level1) - err := DB.Preload("Level2.Level3s.Level4").Last(&got).Error - if err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) - } -} - -func TestPrefixedPreloadDuplication(t *testing.T) { - type ( - Level4 struct { - ID uint - Name string - Level3ID uint - } - Level3 struct { - ID uint - Name string - Level4s []*Level4 - } - Level2 struct { - ID uint - Name string - Level3ID sql.NullInt64 `sql:"index"` - Level3 *Level3 - } - Level1 struct { - ID uint - Name string - Level2ID sql.NullInt64 `sql:"index"` - Level2 *Level2 - } - ) - - DB.DropTableIfExists(new(Level3)) - DB.DropTableIfExists(new(Level4)) - DB.DropTableIfExists(new(Level2)) - DB.DropTableIfExists(new(Level1)) - - if err := DB.AutoMigrate(new(Level3), new(Level4), new(Level2), new(Level1)).Error; err != nil { - t.Error(err) - } - - lvl := &Level3{} - if err := DB.Save(lvl).Error; err != nil { - t.Error(err) - } - - sublvl1 := &Level4{Level3ID: lvl.ID} - if err := DB.Save(sublvl1).Error; err != nil { - t.Error(err) - } - sublvl2 := &Level4{Level3ID: lvl.ID} - if err := DB.Save(sublvl2).Error; err != nil { - t.Error(err) - } - - lvl.Level4s = []*Level4{sublvl1, sublvl2} - - want1 := Level1{ - Level2: &Level2{ - Level3: lvl, - }, - } - if err := DB.Save(&want1).Error; err != nil { - t.Error(err) - } - - want2 := Level1{ - Level2: &Level2{ - Level3: lvl, - }, - } - if err := DB.Save(&want2).Error; err != nil { - t.Error(err) - } - - want := []Level1{want1, want2} - - var got []Level1 - err := DB.Preload("Level2.Level3.Level4s").Find(&got).Error - if err != nil { - t.Error(err) - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want)) - } -} - -func toJSONString(v interface{}) []byte { - r, _ := json.MarshalIndent(v, "", " ") - return r -} diff --git a/vendor/github.com/jinzhu/gorm/query_test.go b/vendor/github.com/jinzhu/gorm/query_test.go deleted file mode 100644 index d6b23ddfe375..000000000000 --- a/vendor/github.com/jinzhu/gorm/query_test.go +++ /dev/null @@ -1,662 +0,0 @@ -package gorm_test - -import ( - "fmt" - "reflect" - - "github.com/jinzhu/gorm" - - "testing" - "time" -) - -func TestFirstAndLast(t *testing.T) { - DB.Save(&User{Name: "user1", Emails: []Email{{Email: "user1@example.com"}}}) - DB.Save(&User{Name: "user2", Emails: []Email{{Email: "user2@example.com"}}}) - - var user1, user2, user3, user4 User - DB.First(&user1) - DB.Order("id").Limit(1).Find(&user2) - - ptrOfUser3 := &user3 - DB.Last(&ptrOfUser3) - DB.Order("id desc").Limit(1).Find(&user4) - if user1.Id != user2.Id || user3.Id != user4.Id { - t.Errorf("First and Last should by order by primary key") - } - - var users []User - DB.First(&users) - if len(users) != 1 { - t.Errorf("Find first record as slice") - } - - var user User - if DB.Joins("left join emails on emails.user_id = users.id").First(&user).Error != nil { - t.Errorf("Should not raise any error when order with Join table") - } - - if user.Email != "" { - t.Errorf("User's Email should be blank as no one set it") - } -} - -func TestFirstAndLastWithNoStdPrimaryKey(t *testing.T) { - DB.Save(&Animal{Name: "animal1"}) - DB.Save(&Animal{Name: "animal2"}) - - var animal1, animal2, animal3, animal4 Animal - DB.First(&animal1) - DB.Order("counter").Limit(1).Find(&animal2) - - DB.Last(&animal3) - DB.Order("counter desc").Limit(1).Find(&animal4) - if animal1.Counter != animal2.Counter || animal3.Counter != animal4.Counter { - t.Errorf("First and Last should work correctly") - } -} - -func TestFirstAndLastWithRaw(t *testing.T) { - user1 := User{Name: "user", Emails: []Email{{Email: "user1@example.com"}}} - user2 := User{Name: "user", Emails: []Email{{Email: "user2@example.com"}}} - DB.Save(&user1) - DB.Save(&user2) - - var user3, user4 User - DB.Raw("select * from users WHERE name = ?", "user").First(&user3) - if user3.Id != user1.Id { - t.Errorf("Find first record with raw") - } - - DB.Raw("select * from users WHERE name = ?", "user").Last(&user4) - if user4.Id != user2.Id { - t.Errorf("Find last record with raw") - } -} - -func TestUIntPrimaryKey(t *testing.T) { - var animal Animal - DB.First(&animal, uint64(1)) - if animal.Counter != 1 { - t.Errorf("Fetch a record from with a non-int primary key should work, but failed") - } - - DB.Model(Animal{}).Where(Animal{Counter: uint64(2)}).Scan(&animal) - if animal.Counter != 2 { - t.Errorf("Fetch a record from with a non-int primary key should work, but failed") - } -} - -func TestStringPrimaryKeyForNumericValueStartingWithZero(t *testing.T) { - type AddressByZipCode struct { - ZipCode string `gorm:"primary_key"` - Address string - } - - DB.AutoMigrate(&AddressByZipCode{}) - DB.Create(&AddressByZipCode{ZipCode: "00501", Address: "Holtsville"}) - - var address AddressByZipCode - DB.First(&address, "00501") - if address.ZipCode != "00501" { - t.Errorf("Fetch a record from with a string primary key for a numeric value starting with zero should work, but failed") - } -} - -func TestFindAsSliceOfPointers(t *testing.T) { - DB.Save(&User{Name: "user"}) - - var users []User - DB.Find(&users) - - var userPointers []*User - DB.Find(&userPointers) - - if len(users) == 0 || len(users) != len(userPointers) { - t.Errorf("Find slice of pointers") - } -} - -func TestSearchWithPlainSQL(t *testing.T) { - user1 := User{Name: "PlainSqlUser1", Age: 1, Birthday: parseTime("2000-1-1")} - user2 := User{Name: "PlainSqlUser2", Age: 10, Birthday: parseTime("2010-1-1")} - user3 := User{Name: "PlainSqlUser3", Age: 20, Birthday: parseTime("2020-1-1")} - DB.Save(&user1).Save(&user2).Save(&user3) - scopedb := DB.Where("name LIKE ?", "%PlainSqlUser%") - - if DB.Where("name = ?", user1.Name).First(&User{}).RecordNotFound() { - t.Errorf("Search with plain SQL") - } - - if DB.Where("name LIKE ?", "%"+user1.Name+"%").First(&User{}).RecordNotFound() { - t.Errorf("Search with plan SQL (regexp)") - } - - var users []User - DB.Find(&users, "name LIKE ? and age > ?", "%PlainSqlUser%", 1) - if len(users) != 2 { - t.Errorf("Should found 2 users that age > 1, but got %v", len(users)) - } - - DB.Where("name LIKE ?", "%PlainSqlUser%").Where("age >= ?", 1).Find(&users) - if len(users) != 3 { - t.Errorf("Should found 3 users that age >= 1, but got %v", len(users)) - } - - scopedb.Where("age <> ?", 20).Find(&users) - if len(users) != 2 { - t.Errorf("Should found 2 users age != 20, but got %v", len(users)) - } - - scopedb.Where("birthday > ?", parseTime("2000-1-1")).Find(&users) - if len(users) != 2 { - t.Errorf("Should found 2 users's birthday > 2000-1-1, but got %v", len(users)) - } - - scopedb.Where("birthday > ?", "2002-10-10").Find(&users) - if len(users) != 2 { - t.Errorf("Should found 2 users's birthday >= 2002-10-10, but got %v", len(users)) - } - - scopedb.Where("birthday >= ?", "2010-1-1").Where("birthday < ?", "2020-1-1").Find(&users) - if len(users) != 1 { - t.Errorf("Should found 1 users's birthday < 2020-1-1 and >= 2010-1-1, but got %v", len(users)) - } - - DB.Where("name in (?)", []string{user1.Name, user2.Name}).Find(&users) - if len(users) != 2 { - t.Errorf("Should found 2 users, but got %v", len(users)) - } - - DB.Where("id in (?)", []int64{user1.Id, user2.Id, user3.Id}).Find(&users) - if len(users) != 3 { - t.Errorf("Should found 3 users, but got %v", len(users)) - } - - DB.Where("id in (?)", user1.Id).Find(&users) - if len(users) != 1 { - t.Errorf("Should found 1 users, but got %v", len(users)) - } - - if err := DB.Where("id IN (?)", []string{}).Find(&users).Error; err != nil { - t.Error("no error should happen when query with empty slice, but got: ", err) - } - - if err := DB.Not("id IN (?)", []string{}).Find(&users).Error; err != nil { - t.Error("no error should happen when query with empty slice, but got: ", err) - } - - if DB.Where("name = ?", "none existing").Find(&[]User{}).RecordNotFound() { - t.Errorf("Should not get RecordNotFound error when looking for none existing records") - } -} - -func TestSearchWithStruct(t *testing.T) { - user1 := User{Name: "StructSearchUser1", Age: 1, Birthday: parseTime("2000-1-1")} - user2 := User{Name: "StructSearchUser2", Age: 10, Birthday: parseTime("2010-1-1")} - user3 := User{Name: "StructSearchUser3", Age: 20, Birthday: parseTime("2020-1-1")} - DB.Save(&user1).Save(&user2).Save(&user3) - - if DB.Where(user1.Id).First(&User{}).RecordNotFound() { - t.Errorf("Search with primary key") - } - - if DB.First(&User{}, user1.Id).RecordNotFound() { - t.Errorf("Search with primary key as inline condition") - } - - if DB.First(&User{}, fmt.Sprintf("%v", user1.Id)).RecordNotFound() { - t.Errorf("Search with primary key as inline condition") - } - - var users []User - DB.Where([]int64{user1.Id, user2.Id, user3.Id}).Find(&users) - if len(users) != 3 { - t.Errorf("Should found 3 users when search with primary keys, but got %v", len(users)) - } - - var user User - DB.First(&user, &User{Name: user1.Name}) - if user.Id == 0 || user.Name != user1.Name { - t.Errorf("Search first record with inline pointer of struct") - } - - DB.First(&user, User{Name: user1.Name}) - if user.Id == 0 || user.Name != user.Name { - t.Errorf("Search first record with inline struct") - } - - DB.Where(&User{Name: user1.Name}).First(&user) - if user.Id == 0 || user.Name != user1.Name { - t.Errorf("Search first record with where struct") - } - - DB.Find(&users, &User{Name: user2.Name}) - if len(users) != 1 { - t.Errorf("Search all records with inline struct") - } -} - -func TestSearchWithMap(t *testing.T) { - companyID := 1 - user1 := User{Name: "MapSearchUser1", Age: 1, Birthday: parseTime("2000-1-1")} - user2 := User{Name: "MapSearchUser2", Age: 10, Birthday: parseTime("2010-1-1")} - user3 := User{Name: "MapSearchUser3", Age: 20, Birthday: parseTime("2020-1-1")} - user4 := User{Name: "MapSearchUser4", Age: 30, Birthday: parseTime("2020-1-1"), CompanyID: &companyID} - DB.Save(&user1).Save(&user2).Save(&user3).Save(&user4) - - var user User - DB.First(&user, map[string]interface{}{"name": user1.Name}) - if user.Id == 0 || user.Name != user1.Name { - t.Errorf("Search first record with inline map") - } - - user = User{} - DB.Where(map[string]interface{}{"name": user2.Name}).First(&user) - if user.Id == 0 || user.Name != user2.Name { - t.Errorf("Search first record with where map") - } - - var users []User - DB.Where(map[string]interface{}{"name": user3.Name}).Find(&users) - if len(users) != 1 { - t.Errorf("Search all records with inline map") - } - - DB.Find(&users, map[string]interface{}{"name": user3.Name}) - if len(users) != 1 { - t.Errorf("Search all records with inline map") - } - - DB.Find(&users, map[string]interface{}{"name": user4.Name, "company_id": nil}) - if len(users) != 0 { - t.Errorf("Search all records with inline map containing null value finding 0 records") - } - - DB.Find(&users, map[string]interface{}{"name": user1.Name, "company_id": nil}) - if len(users) != 1 { - t.Errorf("Search all records with inline map containing null value finding 1 record") - } - - DB.Find(&users, map[string]interface{}{"name": user4.Name, "company_id": companyID}) - if len(users) != 1 { - t.Errorf("Search all records with inline multiple value map") - } -} - -func TestSearchWithEmptyChain(t *testing.T) { - user1 := User{Name: "ChainSearchUser1", Age: 1, Birthday: parseTime("2000-1-1")} - user2 := User{Name: "ChainearchUser2", Age: 10, Birthday: parseTime("2010-1-1")} - user3 := User{Name: "ChainearchUser3", Age: 20, Birthday: parseTime("2020-1-1")} - DB.Save(&user1).Save(&user2).Save(&user3) - - if DB.Where("").Where("").First(&User{}).Error != nil { - t.Errorf("Should not raise any error if searching with empty strings") - } - - if DB.Where(&User{}).Where("name = ?", user1.Name).First(&User{}).Error != nil { - t.Errorf("Should not raise any error if searching with empty struct") - } - - if DB.Where(map[string]interface{}{}).Where("name = ?", user1.Name).First(&User{}).Error != nil { - t.Errorf("Should not raise any error if searching with empty map") - } -} - -func TestSelect(t *testing.T) { - user1 := User{Name: "SelectUser1"} - DB.Save(&user1) - - var user User - DB.Where("name = ?", user1.Name).Select("name").Find(&user) - if user.Id != 0 { - t.Errorf("Should not have ID because only selected name, %+v", user.Id) - } - - if user.Name != user1.Name { - t.Errorf("Should have user Name when selected it") - } -} - -func TestOrderAndPluck(t *testing.T) { - user1 := User{Name: "OrderPluckUser1", Age: 1} - user2 := User{Name: "OrderPluckUser2", Age: 10} - user3 := User{Name: "OrderPluckUser3", Age: 20} - DB.Save(&user1).Save(&user2).Save(&user3) - scopedb := DB.Model(&User{}).Where("name like ?", "%OrderPluckUser%") - - var user User - scopedb.Order(gorm.Expr("name = ? DESC", "OrderPluckUser2")).First(&user) - if user.Name != "OrderPluckUser2" { - t.Errorf("Order with sql expression") - } - - var ages []int64 - scopedb.Order("age desc").Pluck("age", &ages) - if ages[0] != 20 { - t.Errorf("The first age should be 20 when order with age desc") - } - - var ages1, ages2 []int64 - scopedb.Order("age desc").Pluck("age", &ages1).Pluck("age", &ages2) - if !reflect.DeepEqual(ages1, ages2) { - t.Errorf("The first order is the primary order") - } - - var ages3, ages4 []int64 - scopedb.Model(&User{}).Order("age desc").Pluck("age", &ages3).Order("age", true).Pluck("age", &ages4) - if reflect.DeepEqual(ages3, ages4) { - t.Errorf("Reorder should work") - } - - var names []string - var ages5 []int64 - scopedb.Model(User{}).Order("name").Order("age desc").Pluck("age", &ages5).Pluck("name", &names) - if names != nil && ages5 != nil { - if !(names[0] == user1.Name && names[1] == user2.Name && names[2] == user3.Name && ages5[2] == 20) { - t.Errorf("Order with multiple orders") - } - } else { - t.Errorf("Order with multiple orders") - } - - DB.Model(User{}).Select("name, age").Find(&[]User{}) -} - -func TestLimit(t *testing.T) { - user1 := User{Name: "LimitUser1", Age: 1} - user2 := User{Name: "LimitUser2", Age: 10} - user3 := User{Name: "LimitUser3", Age: 20} - user4 := User{Name: "LimitUser4", Age: 10} - user5 := User{Name: "LimitUser5", Age: 20} - DB.Save(&user1).Save(&user2).Save(&user3).Save(&user4).Save(&user5) - - var users1, users2, users3 []User - DB.Order("age desc").Limit(3).Find(&users1).Limit(5).Find(&users2).Limit(-1).Find(&users3) - - if len(users1) != 3 || len(users2) != 5 || len(users3) <= 5 { - t.Errorf("Limit should works") - } -} - -func TestOffset(t *testing.T) { - for i := 0; i < 20; i++ { - DB.Save(&User{Name: fmt.Sprintf("OffsetUser%v", i)}) - } - var users1, users2, users3, users4 []User - DB.Limit(100).Order("age desc").Find(&users1).Offset(3).Find(&users2).Offset(5).Find(&users3).Offset(-1).Find(&users4) - - if (len(users1) != len(users4)) || (len(users1)-len(users2) != 3) || (len(users1)-len(users3) != 5) { - t.Errorf("Offset should work") - } -} - -func TestOr(t *testing.T) { - user1 := User{Name: "OrUser1", Age: 1} - user2 := User{Name: "OrUser2", Age: 10} - user3 := User{Name: "OrUser3", Age: 20} - DB.Save(&user1).Save(&user2).Save(&user3) - - var users []User - DB.Where("name = ?", user1.Name).Or("name = ?", user2.Name).Find(&users) - if len(users) != 2 { - t.Errorf("Find users with or") - } -} - -func TestCount(t *testing.T) { - user1 := User{Name: "CountUser1", Age: 1} - user2 := User{Name: "CountUser2", Age: 10} - user3 := User{Name: "CountUser3", Age: 20} - - DB.Save(&user1).Save(&user2).Save(&user3) - var count, count1, count2 int64 - var users []User - - if err := DB.Where("name = ?", user1.Name).Or("name = ?", user3.Name).Find(&users).Count(&count).Error; err != nil { - t.Errorf(fmt.Sprintf("Count should work, but got err %v", err)) - } - - if count != int64(len(users)) { - t.Errorf("Count() method should get correct value") - } - - DB.Model(&User{}).Where("name = ?", user1.Name).Count(&count1).Or("name in (?)", []string{user2.Name, user3.Name}).Count(&count2) - if count1 != 1 || count2 != 3 { - t.Errorf("Multiple count in chain") - } -} - -func TestNot(t *testing.T) { - DB.Create(getPreparedUser("user1", "not")) - DB.Create(getPreparedUser("user2", "not")) - DB.Create(getPreparedUser("user3", "not")) - - user4 := getPreparedUser("user4", "not") - user4.Company = Company{} - DB.Create(user4) - - DB := DB.Where("role = ?", "not") - - var users1, users2, users3, users4, users5, users6, users7, users8, users9 []User - if DB.Find(&users1).RowsAffected != 4 { - t.Errorf("should find 4 not users") - } - DB.Not(users1[0].Id).Find(&users2) - - if len(users1)-len(users2) != 1 { - t.Errorf("Should ignore the first users with Not") - } - - DB.Not([]int{}).Find(&users3) - if len(users1)-len(users3) != 0 { - t.Errorf("Should find all users with a blank condition") - } - - var name3Count int64 - DB.Table("users").Where("name = ?", "user3").Count(&name3Count) - DB.Not("name", "user3").Find(&users4) - if len(users1)-len(users4) != int(name3Count) { - t.Errorf("Should find all users's name not equal 3") - } - - DB.Not("name = ?", "user3").Find(&users4) - if len(users1)-len(users4) != int(name3Count) { - t.Errorf("Should find all users's name not equal 3") - } - - DB.Not("name <> ?", "user3").Find(&users4) - if len(users4) != int(name3Count) { - t.Errorf("Should find all users's name not equal 3") - } - - DB.Not(User{Name: "user3"}).Find(&users5) - - if len(users1)-len(users5) != int(name3Count) { - t.Errorf("Should find all users's name not equal 3") - } - - DB.Not(map[string]interface{}{"name": "user3"}).Find(&users6) - if len(users1)-len(users6) != int(name3Count) { - t.Errorf("Should find all users's name not equal 3") - } - - DB.Not(map[string]interface{}{"name": "user3", "company_id": nil}).Find(&users7) - if len(users1)-len(users7) != 2 { // not user3 or user4 - t.Errorf("Should find all user's name not equal to 3 who do not have company id") - } - - DB.Not("name", []string{"user3"}).Find(&users8) - if len(users1)-len(users8) != int(name3Count) { - t.Errorf("Should find all users's name not equal 3") - } - - var name2Count int64 - DB.Table("users").Where("name = ?", "user2").Count(&name2Count) - DB.Not("name", []string{"user3", "user2"}).Find(&users9) - if len(users1)-len(users9) != (int(name3Count) + int(name2Count)) { - t.Errorf("Should find all users's name not equal 3") - } -} - -func TestFillSmallerStruct(t *testing.T) { - user1 := User{Name: "SmallerUser", Age: 100} - DB.Save(&user1) - type SimpleUser struct { - Name string - Id int64 - UpdatedAt time.Time - CreatedAt time.Time - } - - var simpleUser SimpleUser - DB.Table("users").Where("name = ?", user1.Name).First(&simpleUser) - - if simpleUser.Id == 0 || simpleUser.Name == "" { - t.Errorf("Should fill data correctly into smaller struct") - } -} - -func TestFindOrInitialize(t *testing.T) { - var user1, user2, user3, user4, user5, user6 User - DB.Where(&User{Name: "find or init", Age: 33}).FirstOrInit(&user1) - if user1.Name != "find or init" || user1.Id != 0 || user1.Age != 33 { - t.Errorf("user should be initialized with search value") - } - - DB.Where(User{Name: "find or init", Age: 33}).FirstOrInit(&user2) - if user2.Name != "find or init" || user2.Id != 0 || user2.Age != 33 { - t.Errorf("user should be initialized with search value") - } - - DB.FirstOrInit(&user3, map[string]interface{}{"name": "find or init 2"}) - if user3.Name != "find or init 2" || user3.Id != 0 { - t.Errorf("user should be initialized with inline search value") - } - - DB.Where(&User{Name: "find or init"}).Attrs(User{Age: 44}).FirstOrInit(&user4) - if user4.Name != "find or init" || user4.Id != 0 || user4.Age != 44 { - t.Errorf("user should be initialized with search value and attrs") - } - - DB.Where(&User{Name: "find or init"}).Assign("age", 44).FirstOrInit(&user4) - if user4.Name != "find or init" || user4.Id != 0 || user4.Age != 44 { - t.Errorf("user should be initialized with search value and assign attrs") - } - - DB.Save(&User{Name: "find or init", Age: 33}) - DB.Where(&User{Name: "find or init"}).Attrs("age", 44).FirstOrInit(&user5) - if user5.Name != "find or init" || user5.Id == 0 || user5.Age != 33 { - t.Errorf("user should be found and not initialized by Attrs") - } - - DB.Where(&User{Name: "find or init", Age: 33}).FirstOrInit(&user6) - if user6.Name != "find or init" || user6.Id == 0 || user6.Age != 33 { - t.Errorf("user should be found with FirstOrInit") - } - - DB.Where(&User{Name: "find or init"}).Assign(User{Age: 44}).FirstOrInit(&user6) - if user6.Name != "find or init" || user6.Id == 0 || user6.Age != 44 { - t.Errorf("user should be found and updated with assigned attrs") - } -} - -func TestFindOrCreate(t *testing.T) { - var user1, user2, user3, user4, user5, user6, user7, user8 User - DB.Where(&User{Name: "find or create", Age: 33}).FirstOrCreate(&user1) - if user1.Name != "find or create" || user1.Id == 0 || user1.Age != 33 { - t.Errorf("user should be created with search value") - } - - DB.Where(&User{Name: "find or create", Age: 33}).FirstOrCreate(&user2) - if user1.Id != user2.Id || user2.Name != "find or create" || user2.Id == 0 || user2.Age != 33 { - t.Errorf("user should be created with search value") - } - - DB.FirstOrCreate(&user3, map[string]interface{}{"name": "find or create 2"}) - if user3.Name != "find or create 2" || user3.Id == 0 { - t.Errorf("user should be created with inline search value") - } - - DB.Where(&User{Name: "find or create 3"}).Attrs("age", 44).FirstOrCreate(&user4) - if user4.Name != "find or create 3" || user4.Id == 0 || user4.Age != 44 { - t.Errorf("user should be created with search value and attrs") - } - - updatedAt1 := user4.UpdatedAt - DB.Where(&User{Name: "find or create 3"}).Assign("age", 55).FirstOrCreate(&user4) - if updatedAt1.Format(time.RFC3339Nano) == user4.UpdatedAt.Format(time.RFC3339Nano) { - t.Errorf("UpdateAt should be changed when update values with assign") - } - - DB.Where(&User{Name: "find or create 4"}).Assign(User{Age: 44}).FirstOrCreate(&user4) - if user4.Name != "find or create 4" || user4.Id == 0 || user4.Age != 44 { - t.Errorf("user should be created with search value and assigned attrs") - } - - DB.Where(&User{Name: "find or create"}).Attrs("age", 44).FirstOrInit(&user5) - if user5.Name != "find or create" || user5.Id == 0 || user5.Age != 33 { - t.Errorf("user should be found and not initialized by Attrs") - } - - DB.Where(&User{Name: "find or create"}).Assign(User{Age: 44}).FirstOrCreate(&user6) - if user6.Name != "find or create" || user6.Id == 0 || user6.Age != 44 { - t.Errorf("user should be found and updated with assigned attrs") - } - - DB.Where(&User{Name: "find or create"}).Find(&user7) - if user7.Name != "find or create" || user7.Id == 0 || user7.Age != 44 { - t.Errorf("user should be found and updated with assigned attrs") - } - - DB.Where(&User{Name: "find or create embedded struct"}).Assign(User{Age: 44, CreditCard: CreditCard{Number: "1231231231"}, Emails: []Email{{Email: "jinzhu@assign_embedded_struct.com"}, {Email: "jinzhu-2@assign_embedded_struct.com"}}}).FirstOrCreate(&user8) - if DB.Where("email = ?", "jinzhu-2@assign_embedded_struct.com").First(&Email{}).RecordNotFound() { - t.Errorf("embedded struct email should be saved") - } - - if DB.Where("email = ?", "1231231231").First(&CreditCard{}).RecordNotFound() { - t.Errorf("embedded struct credit card should be saved") - } -} - -func TestSelectWithEscapedFieldName(t *testing.T) { - user1 := User{Name: "EscapedFieldNameUser", Age: 1} - user2 := User{Name: "EscapedFieldNameUser", Age: 10} - user3 := User{Name: "EscapedFieldNameUser", Age: 20} - DB.Save(&user1).Save(&user2).Save(&user3) - - var names []string - DB.Model(User{}).Where(&User{Name: "EscapedFieldNameUser"}).Pluck("\"name\"", &names) - - if len(names) != 3 { - t.Errorf("Expected 3 name, but got: %d", len(names)) - } -} - -func TestSelectWithVariables(t *testing.T) { - DB.Save(&User{Name: "jinzhu"}) - - rows, _ := DB.Table("users").Select("? as fake", gorm.Expr("name")).Rows() - - if !rows.Next() { - t.Errorf("Should have returned at least one row") - } else { - columns, _ := rows.Columns() - if !reflect.DeepEqual(columns, []string{"fake"}) { - t.Errorf("Should only contains one column") - } - } - - rows.Close() -} - -func TestSelectWithArrayInput(t *testing.T) { - DB.Save(&User{Name: "jinzhu", Age: 42}) - - var user User - DB.Select([]string{"name", "age"}).Where("age = 42 AND name = 'jinzhu'").First(&user) - - if user.Name != "jinzhu" || user.Age != 42 { - t.Errorf("Should have selected both age and name") - } -} diff --git a/vendor/github.com/jinzhu/gorm/scaner_test.go b/vendor/github.com/jinzhu/gorm/scaner_test.go deleted file mode 100644 index fae9d3e168c4..000000000000 --- a/vendor/github.com/jinzhu/gorm/scaner_test.go +++ /dev/null @@ -1,137 +0,0 @@ -package gorm_test - -import ( - "database/sql/driver" - "encoding/json" - "errors" - "testing" - - "github.com/jinzhu/gorm" -) - -func TestScannableSlices(t *testing.T) { - if err := DB.AutoMigrate(&RecordWithSlice{}).Error; err != nil { - t.Errorf("Should create table with slice values correctly: %s", err) - } - - r1 := RecordWithSlice{ - Strings: ExampleStringSlice{"a", "b", "c"}, - Structs: ExampleStructSlice{ - {"name1", "value1"}, - {"name2", "value2"}, - }, - } - - if err := DB.Save(&r1).Error; err != nil { - t.Errorf("Should save record with slice values") - } - - var r2 RecordWithSlice - - if err := DB.Find(&r2).Error; err != nil { - t.Errorf("Should fetch record with slice values") - } - - if len(r2.Strings) != 3 || r2.Strings[0] != "a" || r2.Strings[1] != "b" || r2.Strings[2] != "c" { - t.Errorf("Should have serialised and deserialised a string array") - } - - if len(r2.Structs) != 2 || r2.Structs[0].Name != "name1" || r2.Structs[0].Value != "value1" || r2.Structs[1].Name != "name2" || r2.Structs[1].Value != "value2" { - t.Errorf("Should have serialised and deserialised a struct array") - } -} - -type RecordWithSlice struct { - ID uint64 - Strings ExampleStringSlice `sql:"type:text"` - Structs ExampleStructSlice `sql:"type:text"` -} - -type ExampleStringSlice []string - -func (l ExampleStringSlice) Value() (driver.Value, error) { - return json.Marshal(l) -} - -func (l *ExampleStringSlice) Scan(input interface{}) error { - switch value := input.(type) { - case string: - return json.Unmarshal([]byte(value), l) - case []byte: - return json.Unmarshal(value, l) - default: - return errors.New("not supported") - } -} - -type ExampleStruct struct { - Name string - Value string -} - -type ExampleStructSlice []ExampleStruct - -func (l ExampleStructSlice) Value() (driver.Value, error) { - return json.Marshal(l) -} - -func (l *ExampleStructSlice) Scan(input interface{}) error { - switch value := input.(type) { - case string: - return json.Unmarshal([]byte(value), l) - case []byte: - return json.Unmarshal(value, l) - default: - return errors.New("not supported") - } -} - -type ScannerDataType struct { - Street string `sql:"TYPE:varchar(24)"` -} - -func (ScannerDataType) Value() (driver.Value, error) { - return nil, nil -} - -func (*ScannerDataType) Scan(input interface{}) error { - return nil -} - -type ScannerDataTypeTestStruct struct { - Field1 int - ScannerDataType *ScannerDataType `sql:"TYPE:json"` -} - -type ScannerDataType2 struct { - Street string `sql:"TYPE:varchar(24)"` -} - -func (ScannerDataType2) Value() (driver.Value, error) { - return nil, nil -} - -func (*ScannerDataType2) Scan(input interface{}) error { - return nil -} - -type ScannerDataTypeTestStruct2 struct { - Field1 int - ScannerDataType *ScannerDataType2 -} - -func TestScannerDataType(t *testing.T) { - scope := gorm.Scope{Value: &ScannerDataTypeTestStruct{}} - if field, ok := scope.FieldByName("ScannerDataType"); ok { - if DB.Dialect().DataTypeOf(field.StructField) != "json" { - t.Errorf("data type for scanner is wrong") - } - } - - scope = gorm.Scope{Value: &ScannerDataTypeTestStruct2{}} - if field, ok := scope.FieldByName("ScannerDataType"); ok { - if DB.Dialect().DataTypeOf(field.StructField) != "varchar(24)" { - t.Errorf("data type for scanner is wrong") - } - } -} diff --git a/vendor/github.com/jinzhu/gorm/scope_test.go b/vendor/github.com/jinzhu/gorm/scope_test.go deleted file mode 100644 index 42458995d31a..000000000000 --- a/vendor/github.com/jinzhu/gorm/scope_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package gorm_test - -import ( - "github.com/jinzhu/gorm" - "testing" -) - -func NameIn1And2(d *gorm.DB) *gorm.DB { - return d.Where("name in (?)", []string{"ScopeUser1", "ScopeUser2"}) -} - -func NameIn2And3(d *gorm.DB) *gorm.DB { - return d.Where("name in (?)", []string{"ScopeUser2", "ScopeUser3"}) -} - -func NameIn(names []string) func(d *gorm.DB) *gorm.DB { - return func(d *gorm.DB) *gorm.DB { - return d.Where("name in (?)", names) - } -} - -func TestScopes(t *testing.T) { - user1 := User{Name: "ScopeUser1", Age: 1} - user2 := User{Name: "ScopeUser2", Age: 1} - user3 := User{Name: "ScopeUser3", Age: 2} - DB.Save(&user1).Save(&user2).Save(&user3) - - var users1, users2, users3 []User - DB.Scopes(NameIn1And2).Find(&users1) - if len(users1) != 2 { - t.Errorf("Should found two users's name in 1, 2") - } - - DB.Scopes(NameIn1And2, NameIn2And3).Find(&users2) - if len(users2) != 1 { - t.Errorf("Should found one user's name is 2") - } - - DB.Scopes(NameIn([]string{user1.Name, user3.Name})).Find(&users3) - if len(users3) != 2 { - t.Errorf("Should found two users's name in 1, 3") - } -} diff --git a/vendor/github.com/jinzhu/gorm/search_test.go b/vendor/github.com/jinzhu/gorm/search_test.go deleted file mode 100644 index 4db7ab6a5204..000000000000 --- a/vendor/github.com/jinzhu/gorm/search_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package gorm - -import ( - "reflect" - "testing" -) - -func TestCloneSearch(t *testing.T) { - s := new(search) - s.Where("name = ?", "jinzhu").Order("name").Attrs("name", "jinzhu").Select("name, age") - - s1 := s.clone() - s1.Where("age = ?", 20).Order("age").Attrs("email", "a@e.org").Select("email") - - if reflect.DeepEqual(s.whereConditions, s1.whereConditions) { - t.Errorf("Where should be copied") - } - - if reflect.DeepEqual(s.orders, s1.orders) { - t.Errorf("Order should be copied") - } - - if reflect.DeepEqual(s.initAttrs, s1.initAttrs) { - t.Errorf("InitAttrs should be copied") - } - - if reflect.DeepEqual(s.Select, s1.Select) { - t.Errorf("selectStr should be copied") - } -} diff --git a/vendor/github.com/jinzhu/gorm/update_test.go b/vendor/github.com/jinzhu/gorm/update_test.go deleted file mode 100644 index 85d53e5f06dc..000000000000 --- a/vendor/github.com/jinzhu/gorm/update_test.go +++ /dev/null @@ -1,465 +0,0 @@ -package gorm_test - -import ( - "testing" - "time" - - "github.com/jinzhu/gorm" -) - -func TestUpdate(t *testing.T) { - product1 := Product{Code: "product1code"} - product2 := Product{Code: "product2code"} - - DB.Save(&product1).Save(&product2).Update("code", "product2newcode") - - if product2.Code != "product2newcode" { - t.Errorf("Record should be updated") - } - - DB.First(&product1, product1.Id) - DB.First(&product2, product2.Id) - updatedAt1 := product1.UpdatedAt - - if DB.First(&Product{}, "code = ?", product1.Code).RecordNotFound() { - t.Errorf("Product1 should not be updated") - } - - if !DB.First(&Product{}, "code = ?", "product2code").RecordNotFound() { - t.Errorf("Product2's code should be updated") - } - - if DB.First(&Product{}, "code = ?", "product2newcode").RecordNotFound() { - t.Errorf("Product2's code should be updated") - } - - DB.Table("products").Where("code in (?)", []string{"product1code"}).Update("code", "product1newcode") - - var product4 Product - DB.First(&product4, product1.Id) - if updatedAt1.Format(time.RFC3339Nano) != product4.UpdatedAt.Format(time.RFC3339Nano) { - t.Errorf("updatedAt should be updated if something changed") - } - - if !DB.First(&Product{}, "code = 'product1code'").RecordNotFound() { - t.Errorf("Product1's code should be updated") - } - - if DB.First(&Product{}, "code = 'product1newcode'").RecordNotFound() { - t.Errorf("Product should not be changed to 789") - } - - if DB.Model(product2).Update("CreatedAt", time.Now().Add(time.Hour)).Error != nil { - t.Error("No error should raise when update with CamelCase") - } - - if DB.Model(&product2).UpdateColumn("CreatedAt", time.Now().Add(time.Hour)).Error != nil { - t.Error("No error should raise when update_column with CamelCase") - } - - var products []Product - DB.Find(&products) - if count := DB.Model(Product{}).Update("CreatedAt", time.Now().Add(2*time.Hour)).RowsAffected; count != int64(len(products)) { - t.Error("RowsAffected should be correct when do batch update") - } - - DB.First(&product4, product4.Id) - updatedAt4 := product4.UpdatedAt - DB.Model(&product4).Update("price", gorm.Expr("price + ? - ?", 100, 50)) - var product5 Product - DB.First(&product5, product4.Id) - if product5.Price != product4.Price+100-50 { - t.Errorf("Update with expression") - } - if product4.UpdatedAt.Format(time.RFC3339Nano) == updatedAt4.Format(time.RFC3339Nano) { - t.Errorf("Update with expression should update UpdatedAt") - } -} - -func TestUpdateWithNoStdPrimaryKeyAndDefaultValues(t *testing.T) { - animal := Animal{Name: "Ferdinand"} - DB.Save(&animal) - updatedAt1 := animal.UpdatedAt - - DB.Save(&animal).Update("name", "Francis") - - if updatedAt1.Format(time.RFC3339Nano) == animal.UpdatedAt.Format(time.RFC3339Nano) { - t.Errorf("updatedAt should not be updated if nothing changed") - } - - var animals []Animal - DB.Find(&animals) - if count := DB.Model(Animal{}).Update("CreatedAt", time.Now().Add(2*time.Hour)).RowsAffected; count != int64(len(animals)) { - t.Error("RowsAffected should be correct when do batch update") - } - - animal = Animal{From: "somewhere"} // No name fields, should be filled with the default value (galeone) - DB.Save(&animal).Update("From", "a nice place") // The name field shoul be untouched - DB.First(&animal, animal.Counter) - if animal.Name != "galeone" { - t.Errorf("Name fields shouldn't be changed if untouched, but got %v", animal.Name) - } - - // When changing a field with a default value, the change must occur - animal.Name = "amazing horse" - DB.Save(&animal) - DB.First(&animal, animal.Counter) - if animal.Name != "amazing horse" { - t.Errorf("Update a filed with a default value should occur. But got %v\n", animal.Name) - } - - // When changing a field with a default value with blank value - animal.Name = "" - DB.Save(&animal) - DB.First(&animal, animal.Counter) - if animal.Name != "" { - t.Errorf("Update a filed to blank with a default value should occur. But got %v\n", animal.Name) - } -} - -func TestUpdates(t *testing.T) { - product1 := Product{Code: "product1code", Price: 10} - product2 := Product{Code: "product2code", Price: 10} - DB.Save(&product1).Save(&product2) - DB.Model(&product1).Updates(map[string]interface{}{"code": "product1newcode", "price": 100}) - if product1.Code != "product1newcode" || product1.Price != 100 { - t.Errorf("Record should be updated also with map") - } - - DB.First(&product1, product1.Id) - DB.First(&product2, product2.Id) - updatedAt2 := product2.UpdatedAt - - if DB.First(&Product{}, "code = ? and price = ?", product2.Code, product2.Price).RecordNotFound() { - t.Errorf("Product2 should not be updated") - } - - if DB.First(&Product{}, "code = ?", "product1newcode").RecordNotFound() { - t.Errorf("Product1 should be updated") - } - - DB.Table("products").Where("code in (?)", []string{"product2code"}).Updates(Product{Code: "product2newcode"}) - if !DB.First(&Product{}, "code = 'product2code'").RecordNotFound() { - t.Errorf("Product2's code should be updated") - } - - var product4 Product - DB.First(&product4, product2.Id) - if updatedAt2.Format(time.RFC3339Nano) != product4.UpdatedAt.Format(time.RFC3339Nano) { - t.Errorf("updatedAt should be updated if something changed") - } - - if DB.First(&Product{}, "code = ?", "product2newcode").RecordNotFound() { - t.Errorf("product2's code should be updated") - } - - updatedAt4 := product4.UpdatedAt - DB.Model(&product4).Updates(map[string]interface{}{"price": gorm.Expr("price + ?", 100)}) - var product5 Product - DB.First(&product5, product4.Id) - if product5.Price != product4.Price+100 { - t.Errorf("Updates with expression") - } - // product4's UpdatedAt will be reset when updating - if product4.UpdatedAt.Format(time.RFC3339Nano) == updatedAt4.Format(time.RFC3339Nano) { - t.Errorf("Updates with expression should update UpdatedAt") - } -} - -func TestUpdateColumn(t *testing.T) { - product1 := Product{Code: "product1code", Price: 10} - product2 := Product{Code: "product2code", Price: 20} - DB.Save(&product1).Save(&product2).UpdateColumn(map[string]interface{}{"code": "product2newcode", "price": 100}) - if product2.Code != "product2newcode" || product2.Price != 100 { - t.Errorf("product 2 should be updated with update column") - } - - var product3 Product - DB.First(&product3, product1.Id) - if product3.Code != "product1code" || product3.Price != 10 { - t.Errorf("product 1 should not be updated") - } - - DB.First(&product2, product2.Id) - updatedAt2 := product2.UpdatedAt - DB.Model(product2).UpdateColumn("code", "update_column_new") - var product4 Product - DB.First(&product4, product2.Id) - if updatedAt2.Format(time.RFC3339Nano) != product4.UpdatedAt.Format(time.RFC3339Nano) { - t.Errorf("updatedAt should not be updated with update column") - } - - DB.Model(&product4).UpdateColumn("price", gorm.Expr("price + 100 - 50")) - var product5 Product - DB.First(&product5, product4.Id) - if product5.Price != product4.Price+100-50 { - t.Errorf("UpdateColumn with expression") - } - if product5.UpdatedAt.Format(time.RFC3339Nano) != product4.UpdatedAt.Format(time.RFC3339Nano) { - t.Errorf("UpdateColumn with expression should not update UpdatedAt") - } -} - -func TestSelectWithUpdate(t *testing.T) { - user := getPreparedUser("select_user", "select_with_update") - DB.Create(user) - - var reloadUser User - DB.First(&reloadUser, user.Id) - reloadUser.Name = "new_name" - reloadUser.Age = 50 - reloadUser.BillingAddress = Address{Address1: "New Billing Address"} - reloadUser.ShippingAddress = Address{Address1: "New ShippingAddress Address"} - reloadUser.CreditCard = CreditCard{Number: "987654321"} - reloadUser.Emails = []Email{ - {Email: "new_user_1@example1.com"}, {Email: "new_user_2@example2.com"}, {Email: "new_user_3@example2.com"}, - } - reloadUser.Company = Company{Name: "new company"} - - DB.Select("Name", "BillingAddress", "CreditCard", "Company", "Emails").Save(&reloadUser) - - var queryUser User - DB.Preload("BillingAddress").Preload("ShippingAddress"). - Preload("CreditCard").Preload("Emails").Preload("Company").First(&queryUser, user.Id) - - if queryUser.Name == user.Name || queryUser.Age != user.Age { - t.Errorf("Should only update users with name column") - } - - if queryUser.BillingAddressID.Int64 == user.BillingAddressID.Int64 || - queryUser.ShippingAddressId != user.ShippingAddressId || - queryUser.CreditCard.ID == user.CreditCard.ID || - len(queryUser.Emails) == len(user.Emails) || queryUser.Company.Id == user.Company.Id { - t.Errorf("Should only update selected relationships") - } -} - -func TestSelectWithUpdateWithMap(t *testing.T) { - user := getPreparedUser("select_user", "select_with_update_map") - DB.Create(user) - - updateValues := map[string]interface{}{ - "Name": "new_name", - "Age": 50, - "BillingAddress": Address{Address1: "New Billing Address"}, - "ShippingAddress": Address{Address1: "New ShippingAddress Address"}, - "CreditCard": CreditCard{Number: "987654321"}, - "Emails": []Email{ - {Email: "new_user_1@example1.com"}, {Email: "new_user_2@example2.com"}, {Email: "new_user_3@example2.com"}, - }, - "Company": Company{Name: "new company"}, - } - - var reloadUser User - DB.First(&reloadUser, user.Id) - DB.Model(&reloadUser).Select("Name", "BillingAddress", "CreditCard", "Company", "Emails").Update(updateValues) - - var queryUser User - DB.Preload("BillingAddress").Preload("ShippingAddress"). - Preload("CreditCard").Preload("Emails").Preload("Company").First(&queryUser, user.Id) - - if queryUser.Name == user.Name || queryUser.Age != user.Age { - t.Errorf("Should only update users with name column") - } - - if queryUser.BillingAddressID.Int64 == user.BillingAddressID.Int64 || - queryUser.ShippingAddressId != user.ShippingAddressId || - queryUser.CreditCard.ID == user.CreditCard.ID || - len(queryUser.Emails) == len(user.Emails) || queryUser.Company.Id == user.Company.Id { - t.Errorf("Should only update selected relationships") - } -} - -func TestOmitWithUpdate(t *testing.T) { - user := getPreparedUser("omit_user", "omit_with_update") - DB.Create(user) - - var reloadUser User - DB.First(&reloadUser, user.Id) - reloadUser.Name = "new_name" - reloadUser.Age = 50 - reloadUser.BillingAddress = Address{Address1: "New Billing Address"} - reloadUser.ShippingAddress = Address{Address1: "New ShippingAddress Address"} - reloadUser.CreditCard = CreditCard{Number: "987654321"} - reloadUser.Emails = []Email{ - {Email: "new_user_1@example1.com"}, {Email: "new_user_2@example2.com"}, {Email: "new_user_3@example2.com"}, - } - reloadUser.Company = Company{Name: "new company"} - - DB.Omit("Name", "BillingAddress", "CreditCard", "Company", "Emails").Save(&reloadUser) - - var queryUser User - DB.Preload("BillingAddress").Preload("ShippingAddress"). - Preload("CreditCard").Preload("Emails").Preload("Company").First(&queryUser, user.Id) - - if queryUser.Name != user.Name || queryUser.Age == user.Age { - t.Errorf("Should only update users with name column") - } - - if queryUser.BillingAddressID.Int64 != user.BillingAddressID.Int64 || - queryUser.ShippingAddressId == user.ShippingAddressId || - queryUser.CreditCard.ID != user.CreditCard.ID || - len(queryUser.Emails) != len(user.Emails) || queryUser.Company.Id != user.Company.Id { - t.Errorf("Should only update relationships that not omitted") - } -} - -func TestOmitWithUpdateWithMap(t *testing.T) { - user := getPreparedUser("select_user", "select_with_update_map") - DB.Create(user) - - updateValues := map[string]interface{}{ - "Name": "new_name", - "Age": 50, - "BillingAddress": Address{Address1: "New Billing Address"}, - "ShippingAddress": Address{Address1: "New ShippingAddress Address"}, - "CreditCard": CreditCard{Number: "987654321"}, - "Emails": []Email{ - {Email: "new_user_1@example1.com"}, {Email: "new_user_2@example2.com"}, {Email: "new_user_3@example2.com"}, - }, - "Company": Company{Name: "new company"}, - } - - var reloadUser User - DB.First(&reloadUser, user.Id) - DB.Model(&reloadUser).Omit("Name", "BillingAddress", "CreditCard", "Company", "Emails").Update(updateValues) - - var queryUser User - DB.Preload("BillingAddress").Preload("ShippingAddress"). - Preload("CreditCard").Preload("Emails").Preload("Company").First(&queryUser, user.Id) - - if queryUser.Name != user.Name || queryUser.Age == user.Age { - t.Errorf("Should only update users with name column") - } - - if queryUser.BillingAddressID.Int64 != user.BillingAddressID.Int64 || - queryUser.ShippingAddressId == user.ShippingAddressId || - queryUser.CreditCard.ID != user.CreditCard.ID || - len(queryUser.Emails) != len(user.Emails) || queryUser.Company.Id != user.Company.Id { - t.Errorf("Should only update relationships not omitted") - } -} - -func TestSelectWithUpdateColumn(t *testing.T) { - user := getPreparedUser("select_user", "select_with_update_map") - DB.Create(user) - - updateValues := map[string]interface{}{"Name": "new_name", "Age": 50} - - var reloadUser User - DB.First(&reloadUser, user.Id) - DB.Model(&reloadUser).Select("Name").UpdateColumn(updateValues) - - var queryUser User - DB.First(&queryUser, user.Id) - - if queryUser.Name == user.Name || queryUser.Age != user.Age { - t.Errorf("Should only update users with name column") - } -} - -func TestOmitWithUpdateColumn(t *testing.T) { - user := getPreparedUser("select_user", "select_with_update_map") - DB.Create(user) - - updateValues := map[string]interface{}{"Name": "new_name", "Age": 50} - - var reloadUser User - DB.First(&reloadUser, user.Id) - DB.Model(&reloadUser).Omit("Name").UpdateColumn(updateValues) - - var queryUser User - DB.First(&queryUser, user.Id) - - if queryUser.Name != user.Name || queryUser.Age == user.Age { - t.Errorf("Should omit name column when update user") - } -} - -func TestUpdateColumnsSkipsAssociations(t *testing.T) { - user := getPreparedUser("update_columns_user", "special_role") - user.Age = 99 - address1 := "first street" - user.BillingAddress = Address{Address1: address1} - DB.Save(user) - - // Update a single field of the user and verify that the changed address is not stored. - newAge := int64(100) - user.BillingAddress.Address1 = "second street" - db := DB.Model(user).UpdateColumns(User{Age: newAge}) - if db.RowsAffected != 1 { - t.Errorf("Expected RowsAffected=1 but instead RowsAffected=%v", DB.RowsAffected) - } - - // Verify that Age now=`newAge`. - freshUser := &User{Id: user.Id} - DB.First(freshUser) - if freshUser.Age != newAge { - t.Errorf("Expected freshly queried user to have Age=%v but instead found Age=%v", newAge, freshUser.Age) - } - - // Verify that user's BillingAddress.Address1 is not changed and is still "first street". - DB.First(&freshUser.BillingAddress, freshUser.BillingAddressID) - if freshUser.BillingAddress.Address1 != address1 { - t.Errorf("Expected user's BillingAddress.Address1=%s to remain unchanged after UpdateColumns invocation, but BillingAddress.Address1=%s", address1, freshUser.BillingAddress.Address1) - } -} - -func TestUpdatesWithBlankValues(t *testing.T) { - product := Product{Code: "product1", Price: 10} - DB.Save(&product) - - DB.Model(&Product{Id: product.Id}).Updates(&Product{Price: 100}) - - var product1 Product - DB.First(&product1, product.Id) - - if product1.Code != "product1" || product1.Price != 100 { - t.Errorf("product's code should not be updated") - } -} - -type ElementWithIgnoredField struct { - Id int64 - Value string - IgnoredField int64 `sql:"-"` -} - -func (e ElementWithIgnoredField) TableName() string { - return "element_with_ignored_field" -} - -func TestUpdatesTableWithIgnoredValues(t *testing.T) { - elem := ElementWithIgnoredField{Value: "foo", IgnoredField: 10} - DB.Save(&elem) - - DB.Table(elem.TableName()). - Where("id = ?", elem.Id). - // DB.Model(&ElementWithIgnoredField{Id: elem.Id}). - Updates(&ElementWithIgnoredField{Value: "bar", IgnoredField: 100}) - - var elem1 ElementWithIgnoredField - err := DB.First(&elem1, elem.Id).Error - if err != nil { - t.Errorf("error getting an element from database: %s", err.Error()) - } - - if elem1.IgnoredField != 0 { - t.Errorf("element's ignored field should not be updated") - } -} - -func TestUpdateDecodeVirtualAttributes(t *testing.T) { - var user = User{ - Name: "jinzhu", - IgnoreMe: 88, - } - - DB.Save(&user) - - DB.Model(&user).Updates(User{Name: "jinzhu2", IgnoreMe: 100}) - - if user.IgnoreMe != 100 { - t.Errorf("should decode virtual attributes to struct, so it could be used in callbacks") - } -} diff --git a/vendor/github.com/jinzhu/gorm/utils_test.go b/vendor/github.com/jinzhu/gorm/utils_test.go deleted file mode 100644 index 07f5b17f403c..000000000000 --- a/vendor/github.com/jinzhu/gorm/utils_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package gorm_test - -import ( - "testing" - - "github.com/jinzhu/gorm" -) - -func TestToDBNameGenerateFriendlyName(t *testing.T) { - var maps = map[string]string{ - "": "", - "ThisIsATest": "this_is_a_test", - "PFAndESI": "pf_and_esi", - "AbcAndJkl": "abc_and_jkl", - "EmployeeID": "employee_id", - "SKU_ID": "sku_id", - "HTTPAndSMTP": "http_and_smtp", - "HTTPServerHandlerForURLID": "http_server_handler_for_url_id", - "UUID": "uuid", - "HTTPURL": "http_url", - "HTTP_URL": "http_url", - "ThisIsActuallyATestSoWeMayBeAbleToUseThisCodeInGormPackageAlsoIdCanBeUsedAtTheEndAsID": "this_is_actually_a_test_so_we_may_be_able_to_use_this_code_in_gorm_package_also_id_can_be_used_at_the_end_as_id", - } - - for key, value := range maps { - if gorm.ToDBName(key) != value { - t.Errorf("%v ToDBName should equal %v, but got %v", key, value, gorm.ToDBName(key)) - } - } -} diff --git a/vendor/github.com/jinzhu/inflection/BUILD b/vendor/github.com/jinzhu/inflection/BUILD index 2aa610ab25f7..0751e670e44c 100644 --- a/vendor/github.com/jinzhu/inflection/BUILD +++ b/vendor/github.com/jinzhu/inflection/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -7,13 +7,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_xtest", - srcs = ["inflections_test.go"], - importpath = "github.com/jinzhu/inflection_test", - deps = ["//vendor/github.com/qor/inflection:go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/jinzhu/inflection/inflections_test.go b/vendor/github.com/jinzhu/inflection/inflections_test.go deleted file mode 100644 index 448573d22e23..000000000000 --- a/vendor/github.com/jinzhu/inflection/inflections_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package inflection_test - -import ( - "strings" - "testing" - - "github.com/qor/inflection" -) - -var inflections = map[string]string{ - "star": "stars", - "STAR": "STARS", - "Star": "Stars", - "bus": "buses", - "fish": "fish", - "mouse": "mice", - "query": "queries", - "ability": "abilities", - "agency": "agencies", - "movie": "movies", - "archive": "archives", - "index": "indices", - "wife": "wives", - "safe": "saves", - "half": "halves", - "move": "moves", - "salesperson": "salespeople", - "person": "people", - "spokesman": "spokesmen", - "man": "men", - "woman": "women", - "basis": "bases", - "diagnosis": "diagnoses", - "diagnosis_a": "diagnosis_as", - "datum": "data", - "medium": "media", - "stadium": "stadia", - "analysis": "analyses", - "node_child": "node_children", - "child": "children", - "experience": "experiences", - "day": "days", - "comment": "comments", - "foobar": "foobars", - "newsletter": "newsletters", - "old_news": "old_news", - "news": "news", - "series": "series", - "species": "species", - "quiz": "quizzes", - "perspective": "perspectives", - "ox": "oxen", - "photo": "photos", - "buffalo": "buffaloes", - "tomato": "tomatoes", - "dwarf": "dwarves", - "elf": "elves", - "information": "information", - "equipment": "equipment", - "criterion": "criteria", -} - -func init() { - inflection.AddIrregular("criterion", "criteria") -} - -func TestPlural(t *testing.T) { - for key, value := range inflections { - if v := inflection.Plural(strings.ToUpper(key)); v != strings.ToUpper(value) { - t.Errorf("%v's plural should be %v, but got %v", strings.ToUpper(key), strings.ToUpper(value), v) - } - - if v := inflection.Plural(strings.Title(key)); v != strings.Title(value) { - t.Errorf("%v's plural should be %v, but got %v", strings.Title(key), strings.Title(value), v) - } - - if v := inflection.Plural(key); v != value { - t.Errorf("%v's plural should be %v, but got %v", key, value, v) - } - } -} - -func TestSingular(t *testing.T) { - for key, value := range inflections { - if v := inflection.Singular(strings.ToUpper(value)); v != strings.ToUpper(key) { - t.Errorf("%v's singular should be %v, but got %v", strings.ToUpper(value), strings.ToUpper(key), v) - } - - if v := inflection.Singular(strings.Title(value)); v != strings.Title(key) { - t.Errorf("%v's singular should be %v, but got %v", strings.Title(value), strings.Title(key), v) - } - - if v := inflection.Singular(value); v != key { - t.Errorf("%v's singular should be %v, but got %v", value, key, v) - } - } -} diff --git a/vendor/github.com/mattn/go-sqlite3/BUILD b/vendor/github.com/mattn/go-sqlite3/BUILD index 1f9dd9c110b5..60bbe6ccbd3b 100644 --- a/vendor/github.com/mattn/go-sqlite3/BUILD +++ b/vendor/github.com/mattn/go-sqlite3/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -44,19 +44,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = [ - "callback_test.go", - "error_test.go", - "sqlite3_fts3_test.go", - "sqlite3_test.go", - ], - importpath = "github.com/mattn/go-sqlite3", - library = ":go_default_library", - deps = ["//vendor/github.com/mattn/go-sqlite3/sqlite3_test:go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/mattn/go-sqlite3/callback_test.go b/vendor/github.com/mattn/go-sqlite3/callback_test.go deleted file mode 100644 index 5c61f4439f95..000000000000 --- a/vendor/github.com/mattn/go-sqlite3/callback_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package sqlite3 - -import ( - "errors" - "math" - "reflect" - "testing" -) - -func TestCallbackArgCast(t *testing.T) { - intConv := callbackSyntheticForTests(reflect.ValueOf(int64(math.MaxInt64)), nil) - floatConv := callbackSyntheticForTests(reflect.ValueOf(float64(math.MaxFloat64)), nil) - errConv := callbackSyntheticForTests(reflect.Value{}, errors.New("test")) - - tests := []struct { - f callbackArgConverter - o reflect.Value - }{ - {intConv, reflect.ValueOf(int8(-1))}, - {intConv, reflect.ValueOf(int16(-1))}, - {intConv, reflect.ValueOf(int32(-1))}, - {intConv, reflect.ValueOf(uint8(math.MaxUint8))}, - {intConv, reflect.ValueOf(uint16(math.MaxUint16))}, - {intConv, reflect.ValueOf(uint32(math.MaxUint32))}, - // Special case, int64->uint64 is only 1<<63 - 1, not 1<<64 - 1 - {intConv, reflect.ValueOf(uint64(math.MaxInt64))}, - {floatConv, reflect.ValueOf(float32(math.Inf(1)))}, - } - - for _, test := range tests { - conv := callbackArgCast{test.f, test.o.Type()} - val, err := conv.Run(nil) - if err != nil { - t.Errorf("Couldn't convert to %s: %s", test.o.Type(), err) - } else if !reflect.DeepEqual(val.Interface(), test.o.Interface()) { - t.Errorf("Unexpected result from converting to %s: got %v, want %v", test.o.Type(), val.Interface(), test.o.Interface()) - } - } - - conv := callbackArgCast{errConv, reflect.TypeOf(int8(0))} - _, err := conv.Run(nil) - if err == nil { - t.Errorf("Expected error during callbackArgCast, but got none") - } -} - -func TestCallbackConverters(t *testing.T) { - tests := []struct { - v interface{} - err bool - }{ - // Unfortunately, we can't tell which converter was returned, - // but we can at least check which types can be converted. - {[]byte{0}, false}, - {"text", false}, - {true, false}, - {int8(0), false}, - {int16(0), false}, - {int32(0), false}, - {int64(0), false}, - {uint8(0), false}, - {uint16(0), false}, - {uint32(0), false}, - {uint64(0), false}, - {int(0), false}, - {uint(0), false}, - {float64(0), false}, - {float32(0), false}, - - {func() {}, true}, - {complex64(complex(0, 0)), true}, - {complex128(complex(0, 0)), true}, - {struct{}{}, true}, - {map[string]string{}, true}, - {[]string{}, true}, - {(*int8)(nil), true}, - {make(chan int), true}, - } - - for _, test := range tests { - _, err := callbackArg(reflect.TypeOf(test.v)) - if test.err && err == nil { - t.Errorf("Expected an error when converting %s, got no error", reflect.TypeOf(test.v)) - } else if !test.err && err != nil { - t.Errorf("Expected converter when converting %s, got error: %s", reflect.TypeOf(test.v), err) - } - } - - for _, test := range tests { - _, err := callbackRet(reflect.TypeOf(test.v)) - if test.err && err == nil { - t.Errorf("Expected an error when converting %s, got no error", reflect.TypeOf(test.v)) - } else if !test.err && err != nil { - t.Errorf("Expected converter when converting %s, got error: %s", reflect.TypeOf(test.v), err) - } - } -} diff --git a/vendor/github.com/mattn/go-sqlite3/error_test.go b/vendor/github.com/mattn/go-sqlite3/error_test.go deleted file mode 100644 index 1ccbe5bf8583..000000000000 --- a/vendor/github.com/mattn/go-sqlite3/error_test.go +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright (C) 2014 Yasuhiro Matsumoto . -// -// Use of this source code is governed by an MIT-style -// license that can be found in the LICENSE file. - -package sqlite3 - -import ( - "database/sql" - "io/ioutil" - "os" - "path" - "testing" -) - -func TestSimpleError(t *testing.T) { - e := ErrError.Error() - if e != "SQL logic error or missing database" { - t.Error("wrong error code:" + e) - } -} - -func TestCorruptDbErrors(t *testing.T) { - dirName, err := ioutil.TempDir("", "sqlite3") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dirName) - - dbFileName := path.Join(dirName, "test.db") - f, err := os.Create(dbFileName) - if err != nil { - t.Error(err) - } - f.Write([]byte{1, 2, 3, 4, 5}) - f.Close() - - db, err := sql.Open("sqlite3", dbFileName) - if err == nil { - _, err = db.Exec("drop table foo") - } - - sqliteErr := err.(Error) - if sqliteErr.Code != ErrNotADB { - t.Error("wrong error code for corrupted DB") - } - if err.Error() == "" { - t.Error("wrong error string for corrupted DB") - } - db.Close() -} - -func TestSqlLogicErrors(t *testing.T) { - dirName, err := ioutil.TempDir("", "sqlite3") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dirName) - - dbFileName := path.Join(dirName, "test.db") - db, err := sql.Open("sqlite3", dbFileName) - if err != nil { - t.Error(err) - } - defer db.Close() - - _, err = db.Exec("CREATE TABLE Foo (id INTEGER PRIMARY KEY)") - if err != nil { - t.Error(err) - } - - const expectedErr = "table Foo already exists" - _, err = db.Exec("CREATE TABLE Foo (id INTEGER PRIMARY KEY)") - if err.Error() != expectedErr { - t.Errorf("Unexpected error: %s, expected %s", err.Error(), expectedErr) - } - -} - -func TestExtendedErrorCodes_ForeignKey(t *testing.T) { - dirName, err := ioutil.TempDir("", "sqlite3-err") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dirName) - - dbFileName := path.Join(dirName, "test.db") - db, err := sql.Open("sqlite3", dbFileName) - if err != nil { - t.Error(err) - } - defer db.Close() - - _, err = db.Exec("PRAGMA foreign_keys=ON;") - if err != nil { - t.Errorf("PRAGMA foreign_keys=ON: %v", err) - } - - _, err = db.Exec(`CREATE TABLE Foo ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - value INTEGER NOT NULL, - ref INTEGER NULL REFERENCES Foo (id), - UNIQUE(value) - );`) - if err != nil { - t.Error(err) - } - - _, err = db.Exec("INSERT INTO Foo (ref, value) VALUES (100, 100);") - if err == nil { - t.Error("No error!") - } else { - sqliteErr := err.(Error) - if sqliteErr.Code != ErrConstraint { - t.Errorf("Wrong basic error code: %d != %d", - sqliteErr.Code, ErrConstraint) - } - if sqliteErr.ExtendedCode != ErrConstraintForeignKey { - t.Errorf("Wrong extended error code: %d != %d", - sqliteErr.ExtendedCode, ErrConstraintForeignKey) - } - } - -} - -func TestExtendedErrorCodes_NotNull(t *testing.T) { - dirName, err := ioutil.TempDir("", "sqlite3-err") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dirName) - - dbFileName := path.Join(dirName, "test.db") - db, err := sql.Open("sqlite3", dbFileName) - if err != nil { - t.Error(err) - } - defer db.Close() - - _, err = db.Exec("PRAGMA foreign_keys=ON;") - if err != nil { - t.Errorf("PRAGMA foreign_keys=ON: %v", err) - } - - _, err = db.Exec(`CREATE TABLE Foo ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - value INTEGER NOT NULL, - ref INTEGER NULL REFERENCES Foo (id), - UNIQUE(value) - );`) - if err != nil { - t.Error(err) - } - - res, err := db.Exec("INSERT INTO Foo (value) VALUES (100);") - if err != nil { - t.Fatalf("Creating first row: %v", err) - } - - id, err := res.LastInsertId() - if err != nil { - t.Fatalf("Retrieving last insert id: %v", err) - } - - _, err = db.Exec("INSERT INTO Foo (ref) VALUES (?);", id) - if err == nil { - t.Error("No error!") - } else { - sqliteErr := err.(Error) - if sqliteErr.Code != ErrConstraint { - t.Errorf("Wrong basic error code: %d != %d", - sqliteErr.Code, ErrConstraint) - } - if sqliteErr.ExtendedCode != ErrConstraintNotNull { - t.Errorf("Wrong extended error code: %d != %d", - sqliteErr.ExtendedCode, ErrConstraintNotNull) - } - } - -} - -func TestExtendedErrorCodes_Unique(t *testing.T) { - dirName, err := ioutil.TempDir("", "sqlite3-err") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dirName) - - dbFileName := path.Join(dirName, "test.db") - db, err := sql.Open("sqlite3", dbFileName) - if err != nil { - t.Error(err) - } - defer db.Close() - - _, err = db.Exec("PRAGMA foreign_keys=ON;") - if err != nil { - t.Errorf("PRAGMA foreign_keys=ON: %v", err) - } - - _, err = db.Exec(`CREATE TABLE Foo ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - value INTEGER NOT NULL, - ref INTEGER NULL REFERENCES Foo (id), - UNIQUE(value) - );`) - if err != nil { - t.Error(err) - } - - res, err := db.Exec("INSERT INTO Foo (value) VALUES (100);") - if err != nil { - t.Fatalf("Creating first row: %v", err) - } - - id, err := res.LastInsertId() - if err != nil { - t.Fatalf("Retrieving last insert id: %v", err) - } - - _, err = db.Exec("INSERT INTO Foo (ref, value) VALUES (?, 100);", id) - if err == nil { - t.Error("No error!") - } else { - sqliteErr := err.(Error) - if sqliteErr.Code != ErrConstraint { - t.Errorf("Wrong basic error code: %d != %d", - sqliteErr.Code, ErrConstraint) - } - if sqliteErr.ExtendedCode != ErrConstraintUnique { - t.Errorf("Wrong extended error code: %d != %d", - sqliteErr.ExtendedCode, ErrConstraintUnique) - } - extended := sqliteErr.Code.Extend(3).Error() - expected := "constraint failed" - if extended != expected { - t.Errorf("Wrong basic error code: %q != %q", - extended, expected) - } - } - -} diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_fts3_test.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_fts3_test.go deleted file mode 100644 index e06fc5d1d09d..000000000000 --- a/vendor/github.com/mattn/go-sqlite3/sqlite3_fts3_test.go +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (C) 2015 Yasuhiro Matsumoto . -// -// Use of this source code is governed by an MIT-style -// license that can be found in the LICENSE file. - -package sqlite3 - -import ( - "database/sql" - "os" - "testing" -) - -func TestFTS3(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - defer db.Close() - - _, err = db.Exec("DROP TABLE foo") - _, err = db.Exec("CREATE VIRTUAL TABLE foo USING fts3(id INTEGER PRIMARY KEY, value TEXT)") - if err != nil { - t.Fatal("Failed to create table:", err) - } - - _, err = db.Exec("INSERT INTO foo(id, value) VALUES(?, ?)", 1, `今日の 晩御飯は 天麩羅よ`) - if err != nil { - t.Fatal("Failed to insert value:", err) - } - - _, err = db.Exec("INSERT INTO foo(id, value) VALUES(?, ?)", 2, `今日は いい 天気だ`) - if err != nil { - t.Fatal("Failed to insert value:", err) - } - - rows, err := db.Query("SELECT id, value FROM foo WHERE value MATCH '今日* 天*'") - if err != nil { - t.Fatal("Unable to query foo table:", err) - } - defer rows.Close() - - for rows.Next() { - var id int - var value string - - if err := rows.Scan(&id, &value); err != nil { - t.Error("Unable to scan results:", err) - continue - } - - if id == 1 && value != `今日の 晩御飯は 天麩羅よ` { - t.Error("Value for id 1 should be `今日の 晩御飯は 天麩羅よ`, but:", value) - } else if id == 2 && value != `今日は いい 天気だ` { - t.Error("Value for id 2 should be `今日は いい 天気だ`, but:", value) - } - } - - rows, err = db.Query("SELECT value FROM foo WHERE value MATCH '今日* 天麩羅*'") - if err != nil { - t.Fatal("Unable to query foo table:", err) - } - defer rows.Close() - - var value string - if !rows.Next() { - t.Fatal("Result should be only one") - } - - if err := rows.Scan(&value); err != nil { - t.Fatal("Unable to scan results:", err) - } - - if value != `今日の 晩御飯は 天麩羅よ` { - t.Fatal("Value should be `今日の 晩御飯は 天麩羅よ`, but:", value) - } - - if rows.Next() { - t.Fatal("Result should be only one") - } -} - -func TestFTS4(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - defer db.Close() - - _, err = db.Exec("DROP TABLE foo") - _, err = db.Exec("CREATE VIRTUAL TABLE foo USING fts4(tokenize=unicode61, id INTEGER PRIMARY KEY, value TEXT)") - switch { - case err != nil && err.Error() == "unknown tokenizer: unicode61": - t.Skip("FTS4 not supported") - case err != nil: - t.Fatal("Failed to create table:", err) - } - - _, err = db.Exec("INSERT INTO foo(id, value) VALUES(?, ?)", 1, `février`) - if err != nil { - t.Fatal("Failed to insert value:", err) - } - - rows, err := db.Query("SELECT value FROM foo WHERE value MATCH 'fevrier'") - if err != nil { - t.Fatal("Unable to query foo table:", err) - } - defer rows.Close() - - var value string - if !rows.Next() { - t.Fatal("Result should be only one") - } - - if err := rows.Scan(&value); err != nil { - t.Fatal("Unable to scan results:", err) - } - - if value != `février` { - t.Fatal("Value should be `février`, but:", value) - } - - if rows.Next() { - t.Fatal("Result should be only one") - } -} diff --git a/vendor/github.com/mattn/go-sqlite3/sqlite3_test.go b/vendor/github.com/mattn/go-sqlite3/sqlite3_test.go deleted file mode 100644 index 44ec64084f3c..000000000000 --- a/vendor/github.com/mattn/go-sqlite3/sqlite3_test.go +++ /dev/null @@ -1,1350 +0,0 @@ -// Copyright (C) 2014 Yasuhiro Matsumoto . -// -// Use of this source code is governed by an MIT-style -// license that can be found in the LICENSE file. - -package sqlite3 - -import ( - "database/sql" - "database/sql/driver" - "errors" - "fmt" - "io/ioutil" - "net/url" - "os" - "reflect" - "regexp" - "strings" - "sync" - "testing" - "time" - - "github.com/mattn/go-sqlite3/sqlite3_test" -) - -func TempFilename(t *testing.T) string { - f, err := ioutil.TempFile("", "go-sqlite3-test-") - if err != nil { - t.Fatal(err) - } - f.Close() - return f.Name() -} - -func doTestOpen(t *testing.T, option string) (string, error) { - var url string - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - if option != "" { - url = tempFilename + option - } else { - url = tempFilename - } - db, err := sql.Open("sqlite3", url) - if err != nil { - return "Failed to open database:", err - } - defer os.Remove(tempFilename) - defer db.Close() - - _, err = db.Exec("drop table foo") - _, err = db.Exec("create table foo (id integer)") - if err != nil { - return "Failed to create table:", err - } - - if stat, err := os.Stat(tempFilename); err != nil || stat.IsDir() { - return "Failed to create ./foo.db", nil - } - - return "", nil -} - -func TestOpen(t *testing.T) { - cases := map[string]bool{ - "": true, - "?_txlock=immediate": true, - "?_txlock=deferred": true, - "?_txlock=exclusive": true, - "?_txlock=bogus": false, - } - for option, expectedPass := range cases { - result, err := doTestOpen(t, option) - if result == "" { - if !expectedPass { - errmsg := fmt.Sprintf("_txlock error not caught at dbOpen with option: %s", option) - t.Fatal(errmsg) - } - } else if expectedPass { - if err == nil { - t.Fatal(result) - } else { - t.Fatal(result, err) - } - } - } -} - -func TestReadonly(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - - db1, err := sql.Open("sqlite3", "file:"+tempFilename) - if err != nil { - t.Fatal(err) - } - db1.Exec("CREATE TABLE test (x int, y float)") - - db2, err := sql.Open("sqlite3", "file:"+tempFilename+"?mode=ro") - if err != nil { - t.Fatal(err) - } - _ = db2 - _, err = db2.Exec("INSERT INTO test VALUES (1, 3.14)") - if err == nil { - t.Fatal("didn't expect INSERT into read-only database to work") - } -} - -func TestClose(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - - _, err = db.Exec("drop table foo") - _, err = db.Exec("create table foo (id integer)") - if err != nil { - t.Fatal("Failed to create table:", err) - } - - stmt, err := db.Prepare("select id from foo where id = ?") - if err != nil { - t.Fatal("Failed to select records:", err) - } - - db.Close() - _, err = stmt.Exec(1) - if err == nil { - t.Fatal("Failed to operate closed statement") - } -} - -func TestInsert(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - defer db.Close() - - _, err = db.Exec("drop table foo") - _, err = db.Exec("create table foo (id integer)") - if err != nil { - t.Fatal("Failed to create table:", err) - } - - res, err := db.Exec("insert into foo(id) values(123)") - if err != nil { - t.Fatal("Failed to insert record:", err) - } - affected, _ := res.RowsAffected() - if affected != 1 { - t.Fatalf("Expected %d for affected rows, but %d:", 1, affected) - } - - rows, err := db.Query("select id from foo") - if err != nil { - t.Fatal("Failed to select records:", err) - } - defer rows.Close() - - rows.Next() - - var result int - rows.Scan(&result) - if result != 123 { - t.Errorf("Expected %d for fetched result, but %d:", 123, result) - } -} - -func TestUpdate(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - defer db.Close() - - _, err = db.Exec("drop table foo") - _, err = db.Exec("create table foo (id integer)") - if err != nil { - t.Fatal("Failed to create table:", err) - } - - res, err := db.Exec("insert into foo(id) values(123)") - if err != nil { - t.Fatal("Failed to insert record:", err) - } - expected, err := res.LastInsertId() - if err != nil { - t.Fatal("Failed to get LastInsertId:", err) - } - affected, _ := res.RowsAffected() - if err != nil { - t.Fatal("Failed to get RowsAffected:", err) - } - if affected != 1 { - t.Fatalf("Expected %d for affected rows, but %d:", 1, affected) - } - - res, err = db.Exec("update foo set id = 234") - if err != nil { - t.Fatal("Failed to update record:", err) - } - lastId, err := res.LastInsertId() - if err != nil { - t.Fatal("Failed to get LastInsertId:", err) - } - if expected != lastId { - t.Errorf("Expected %q for last Id, but %q:", expected, lastId) - } - affected, _ = res.RowsAffected() - if err != nil { - t.Fatal("Failed to get RowsAffected:", err) - } - if affected != 1 { - t.Fatalf("Expected %d for affected rows, but %d:", 1, affected) - } - - rows, err := db.Query("select id from foo") - if err != nil { - t.Fatal("Failed to select records:", err) - } - defer rows.Close() - - rows.Next() - - var result int - rows.Scan(&result) - if result != 234 { - t.Errorf("Expected %d for fetched result, but %d:", 234, result) - } -} - -func TestDelete(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - defer db.Close() - - _, err = db.Exec("drop table foo") - _, err = db.Exec("create table foo (id integer)") - if err != nil { - t.Fatal("Failed to create table:", err) - } - - res, err := db.Exec("insert into foo(id) values(123)") - if err != nil { - t.Fatal("Failed to insert record:", err) - } - expected, err := res.LastInsertId() - if err != nil { - t.Fatal("Failed to get LastInsertId:", err) - } - affected, err := res.RowsAffected() - if err != nil { - t.Fatal("Failed to get RowsAffected:", err) - } - if affected != 1 { - t.Errorf("Expected %d for cout of affected rows, but %q:", 1, affected) - } - - res, err = db.Exec("delete from foo where id = 123") - if err != nil { - t.Fatal("Failed to delete record:", err) - } - lastId, err := res.LastInsertId() - if err != nil { - t.Fatal("Failed to get LastInsertId:", err) - } - if expected != lastId { - t.Errorf("Expected %q for last Id, but %q:", expected, lastId) - } - affected, err = res.RowsAffected() - if err != nil { - t.Fatal("Failed to get RowsAffected:", err) - } - if affected != 1 { - t.Errorf("Expected %d for cout of affected rows, but %q:", 1, affected) - } - - rows, err := db.Query("select id from foo") - if err != nil { - t.Fatal("Failed to select records:", err) - } - defer rows.Close() - - if rows.Next() { - t.Error("Fetched row but expected not rows") - } -} - -func TestBooleanRoundtrip(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - defer db.Close() - - _, err = db.Exec("DROP TABLE foo") - _, err = db.Exec("CREATE TABLE foo(id INTEGER, value BOOL)") - if err != nil { - t.Fatal("Failed to create table:", err) - } - - _, err = db.Exec("INSERT INTO foo(id, value) VALUES(1, ?)", true) - if err != nil { - t.Fatal("Failed to insert true value:", err) - } - - _, err = db.Exec("INSERT INTO foo(id, value) VALUES(2, ?)", false) - if err != nil { - t.Fatal("Failed to insert false value:", err) - } - - rows, err := db.Query("SELECT id, value FROM foo") - if err != nil { - t.Fatal("Unable to query foo table:", err) - } - defer rows.Close() - - for rows.Next() { - var id int - var value bool - - if err := rows.Scan(&id, &value); err != nil { - t.Error("Unable to scan results:", err) - continue - } - - if id == 1 && !value { - t.Error("Value for id 1 should be true, not false") - - } else if id == 2 && value { - t.Error("Value for id 2 should be false, not true") - } - } -} - -func timezone(t time.Time) string { return t.Format("-07:00") } - -func TestTimestamp(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - defer db.Close() - - _, err = db.Exec("DROP TABLE foo") - _, err = db.Exec("CREATE TABLE foo(id INTEGER, ts timeSTAMP, dt DATETIME)") - if err != nil { - t.Fatal("Failed to create table:", err) - } - - timestamp1 := time.Date(2012, time.April, 6, 22, 50, 0, 0, time.UTC) - timestamp2 := time.Date(2006, time.January, 2, 15, 4, 5, 123456789, time.UTC) - timestamp3 := time.Date(2012, time.November, 4, 0, 0, 0, 0, time.UTC) - tzTest := time.FixedZone("TEST", -9*3600-13*60) - tests := []struct { - value interface{} - expected time.Time - }{ - {"nonsense", time.Time{}}, - {"0000-00-00 00:00:00", time.Time{}}, - {timestamp1, timestamp1}, - {timestamp2.Unix(), timestamp2.Truncate(time.Second)}, - {timestamp2.UnixNano() / int64(time.Millisecond), timestamp2.Truncate(time.Millisecond)}, - {timestamp1.In(tzTest), timestamp1.In(tzTest)}, - {timestamp1.Format("2006-01-02 15:04:05.000"), timestamp1}, - {timestamp1.Format("2006-01-02T15:04:05.000"), timestamp1}, - {timestamp1.Format("2006-01-02 15:04:05"), timestamp1}, - {timestamp1.Format("2006-01-02T15:04:05"), timestamp1}, - {timestamp2, timestamp2}, - {"2006-01-02 15:04:05.123456789", timestamp2}, - {"2006-01-02T15:04:05.123456789", timestamp2}, - {"2006-01-02T05:51:05.123456789-09:13", timestamp2.In(tzTest)}, - {"2012-11-04", timestamp3}, - {"2012-11-04 00:00", timestamp3}, - {"2012-11-04 00:00:00", timestamp3}, - {"2012-11-04 00:00:00.000", timestamp3}, - {"2012-11-04T00:00", timestamp3}, - {"2012-11-04T00:00:00", timestamp3}, - {"2012-11-04T00:00:00.000", timestamp3}, - {"2006-01-02T15:04:05.123456789Z", timestamp2}, - {"2012-11-04Z", timestamp3}, - {"2012-11-04 00:00Z", timestamp3}, - {"2012-11-04 00:00:00Z", timestamp3}, - {"2012-11-04 00:00:00.000Z", timestamp3}, - {"2012-11-04T00:00Z", timestamp3}, - {"2012-11-04T00:00:00Z", timestamp3}, - {"2012-11-04T00:00:00.000Z", timestamp3}, - } - for i := range tests { - _, err = db.Exec("INSERT INTO foo(id, ts, dt) VALUES(?, ?, ?)", i, tests[i].value, tests[i].value) - if err != nil { - t.Fatal("Failed to insert timestamp:", err) - } - } - - rows, err := db.Query("SELECT id, ts, dt FROM foo ORDER BY id ASC") - if err != nil { - t.Fatal("Unable to query foo table:", err) - } - defer rows.Close() - - seen := 0 - for rows.Next() { - var id int - var ts, dt time.Time - - if err := rows.Scan(&id, &ts, &dt); err != nil { - t.Error("Unable to scan results:", err) - continue - } - if id < 0 || id >= len(tests) { - t.Error("Bad row id: ", id) - continue - } - seen++ - if !tests[id].expected.Equal(ts) { - t.Errorf("Timestamp value for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected, dt) - } - if !tests[id].expected.Equal(dt) { - t.Errorf("Datetime value for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected, dt) - } - if timezone(tests[id].expected) != timezone(ts) { - t.Errorf("Timezone for id %v (%v) should be %v, not %v", id, tests[id].value, - timezone(tests[id].expected), timezone(ts)) - } - if timezone(tests[id].expected) != timezone(dt) { - t.Errorf("Timezone for id %v (%v) should be %v, not %v", id, tests[id].value, - timezone(tests[id].expected), timezone(dt)) - } - } - - if seen != len(tests) { - t.Errorf("Expected to see %d rows", len(tests)) - } -} - -func TestBoolean(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - - defer db.Close() - - _, err = db.Exec("CREATE TABLE foo(id INTEGER, fbool BOOLEAN)") - if err != nil { - t.Fatal("Failed to create table:", err) - } - - bool1 := true - _, err = db.Exec("INSERT INTO foo(id, fbool) VALUES(1, ?)", bool1) - if err != nil { - t.Fatal("Failed to insert boolean:", err) - } - - bool2 := false - _, err = db.Exec("INSERT INTO foo(id, fbool) VALUES(2, ?)", bool2) - if err != nil { - t.Fatal("Failed to insert boolean:", err) - } - - bool3 := "nonsense" - _, err = db.Exec("INSERT INTO foo(id, fbool) VALUES(3, ?)", bool3) - if err != nil { - t.Fatal("Failed to insert nonsense:", err) - } - - rows, err := db.Query("SELECT id, fbool FROM foo where fbool = ?", bool1) - if err != nil { - t.Fatal("Unable to query foo table:", err) - } - counter := 0 - - var id int - var fbool bool - - for rows.Next() { - if err := rows.Scan(&id, &fbool); err != nil { - t.Fatal("Unable to scan results:", err) - } - counter++ - } - - if counter != 1 { - t.Fatalf("Expected 1 row but %v", counter) - } - - if id != 1 && fbool != true { - t.Fatalf("Value for id 1 should be %v, not %v", bool1, fbool) - } - - rows, err = db.Query("SELECT id, fbool FROM foo where fbool = ?", bool2) - if err != nil { - t.Fatal("Unable to query foo table:", err) - } - - counter = 0 - - for rows.Next() { - if err := rows.Scan(&id, &fbool); err != nil { - t.Fatal("Unable to scan results:", err) - } - counter++ - } - - if counter != 1 { - t.Fatalf("Expected 1 row but %v", counter) - } - - if id != 2 && fbool != false { - t.Fatalf("Value for id 2 should be %v, not %v", bool2, fbool) - } - - // make sure "nonsense" triggered an error - rows, err = db.Query("SELECT id, fbool FROM foo where id=?;", 3) - if err != nil { - t.Fatal("Unable to query foo table:", err) - } - - rows.Next() - err = rows.Scan(&id, &fbool) - if err == nil { - t.Error("Expected error from \"nonsense\" bool") - } -} - -func TestFloat32(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - defer db.Close() - - _, err = db.Exec("CREATE TABLE foo(id INTEGER)") - if err != nil { - t.Fatal("Failed to create table:", err) - } - - _, err = db.Exec("INSERT INTO foo(id) VALUES(null)") - if err != nil { - t.Fatal("Failed to insert null:", err) - } - - rows, err := db.Query("SELECT id FROM foo") - if err != nil { - t.Fatal("Unable to query foo table:", err) - } - - if !rows.Next() { - t.Fatal("Unable to query results:", err) - } - - var id interface{} - if err := rows.Scan(&id); err != nil { - t.Fatal("Unable to scan results:", err) - } - if id != nil { - t.Error("Expected nil but not") - } -} - -func TestNull(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - defer db.Close() - - rows, err := db.Query("SELECT 3.141592") - if err != nil { - t.Fatal("Unable to query foo table:", err) - } - - if !rows.Next() { - t.Fatal("Unable to query results:", err) - } - - var v interface{} - if err := rows.Scan(&v); err != nil { - t.Fatal("Unable to scan results:", err) - } - f, ok := v.(float64) - if !ok { - t.Error("Expected float but not") - } - if f != 3.141592 { - t.Error("Expected 3.141592 but not") - } -} - -func TestTransaction(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - defer db.Close() - - _, err = db.Exec("CREATE TABLE foo(id INTEGER)") - if err != nil { - t.Fatal("Failed to create table:", err) - } - - tx, err := db.Begin() - if err != nil { - t.Fatal("Failed to begin transaction:", err) - } - - _, err = tx.Exec("INSERT INTO foo(id) VALUES(1)") - if err != nil { - t.Fatal("Failed to insert null:", err) - } - - rows, err := tx.Query("SELECT id from foo") - if err != nil { - t.Fatal("Unable to query foo table:", err) - } - - err = tx.Rollback() - if err != nil { - t.Fatal("Failed to rollback transaction:", err) - } - - if rows.Next() { - t.Fatal("Unable to query results:", err) - } - - tx, err = db.Begin() - if err != nil { - t.Fatal("Failed to begin transaction:", err) - } - - _, err = tx.Exec("INSERT INTO foo(id) VALUES(1)") - if err != nil { - t.Fatal("Failed to insert null:", err) - } - - err = tx.Commit() - if err != nil { - t.Fatal("Failed to commit transaction:", err) - } - - rows, err = tx.Query("SELECT id from foo") - if err == nil { - t.Fatal("Expected failure to query") - } -} - -func TestWAL(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - defer db.Close() - - if _, err = db.Exec("PRAGMA journal_mode=WAL;"); err != nil { - t.Fatal("Failed to Exec PRAGMA journal_mode:", err) - } - if _, err = db.Exec("PRAGMA locking_mode=EXCLUSIVE;"); err != nil { - t.Fatal("Failed to Exec PRAGMA locking_mode:", err) - } - if _, err = db.Exec("CREATE TABLE test (id SERIAL, user TEXT NOT NULL, name TEXT NOT NULL);"); err != nil { - t.Fatal("Failed to Exec CREATE TABLE:", err) - } - if _, err = db.Exec("INSERT INTO test (user, name) VALUES ('user','name');"); err != nil { - t.Fatal("Failed to Exec INSERT:", err) - } - - trans, err := db.Begin() - if err != nil { - t.Fatal("Failed to Begin:", err) - } - s, err := trans.Prepare("INSERT INTO test (user, name) VALUES (?, ?);") - if err != nil { - t.Fatal("Failed to Prepare:", err) - } - - var count int - if err = trans.QueryRow("SELECT count(user) FROM test;").Scan(&count); err != nil { - t.Fatal("Failed to QueryRow:", err) - } - if _, err = s.Exec("bbbb", "aaaa"); err != nil { - t.Fatal("Failed to Exec prepared statement:", err) - } - if err = s.Close(); err != nil { - t.Fatal("Failed to Close prepared statement:", err) - } - if err = trans.Commit(); err != nil { - t.Fatal("Failed to Commit:", err) - } -} - -func TestTimezoneConversion(t *testing.T) { - zones := []string{"UTC", "US/Central", "US/Pacific", "Local"} - for _, tz := range zones { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename+"?_loc="+url.QueryEscape(tz)) - if err != nil { - t.Fatal("Failed to open database:", err) - } - defer db.Close() - - _, err = db.Exec("DROP TABLE foo") - _, err = db.Exec("CREATE TABLE foo(id INTEGER, ts TIMESTAMP, dt DATETIME)") - if err != nil { - t.Fatal("Failed to create table:", err) - } - - loc, err := time.LoadLocation(tz) - if err != nil { - t.Fatal("Failed to load location:", err) - } - - timestamp1 := time.Date(2012, time.April, 6, 22, 50, 0, 0, time.UTC) - timestamp2 := time.Date(2006, time.January, 2, 15, 4, 5, 123456789, time.UTC) - timestamp3 := time.Date(2012, time.November, 4, 0, 0, 0, 0, time.UTC) - tests := []struct { - value interface{} - expected time.Time - }{ - {"nonsense", time.Time{}.In(loc)}, - {"0000-00-00 00:00:00", time.Time{}.In(loc)}, - {timestamp1, timestamp1.In(loc)}, - {timestamp1.Unix(), timestamp1.In(loc)}, - {timestamp1.In(time.FixedZone("TEST", -7*3600)), timestamp1.In(loc)}, - {timestamp1.Format("2006-01-02 15:04:05.000"), timestamp1.In(loc)}, - {timestamp1.Format("2006-01-02T15:04:05.000"), timestamp1.In(loc)}, - {timestamp1.Format("2006-01-02 15:04:05"), timestamp1.In(loc)}, - {timestamp1.Format("2006-01-02T15:04:05"), timestamp1.In(loc)}, - {timestamp2, timestamp2.In(loc)}, - {"2006-01-02 15:04:05.123456789", timestamp2.In(loc)}, - {"2006-01-02T15:04:05.123456789", timestamp2.In(loc)}, - {"2012-11-04", timestamp3.In(loc)}, - {"2012-11-04 00:00", timestamp3.In(loc)}, - {"2012-11-04 00:00:00", timestamp3.In(loc)}, - {"2012-11-04 00:00:00.000", timestamp3.In(loc)}, - {"2012-11-04T00:00", timestamp3.In(loc)}, - {"2012-11-04T00:00:00", timestamp3.In(loc)}, - {"2012-11-04T00:00:00.000", timestamp3.In(loc)}, - } - for i := range tests { - _, err = db.Exec("INSERT INTO foo(id, ts, dt) VALUES(?, ?, ?)", i, tests[i].value, tests[i].value) - if err != nil { - t.Fatal("Failed to insert timestamp:", err) - } - } - - rows, err := db.Query("SELECT id, ts, dt FROM foo ORDER BY id ASC") - if err != nil { - t.Fatal("Unable to query foo table:", err) - } - defer rows.Close() - - seen := 0 - for rows.Next() { - var id int - var ts, dt time.Time - - if err := rows.Scan(&id, &ts, &dt); err != nil { - t.Error("Unable to scan results:", err) - continue - } - if id < 0 || id >= len(tests) { - t.Error("Bad row id: ", id) - continue - } - seen++ - if !tests[id].expected.Equal(ts) { - t.Errorf("Timestamp value for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected, ts) - } - if !tests[id].expected.Equal(dt) { - t.Errorf("Datetime value for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected, dt) - } - if tests[id].expected.Location().String() != ts.Location().String() { - t.Errorf("Location for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected.Location().String(), ts.Location().String()) - } - if tests[id].expected.Location().String() != dt.Location().String() { - t.Errorf("Location for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected.Location().String(), dt.Location().String()) - } - } - - if seen != len(tests) { - t.Errorf("Expected to see %d rows", len(tests)) - } - } -} - -func TestSuite(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename+"?_busy_timeout=99999") - if err != nil { - t.Fatal(err) - } - defer db.Close() - - sqlite3_test.RunTests(t, db, sqlite3_test.SQLITE) -} - -// TODO: Execer & Queryer currently disabled -// https://github.com/mattn/go-sqlite3/issues/82 -func TestExecer(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - defer db.Close() - - _, err = db.Exec(` - create table foo (id integer); -- one comment - insert into foo(id) values(?); - insert into foo(id) values(?); - insert into foo(id) values(?); -- another comment - `, 1, 2, 3) - if err != nil { - t.Error("Failed to call db.Exec:", err) - } -} - -func TestQueryer(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - defer db.Close() - - _, err = db.Exec(` - create table foo (id integer); - `) - if err != nil { - t.Error("Failed to call db.Query:", err) - } - - rows, err := db.Query(` - insert into foo(id) values(?); - insert into foo(id) values(?); - insert into foo(id) values(?); - select id from foo order by id; - `, 3, 2, 1) - if err != nil { - t.Error("Failed to call db.Query:", err) - } - defer rows.Close() - n := 1 - if rows != nil { - for rows.Next() { - var id int - err = rows.Scan(&id) - if err != nil { - t.Error("Failed to db.Query:", err) - } - if id != n { - t.Error("Failed to db.Query: not matched results") - } - } - } -} - -func TestStress(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - db.Exec("CREATE TABLE foo (id int);") - db.Exec("INSERT INTO foo VALUES(1);") - db.Exec("INSERT INTO foo VALUES(2);") - db.Close() - - for i := 0; i < 10000; i++ { - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - - for j := 0; j < 3; j++ { - rows, err := db.Query("select * from foo where id=1;") - if err != nil { - t.Error("Failed to call db.Query:", err) - } - for rows.Next() { - var i int - if err := rows.Scan(&i); err != nil { - t.Errorf("Scan failed: %v\n", err) - } - } - if err := rows.Err(); err != nil { - t.Errorf("Post-scan failed: %v\n", err) - } - rows.Close() - } - db.Close() - } -} - -func TestDateTimeLocal(t *testing.T) { - zone := "Asia/Tokyo" - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename+"?_loc="+zone) - if err != nil { - t.Fatal("Failed to open database:", err) - } - db.Exec("CREATE TABLE foo (dt datetime);") - db.Exec("INSERT INTO foo VALUES('2015-03-05 15:16:17');") - - row := db.QueryRow("select * from foo") - var d time.Time - err = row.Scan(&d) - if err != nil { - t.Fatal("Failed to scan datetime:", err) - } - if d.Hour() == 15 || !strings.Contains(d.String(), "JST") { - t.Fatal("Result should have timezone", d) - } - db.Close() - - db, err = sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - - row = db.QueryRow("select * from foo") - err = row.Scan(&d) - if err != nil { - t.Fatal("Failed to scan datetime:", err) - } - if d.UTC().Hour() != 15 || !strings.Contains(d.String(), "UTC") { - t.Fatalf("Result should not have timezone %v %v", zone, d.String()) - } - - _, err = db.Exec("DELETE FROM foo") - if err != nil { - t.Fatal("Failed to delete table:", err) - } - dt, err := time.Parse("2006/1/2 15/4/5 -0700 MST", "2015/3/5 15/16/17 +0900 JST") - if err != nil { - t.Fatal("Failed to parse datetime:", err) - } - db.Exec("INSERT INTO foo VALUES(?);", dt) - - db.Close() - db, err = sql.Open("sqlite3", tempFilename+"?_loc="+zone) - if err != nil { - t.Fatal("Failed to open database:", err) - } - - row = db.QueryRow("select * from foo") - err = row.Scan(&d) - if err != nil { - t.Fatal("Failed to scan datetime:", err) - } - if d.Hour() != 15 || !strings.Contains(d.String(), "JST") { - t.Fatalf("Result should have timezone %v %v", zone, d.String()) - } -} - -func TestVersion(t *testing.T) { - s, n, id := Version() - if s == "" || n == 0 || id == "" { - t.Errorf("Version failed %q, %d, %q\n", s, n, id) - } -} - -func TestNumberNamedParams(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - defer db.Close() - - _, err = db.Exec(` - create table foo (id integer, name text, extra text); - `) - if err != nil { - t.Error("Failed to call db.Query:", err) - } - - _, err = db.Exec(`insert into foo(id, name, extra) values($1, $2, $2)`, 1, "foo") - if err != nil { - t.Error("Failed to call db.Exec:", err) - } - - row := db.QueryRow(`select id, extra from foo where id = $1 and extra = $2`, 1, "foo") - if row == nil { - t.Error("Failed to call db.QueryRow") - } - var id int - var extra string - err = row.Scan(&id, &extra) - if err != nil { - t.Error("Failed to db.Scan:", err) - } - if id != 1 || extra != "foo" { - t.Error("Failed to db.QueryRow: not matched results") - } -} - -func TestStringContainingZero(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - defer db.Close() - - _, err = db.Exec(` - create table foo (id integer, name, extra text); - `) - if err != nil { - t.Error("Failed to call db.Query:", err) - } - - const text = "foo\x00bar" - - _, err = db.Exec(`insert into foo(id, name, extra) values($1, $2, $2)`, 1, text) - if err != nil { - t.Error("Failed to call db.Exec:", err) - } - - row := db.QueryRow(`select id, extra from foo where id = $1 and extra = $2`, 1, text) - if row == nil { - t.Error("Failed to call db.QueryRow") - } - - var id int - var extra string - err = row.Scan(&id, &extra) - if err != nil { - t.Error("Failed to db.Scan:", err) - } - if id != 1 || extra != text { - t.Error("Failed to db.QueryRow: not matched results") - } -} - -const CurrentTimeStamp = "2006-01-02 15:04:05" - -type TimeStamp struct{ *time.Time } - -func (t TimeStamp) Scan(value interface{}) error { - var err error - switch v := value.(type) { - case string: - *t.Time, err = time.Parse(CurrentTimeStamp, v) - case []byte: - *t.Time, err = time.Parse(CurrentTimeStamp, string(v)) - default: - err = errors.New("invalid type for current_timestamp") - } - return err -} - -func (t TimeStamp) Value() (driver.Value, error) { - return t.Time.Format(CurrentTimeStamp), nil -} - -func TestDateTimeNow(t *testing.T) { - tempFilename := TempFilename(t) - defer os.Remove(tempFilename) - db, err := sql.Open("sqlite3", tempFilename) - if err != nil { - t.Fatal("Failed to open database:", err) - } - defer db.Close() - - var d time.Time - err = db.QueryRow("SELECT datetime('now')").Scan(TimeStamp{&d}) - if err != nil { - t.Fatal("Failed to scan datetime:", err) - } -} - -func TestFunctionRegistration(t *testing.T) { - addi_8_16_32 := func(a int8, b int16) int32 { return int32(a) + int32(b) } - addi_64 := func(a, b int64) int64 { return a + b } - addu_8_16_32 := func(a uint8, b uint16) uint32 { return uint32(a) + uint32(b) } - addu_64 := func(a, b uint64) uint64 { return a + b } - addiu := func(a int, b uint) int64 { return int64(a) + int64(b) } - addf_32_64 := func(a float32, b float64) float64 { return float64(a) + b } - not := func(a bool) bool { return !a } - regex := func(re, s string) (bool, error) { - return regexp.MatchString(re, s) - } - generic := func(a interface{}) int64 { - switch a.(type) { - case int64: - return 1 - case float64: - return 2 - case []byte: - return 3 - case string: - return 4 - default: - panic("unreachable") - } - } - variadic := func(a, b int64, c ...int64) int64 { - ret := a + b - for _, d := range c { - ret += d - } - return ret - } - variadicGeneric := func(a ...interface{}) int64 { - return int64(len(a)) - } - - sql.Register("sqlite3_FunctionRegistration", &SQLiteDriver{ - ConnectHook: func(conn *SQLiteConn) error { - if err := conn.RegisterFunc("addi_8_16_32", addi_8_16_32, true); err != nil { - return err - } - if err := conn.RegisterFunc("addi_64", addi_64, true); err != nil { - return err - } - if err := conn.RegisterFunc("addu_8_16_32", addu_8_16_32, true); err != nil { - return err - } - if err := conn.RegisterFunc("addu_64", addu_64, true); err != nil { - return err - } - if err := conn.RegisterFunc("addiu", addiu, true); err != nil { - return err - } - if err := conn.RegisterFunc("addf_32_64", addf_32_64, true); err != nil { - return err - } - if err := conn.RegisterFunc("not", not, true); err != nil { - return err - } - if err := conn.RegisterFunc("regex", regex, true); err != nil { - return err - } - if err := conn.RegisterFunc("generic", generic, true); err != nil { - return err - } - if err := conn.RegisterFunc("variadic", variadic, true); err != nil { - return err - } - if err := conn.RegisterFunc("variadicGeneric", variadicGeneric, true); err != nil { - return err - } - return nil - }, - }) - db, err := sql.Open("sqlite3_FunctionRegistration", ":memory:") - if err != nil { - t.Fatal("Failed to open database:", err) - } - defer db.Close() - - ops := []struct { - query string - expected interface{} - }{ - {"SELECT addi_8_16_32(1,2)", int32(3)}, - {"SELECT addi_64(1,2)", int64(3)}, - {"SELECT addu_8_16_32(1,2)", uint32(3)}, - {"SELECT addu_64(1,2)", uint64(3)}, - {"SELECT addiu(1,2)", int64(3)}, - {"SELECT addf_32_64(1.5,1.5)", float64(3)}, - {"SELECT not(1)", false}, - {"SELECT not(0)", true}, - {`SELECT regex("^foo.*", "foobar")`, true}, - {`SELECT regex("^foo.*", "barfoobar")`, false}, - {"SELECT generic(1)", int64(1)}, - {"SELECT generic(1.1)", int64(2)}, - {`SELECT generic(NULL)`, int64(3)}, - {`SELECT generic("foo")`, int64(4)}, - {"SELECT variadic(1,2)", int64(3)}, - {"SELECT variadic(1,2,3,4)", int64(10)}, - {"SELECT variadic(1,1,1,1,1,1,1,1,1,1)", int64(10)}, - {`SELECT variadicGeneric(1,"foo",2.3, NULL)`, int64(4)}, - } - - for _, op := range ops { - ret := reflect.New(reflect.TypeOf(op.expected)) - err = db.QueryRow(op.query).Scan(ret.Interface()) - if err != nil { - t.Errorf("Query %q failed: %s", op.query, err) - } else if !reflect.DeepEqual(ret.Elem().Interface(), op.expected) { - t.Errorf("Query %q returned wrong value: got %v (%T), want %v (%T)", op.query, ret.Elem().Interface(), ret.Elem().Interface(), op.expected, op.expected) - } - } -} - -type sumAggregator int64 - -func (s *sumAggregator) Step(x int64) { - *s += sumAggregator(x) -} - -func (s *sumAggregator) Done() int64 { - return int64(*s) -} - -func TestAggregatorRegistration(t *testing.T) { - customSum := func() *sumAggregator { - var ret sumAggregator - return &ret - } - - sql.Register("sqlite3_AggregatorRegistration", &SQLiteDriver{ - ConnectHook: func(conn *SQLiteConn) error { - if err := conn.RegisterAggregator("customSum", customSum, true); err != nil { - return err - } - return nil - }, - }) - db, err := sql.Open("sqlite3_AggregatorRegistration", ":memory:") - if err != nil { - t.Fatal("Failed to open database:", err) - } - defer db.Close() - - _, err = db.Exec("create table foo (department integer, profits integer)") - if err != nil { - t.Fatal("Failed to create table:", err) - } - - _, err = db.Exec("insert into foo values (1, 10), (1, 20), (2, 42)") - if err != nil { - t.Fatal("Failed to insert records:", err) - } - - tests := []struct { - dept, sum int64 - }{ - {1, 30}, - {2, 42}, - } - - for _, test := range tests { - var ret int64 - err = db.QueryRow("select customSum(profits) from foo where department = $1 group by department", test.dept).Scan(&ret) - if err != nil { - t.Fatal("Query failed:", err) - } - if ret != test.sum { - t.Fatalf("Custom sum returned wrong value, got %d, want %d", ret, test.sum) - } - } -} - -func TestDeclTypes(t *testing.T) { - - d := SQLiteDriver{} - - conn, err := d.Open(":memory:") - if err != nil { - t.Fatal("Failed to begin transaction:", err) - } - defer conn.Close() - - sqlite3conn := conn.(*SQLiteConn) - - _, err = sqlite3conn.Exec("create table foo (id integer not null primary key, name text)", nil) - if err != nil { - t.Fatal("Failed to create table:", err) - } - - _, err = sqlite3conn.Exec("insert into foo(name) values(\"bar\")", nil) - if err != nil { - t.Fatal("Failed to insert:", err) - } - - rs, err := sqlite3conn.Query("select * from foo", nil) - if err != nil { - t.Fatal("Failed to select:", err) - } - defer rs.Close() - - declTypes := rs.(*SQLiteRows).DeclTypes() - - if !reflect.DeepEqual(declTypes, []string{"integer", "text"}) { - t.Fatal("Unexpected declTypes:", declTypes) - } -} - -var customFunctionOnce sync.Once - -func BenchmarkCustomFunctions(b *testing.B) { - customFunctionOnce.Do(func() { - custom_add := func(a, b int64) int64 { - return a + b - } - - sql.Register("sqlite3_BenchmarkCustomFunctions", &SQLiteDriver{ - ConnectHook: func(conn *SQLiteConn) error { - // Impure function to force sqlite to reexecute it each time. - if err := conn.RegisterFunc("custom_add", custom_add, false); err != nil { - return err - } - return nil - }, - }) - }) - - db, err := sql.Open("sqlite3_BenchmarkCustomFunctions", ":memory:") - if err != nil { - b.Fatal("Failed to open database:", err) - } - defer db.Close() - - b.ResetTimer() - for i := 0; i < b.N; i++ { - var i int64 - err = db.QueryRow("SELECT custom_add(1,2)").Scan(&i) - if err != nil { - b.Fatal("Failed to run custom add:", err) - } - } -} diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/BUILD b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/BUILD index 4ba71b2f859d..3e143d07f7d1 100644 --- a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/BUILD +++ b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -12,21 +12,6 @@ go_library( deps = ["//vendor/github.com/golang/protobuf/proto:go_default_library"], ) -go_test( - name = "go_default_test", - srcs = [ - "all_test.go", - "fixtures_test.go", - ], - importpath = "github.com/matttproud/golang_protobuf_extensions/pbutil", - library = ":go_default_library", - deps = [ - "//vendor/github.com/golang/protobuf/proto:go_default_library", - "//vendor/github.com/golang/protobuf/proto/testdata:go_default_library", - "//vendor/github.com/matttproud/golang_protobuf_extensions/pbtest:go_default_library", - ], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go deleted file mode 100644 index 094156e66c58..000000000000 --- a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go +++ /dev/null @@ -1,320 +0,0 @@ -// Copyright 2013 Matt T. Proud -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package pbutil - -import ( - "bytes" - "math/rand" - "reflect" - "testing" - "testing/quick" - - "github.com/matttproud/golang_protobuf_extensions/pbtest" - - . "github.com/golang/protobuf/proto" - . "github.com/golang/protobuf/proto/testdata" -) - -func TestWriteDelimited(t *testing.T) { - for _, test := range []struct { - msg Message - buf []byte - n int - err error - }{ - { - msg: &Empty{}, - n: 1, - buf: []byte{0}, - }, - { - msg: &GoEnum{Foo: FOO_FOO1.Enum()}, - n: 3, - buf: []byte{2, 8, 1}, - }, - { - msg: &Strings{ - StringField: String(`This is my gigantic, unhappy string. It exceeds -the encoding size of a single byte varint. We are using it to fuzz test the -correctness of the header decoding mechanisms, which may prove problematic. -I expect it may. Let's hope you enjoy testing as much as we do.`), - }, - n: 271, - buf: []byte{141, 2, 10, 138, 2, 84, 104, 105, 115, 32, 105, 115, 32, 109, - 121, 32, 103, 105, 103, 97, 110, 116, 105, 99, 44, 32, 117, 110, 104, - 97, 112, 112, 121, 32, 115, 116, 114, 105, 110, 103, 46, 32, 32, 73, - 116, 32, 101, 120, 99, 101, 101, 100, 115, 10, 116, 104, 101, 32, 101, - 110, 99, 111, 100, 105, 110, 103, 32, 115, 105, 122, 101, 32, 111, 102, - 32, 97, 32, 115, 105, 110, 103, 108, 101, 32, 98, 121, 116, 101, 32, - 118, 97, 114, 105, 110, 116, 46, 32, 32, 87, 101, 32, 97, 114, 101, 32, - 117, 115, 105, 110, 103, 32, 105, 116, 32, 116, 111, 32, 102, 117, 122, - 122, 32, 116, 101, 115, 116, 32, 116, 104, 101, 10, 99, 111, 114, 114, - 101, 99, 116, 110, 101, 115, 115, 32, 111, 102, 32, 116, 104, 101, 32, - 104, 101, 97, 100, 101, 114, 32, 100, 101, 99, 111, 100, 105, 110, 103, - 32, 109, 101, 99, 104, 97, 110, 105, 115, 109, 115, 44, 32, 119, 104, - 105, 99, 104, 32, 109, 97, 121, 32, 112, 114, 111, 118, 101, 32, 112, - 114, 111, 98, 108, 101, 109, 97, 116, 105, 99, 46, 10, 73, 32, 101, 120, - 112, 101, 99, 116, 32, 105, 116, 32, 109, 97, 121, 46, 32, 32, 76, 101, - 116, 39, 115, 32, 104, 111, 112, 101, 32, 121, 111, 117, 32, 101, 110, - 106, 111, 121, 32, 116, 101, 115, 116, 105, 110, 103, 32, 97, 115, 32, - 109, 117, 99, 104, 32, 97, 115, 32, 119, 101, 32, 100, 111, 46}, - }, - } { - var buf bytes.Buffer - if n, err := WriteDelimited(&buf, test.msg); n != test.n || err != test.err { - t.Fatalf("WriteDelimited(buf, %#v) = %v, %v; want %v, %v", test.msg, n, err, test.n, test.err) - } - if out := buf.Bytes(); !bytes.Equal(out, test.buf) { - t.Fatalf("WriteDelimited(buf, %#v); buf = %v; want %v", test.msg, out, test.buf) - } - } -} - -func TestReadDelimited(t *testing.T) { - for _, test := range []struct { - buf []byte - msg Message - n int - err error - }{ - { - buf: []byte{0}, - msg: &Empty{}, - n: 1, - }, - { - n: 3, - buf: []byte{2, 8, 1}, - msg: &GoEnum{Foo: FOO_FOO1.Enum()}, - }, - { - buf: []byte{141, 2, 10, 138, 2, 84, 104, 105, 115, 32, 105, 115, 32, 109, - 121, 32, 103, 105, 103, 97, 110, 116, 105, 99, 44, 32, 117, 110, 104, - 97, 112, 112, 121, 32, 115, 116, 114, 105, 110, 103, 46, 32, 32, 73, - 116, 32, 101, 120, 99, 101, 101, 100, 115, 10, 116, 104, 101, 32, 101, - 110, 99, 111, 100, 105, 110, 103, 32, 115, 105, 122, 101, 32, 111, 102, - 32, 97, 32, 115, 105, 110, 103, 108, 101, 32, 98, 121, 116, 101, 32, - 118, 97, 114, 105, 110, 116, 46, 32, 32, 87, 101, 32, 97, 114, 101, 32, - 117, 115, 105, 110, 103, 32, 105, 116, 32, 116, 111, 32, 102, 117, 122, - 122, 32, 116, 101, 115, 116, 32, 116, 104, 101, 10, 99, 111, 114, 114, - 101, 99, 116, 110, 101, 115, 115, 32, 111, 102, 32, 116, 104, 101, 32, - 104, 101, 97, 100, 101, 114, 32, 100, 101, 99, 111, 100, 105, 110, 103, - 32, 109, 101, 99, 104, 97, 110, 105, 115, 109, 115, 44, 32, 119, 104, - 105, 99, 104, 32, 109, 97, 121, 32, 112, 114, 111, 118, 101, 32, 112, - 114, 111, 98, 108, 101, 109, 97, 116, 105, 99, 46, 10, 73, 32, 101, 120, - 112, 101, 99, 116, 32, 105, 116, 32, 109, 97, 121, 46, 32, 32, 76, 101, - 116, 39, 115, 32, 104, 111, 112, 101, 32, 121, 111, 117, 32, 101, 110, - 106, 111, 121, 32, 116, 101, 115, 116, 105, 110, 103, 32, 97, 115, 32, - 109, 117, 99, 104, 32, 97, 115, 32, 119, 101, 32, 100, 111, 46}, - msg: &Strings{ - StringField: String(`This is my gigantic, unhappy string. It exceeds -the encoding size of a single byte varint. We are using it to fuzz test the -correctness of the header decoding mechanisms, which may prove problematic. -I expect it may. Let's hope you enjoy testing as much as we do.`), - }, - n: 271, - }, - } { - msg := Clone(test.msg) - msg.Reset() - if n, err := ReadDelimited(bytes.NewBuffer(test.buf), msg); n != test.n || err != test.err { - t.Fatalf("ReadDelimited(%v, msg) = %v, %v; want %v, %v", test.buf, n, err, test.n, test.err) - } - if !Equal(msg, test.msg) { - t.Fatalf("ReadDelimited(%v, msg); msg = %v; want %v", test.buf, msg, test.msg) - } - } -} - -func TestEndToEndValid(t *testing.T) { - for _, test := range [][]Message{ - {&Empty{}}, - {&GoEnum{Foo: FOO_FOO1.Enum()}, &Empty{}, &GoEnum{Foo: FOO_FOO1.Enum()}}, - {&GoEnum{Foo: FOO_FOO1.Enum()}}, - {&Strings{ - StringField: String(`This is my gigantic, unhappy string. It exceeds -the encoding size of a single byte varint. We are using it to fuzz test the -correctness of the header decoding mechanisms, which may prove problematic. -I expect it may. Let's hope you enjoy testing as much as we do.`), - }}, - } { - var buf bytes.Buffer - var written int - for i, msg := range test { - n, err := WriteDelimited(&buf, msg) - if err != nil { - // Assumption: TestReadDelimited and TestWriteDelimited are sufficient - // and inputs for this test are explicitly exercised there. - t.Fatalf("WriteDelimited(buf, %v[%d]) = ?, %v; wanted ?, nil", test, i, err) - } - written += n - } - var read int - for i, msg := range test { - out := Clone(msg) - out.Reset() - n, _ := ReadDelimited(&buf, out) - // Decide to do EOF checking? - read += n - if !Equal(out, msg) { - t.Fatalf("out = %v; want %v[%d] = %#v", out, test, i, msg) - } - } - if read != written { - t.Fatalf("%v read = %d; want %d", test, read, written) - } - } -} - -// rndMessage generates a random valid Protocol Buffer message. -func rndMessage(r *rand.Rand) Message { - var t reflect.Type - switch v := rand.Intn(23); v { - // TODO(br): Uncomment the elements below once fix is incorporated, except - // for the elements marked as patently incompatible. - // case 0: - // t = reflect.TypeOf(&GoEnum{}) - // break - // case 1: - // t = reflect.TypeOf(&GoTestField{}) - // break - case 2: - t = reflect.TypeOf(&GoTest{}) - break - // case 3: - // t = reflect.TypeOf(&GoSkipTest{}) - // break - // case 4: - // t = reflect.TypeOf(&NonPackedTest{}) - // break - // case 5: - // t = reflect.TypeOf(&PackedTest{}) - // break - case 6: - t = reflect.TypeOf(&MaxTag{}) - break - case 7: - t = reflect.TypeOf(&OldMessage{}) - break - case 8: - t = reflect.TypeOf(&NewMessage{}) - break - case 9: - t = reflect.TypeOf(&InnerMessage{}) - break - case 10: - t = reflect.TypeOf(&OtherMessage{}) - break - case 11: - // PATENTLY INVALID FOR FUZZ GENERATION - // t = reflect.TypeOf(&MyMessage{}) - break - // case 12: - // t = reflect.TypeOf(&Ext{}) - // break - case 13: - // PATENTLY INVALID FOR FUZZ GENERATION - // t = reflect.TypeOf(&MyMessageSet{}) - break - // case 14: - // t = reflect.TypeOf(&Empty{}) - // break - // case 15: - // t = reflect.TypeOf(&MessageList{}) - // break - // case 16: - // t = reflect.TypeOf(&Strings{}) - // break - // case 17: - // t = reflect.TypeOf(&Defaults{}) - // break - // case 17: - // t = reflect.TypeOf(&SubDefaults{}) - // break - // case 18: - // t = reflect.TypeOf(&RepeatedEnum{}) - // break - case 19: - t = reflect.TypeOf(&MoreRepeated{}) - break - // case 20: - // t = reflect.TypeOf(&GroupOld{}) - // break - // case 21: - // t = reflect.TypeOf(&GroupNew{}) - // break - case 22: - t = reflect.TypeOf(&FloatingPoint{}) - break - default: - // TODO(br): Replace with an unreachable once fixed. - t = reflect.TypeOf(&GoTest{}) - break - } - if t == nil { - t = reflect.TypeOf(&GoTest{}) - } - v, ok := quick.Value(t, r) - if !ok { - panic("attempt to generate illegal item; consult item 11") - } - if err := pbtest.SanitizeGenerated(v.Interface().(Message)); err != nil { - panic(err) - } - return v.Interface().(Message) -} - -// rndMessages generates several random Protocol Buffer messages. -func rndMessages(r *rand.Rand) []Message { - n := r.Intn(128) - out := make([]Message, 0, n) - for i := 0; i < n; i++ { - out = append(out, rndMessage(r)) - } - return out -} - -func TestFuzz(t *testing.T) { - rnd := rand.New(rand.NewSource(42)) - check := func() bool { - messages := rndMessages(rnd) - var buf bytes.Buffer - var written int - for i, msg := range messages { - n, err := WriteDelimited(&buf, msg) - if err != nil { - t.Fatalf("WriteDelimited(buf, %v[%d]) = ?, %v; wanted ?, nil", messages, i, err) - } - written += n - } - var read int - for i, msg := range messages { - out := Clone(msg) - out.Reset() - n, _ := ReadDelimited(&buf, out) - read += n - if !Equal(out, msg) { - t.Fatalf("out = %v; want %v[%d] = %#v", out, messages, i, msg) - } - } - if read != written { - t.Fatalf("%v read = %d; want %d", messages, read, written) - } - return true - } - if err := quick.Check(check, nil); err != nil { - t.Fatal(err) - } -} diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go deleted file mode 100644 index d6d9b25594f2..000000000000 --- a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// http://github.com/golang/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package pbutil - -import ( - . "github.com/golang/protobuf/proto" - . "github.com/golang/protobuf/proto/testdata" -) - -// FROM https://github.com/golang/protobuf/blob/master/proto/all_test.go. - -func initGoTestField() *GoTestField { - f := new(GoTestField) - f.Label = String("label") - f.Type = String("type") - return f -} - -// These are all structurally equivalent but the tag numbers differ. -// (It's remarkable that required, optional, and repeated all have -// 8 letters.) -func initGoTest_RequiredGroup() *GoTest_RequiredGroup { - return &GoTest_RequiredGroup{ - RequiredField: String("required"), - } -} - -func initGoTest_OptionalGroup() *GoTest_OptionalGroup { - return &GoTest_OptionalGroup{ - RequiredField: String("optional"), - } -} - -func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { - return &GoTest_RepeatedGroup{ - RequiredField: String("repeated"), - } -} - -func initGoTest(setdefaults bool) *GoTest { - pb := new(GoTest) - if setdefaults { - pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) - pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) - pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) - pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) - pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) - pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) - pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) - pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) - pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) - pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) - pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted - pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) - pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) - } - - pb.Kind = GoTest_TIME.Enum() - pb.RequiredField = initGoTestField() - pb.F_BoolRequired = Bool(true) - pb.F_Int32Required = Int32(3) - pb.F_Int64Required = Int64(6) - pb.F_Fixed32Required = Uint32(32) - pb.F_Fixed64Required = Uint64(64) - pb.F_Uint32Required = Uint32(3232) - pb.F_Uint64Required = Uint64(6464) - pb.F_FloatRequired = Float32(3232) - pb.F_DoubleRequired = Float64(6464) - pb.F_StringRequired = String("string") - pb.F_BytesRequired = []byte("bytes") - pb.F_Sint32Required = Int32(-32) - pb.F_Sint64Required = Int64(-64) - pb.Requiredgroup = initGoTest_RequiredGroup() - - return pb -} diff --git a/vendor/github.com/petar/GoLLRB/llrb/BUILD b/vendor/github.com/petar/GoLLRB/llrb/BUILD index 187bc94e2a93..ae6247eebee6 100644 --- a/vendor/github.com/petar/GoLLRB/llrb/BUILD +++ b/vendor/github.com/petar/GoLLRB/llrb/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -13,16 +13,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = [ - "iterator_test.go", - "llrb_test.go", - ], - importpath = "github.com/petar/GoLLRB/llrb", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/petar/GoLLRB/llrb/iterator_test.go b/vendor/github.com/petar/GoLLRB/llrb/iterator_test.go deleted file mode 100644 index db5e12c92eb7..000000000000 --- a/vendor/github.com/petar/GoLLRB/llrb/iterator_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package llrb - -import ( - "reflect" - "testing" -) - -func TestAscendGreaterOrEqual(t *testing.T) { - tree := New() - tree.InsertNoReplace(Int(4)) - tree.InsertNoReplace(Int(6)) - tree.InsertNoReplace(Int(1)) - tree.InsertNoReplace(Int(3)) - var ary []Item - tree.AscendGreaterOrEqual(Int(-1), func(i Item) bool { - ary = append(ary, i) - return true - }) - expected := []Item{Int(1), Int(3), Int(4), Int(6)} - if !reflect.DeepEqual(ary, expected) { - t.Errorf("expected %v but got %v", expected, ary) - } - ary = nil - tree.AscendGreaterOrEqual(Int(3), func(i Item) bool { - ary = append(ary, i) - return true - }) - expected = []Item{Int(3), Int(4), Int(6)} - if !reflect.DeepEqual(ary, expected) { - t.Errorf("expected %v but got %v", expected, ary) - } - ary = nil - tree.AscendGreaterOrEqual(Int(2), func(i Item) bool { - ary = append(ary, i) - return true - }) - expected = []Item{Int(3), Int(4), Int(6)} - if !reflect.DeepEqual(ary, expected) { - t.Errorf("expected %v but got %v", expected, ary) - } -} - -func TestDescendLessOrEqual(t *testing.T) { - tree := New() - tree.InsertNoReplace(Int(4)) - tree.InsertNoReplace(Int(6)) - tree.InsertNoReplace(Int(1)) - tree.InsertNoReplace(Int(3)) - var ary []Item - tree.DescendLessOrEqual(Int(10), func(i Item) bool { - ary = append(ary, i) - return true - }) - expected := []Item{Int(6), Int(4), Int(3), Int(1)} - if !reflect.DeepEqual(ary, expected) { - t.Errorf("expected %v but got %v", expected, ary) - } - ary = nil - tree.DescendLessOrEqual(Int(4), func(i Item) bool { - ary = append(ary, i) - return true - }) - expected = []Item{Int(4), Int(3), Int(1)} - if !reflect.DeepEqual(ary, expected) { - t.Errorf("expected %v but got %v", expected, ary) - } - ary = nil - tree.DescendLessOrEqual(Int(5), func(i Item) bool { - ary = append(ary, i) - return true - }) - expected = []Item{Int(4), Int(3), Int(1)} - if !reflect.DeepEqual(ary, expected) { - t.Errorf("expected %v but got %v", expected, ary) - } -} diff --git a/vendor/github.com/petar/GoLLRB/llrb/llrb_test.go b/vendor/github.com/petar/GoLLRB/llrb/llrb_test.go deleted file mode 100644 index b7bc97800706..000000000000 --- a/vendor/github.com/petar/GoLLRB/llrb/llrb_test.go +++ /dev/null @@ -1,239 +0,0 @@ -// Copyright 2010 Petar Maymounkov. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package llrb - -import ( - "math" - "math/rand" - "testing" -) - -func TestCases(t *testing.T) { - tree := New() - tree.ReplaceOrInsert(Int(1)) - tree.ReplaceOrInsert(Int(1)) - if tree.Len() != 1 { - t.Errorf("expecting len 1") - } - if !tree.Has(Int(1)) { - t.Errorf("expecting to find key=1") - } - - tree.Delete(Int(1)) - if tree.Len() != 0 { - t.Errorf("expecting len 0") - } - if tree.Has(Int(1)) { - t.Errorf("not expecting to find key=1") - } - - tree.Delete(Int(1)) - if tree.Len() != 0 { - t.Errorf("expecting len 0") - } - if tree.Has(Int(1)) { - t.Errorf("not expecting to find key=1") - } -} - -func TestReverseInsertOrder(t *testing.T) { - tree := New() - n := 100 - for i := 0; i < n; i++ { - tree.ReplaceOrInsert(Int(n - i)) - } - i := 0 - tree.AscendGreaterOrEqual(Int(0), func(item Item) bool { - i++ - if item.(Int) != Int(i) { - t.Errorf("bad order: got %d, expect %d", item.(Int), i) - } - return true - }) -} - -func TestRange(t *testing.T) { - tree := New() - order := []String{ - "ab", "aba", "abc", "a", "aa", "aaa", "b", "a-", "a!", - } - for _, i := range order { - tree.ReplaceOrInsert(i) - } - k := 0 - tree.AscendRange(String("ab"), String("ac"), func(item Item) bool { - if k > 3 { - t.Fatalf("returned more items than expected") - } - i1 := order[k] - i2 := item.(String) - if i1 != i2 { - t.Errorf("expecting %s, got %s", i1, i2) - } - k++ - return true - }) -} - -func TestRandomInsertOrder(t *testing.T) { - tree := New() - n := 1000 - perm := rand.Perm(n) - for i := 0; i < n; i++ { - tree.ReplaceOrInsert(Int(perm[i])) - } - j := 0 - tree.AscendGreaterOrEqual(Int(0), func(item Item) bool { - if item.(Int) != Int(j) { - t.Fatalf("bad order") - } - j++ - return true - }) -} - -func TestRandomReplace(t *testing.T) { - tree := New() - n := 100 - perm := rand.Perm(n) - for i := 0; i < n; i++ { - tree.ReplaceOrInsert(Int(perm[i])) - } - perm = rand.Perm(n) - for i := 0; i < n; i++ { - if replaced := tree.ReplaceOrInsert(Int(perm[i])); replaced == nil || replaced.(Int) != Int(perm[i]) { - t.Errorf("error replacing") - } - } -} - -func TestRandomInsertSequentialDelete(t *testing.T) { - tree := New() - n := 1000 - perm := rand.Perm(n) - for i := 0; i < n; i++ { - tree.ReplaceOrInsert(Int(perm[i])) - } - for i := 0; i < n; i++ { - tree.Delete(Int(i)) - } -} - -func TestRandomInsertDeleteNonExistent(t *testing.T) { - tree := New() - n := 100 - perm := rand.Perm(n) - for i := 0; i < n; i++ { - tree.ReplaceOrInsert(Int(perm[i])) - } - if tree.Delete(Int(200)) != nil { - t.Errorf("deleted non-existent item") - } - if tree.Delete(Int(-2)) != nil { - t.Errorf("deleted non-existent item") - } - for i := 0; i < n; i++ { - if u := tree.Delete(Int(i)); u == nil || u.(Int) != Int(i) { - t.Errorf("delete failed") - } - } - if tree.Delete(Int(200)) != nil { - t.Errorf("deleted non-existent item") - } - if tree.Delete(Int(-2)) != nil { - t.Errorf("deleted non-existent item") - } -} - -func TestRandomInsertPartialDeleteOrder(t *testing.T) { - tree := New() - n := 100 - perm := rand.Perm(n) - for i := 0; i < n; i++ { - tree.ReplaceOrInsert(Int(perm[i])) - } - for i := 1; i < n-1; i++ { - tree.Delete(Int(i)) - } - j := 0 - tree.AscendGreaterOrEqual(Int(0), func(item Item) bool { - switch j { - case 0: - if item.(Int) != Int(0) { - t.Errorf("expecting 0") - } - case 1: - if item.(Int) != Int(n-1) { - t.Errorf("expecting %d", n-1) - } - } - j++ - return true - }) -} - -func TestRandomInsertStats(t *testing.T) { - tree := New() - n := 100000 - perm := rand.Perm(n) - for i := 0; i < n; i++ { - tree.ReplaceOrInsert(Int(perm[i])) - } - avg, _ := tree.HeightStats() - expAvg := math.Log2(float64(n)) - 1.5 - if math.Abs(avg-expAvg) >= 2.0 { - t.Errorf("too much deviation from expected average height") - } -} - -func BenchmarkInsert(b *testing.B) { - tree := New() - for i := 0; i < b.N; i++ { - tree.ReplaceOrInsert(Int(b.N - i)) - } -} - -func BenchmarkDelete(b *testing.B) { - b.StopTimer() - tree := New() - for i := 0; i < b.N; i++ { - tree.ReplaceOrInsert(Int(b.N - i)) - } - b.StartTimer() - for i := 0; i < b.N; i++ { - tree.Delete(Int(i)) - } -} - -func BenchmarkDeleteMin(b *testing.B) { - b.StopTimer() - tree := New() - for i := 0; i < b.N; i++ { - tree.ReplaceOrInsert(Int(b.N - i)) - } - b.StartTimer() - for i := 0; i < b.N; i++ { - tree.DeleteMin() - } -} - -func TestInsertNoReplace(t *testing.T) { - tree := New() - n := 1000 - for q := 0; q < 2; q++ { - perm := rand.Perm(n) - for i := 0; i < n; i++ { - tree.InsertNoReplace(Int(perm[i])) - } - } - j := 0 - tree.AscendGreaterOrEqual(Int(0), func(item Item) bool { - if item.(Int) != Int(j/2) { - t.Fatalf("bad order") - } - j++ - return true - }) -} diff --git a/vendor/github.com/peterbourgon/diskv/BUILD b/vendor/github.com/peterbourgon/diskv/BUILD index 2bb0c244dd4d..f69fe4c65f41 100644 --- a/vendor/github.com/peterbourgon/diskv/BUILD +++ b/vendor/github.com/peterbourgon/diskv/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -12,30 +12,6 @@ go_library( deps = ["//vendor/github.com/google/btree:go_default_library"], ) -go_test( - name = "go_default_test", - srcs = [ - "basic_test.go", - "compression_test.go", - "index_test.go", - "issues_test.go", - "speed_test.go", - "stream_test.go", - ], - importpath = "github.com/peterbourgon/diskv", - library = ":go_default_library", -) - -go_test( - name = "go_default_xtest", - srcs = [ - "import_test.go", - "keys_test.go", - ], - importpath = "github.com/peterbourgon/diskv_test", - deps = [":go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/peterbourgon/diskv/basic_test.go b/vendor/github.com/peterbourgon/diskv/basic_test.go deleted file mode 100644 index 7bf7eda05f2b..000000000000 --- a/vendor/github.com/peterbourgon/diskv/basic_test.go +++ /dev/null @@ -1,253 +0,0 @@ -package diskv - -import ( - "bytes" - "testing" - "time" -) - -func cmpBytes(a, b []byte) bool { - if len(a) != len(b) { - return false - } - for i := 0; i < len(a); i++ { - if a[i] != b[i] { - return false - } - } - return true -} - -func (d *Diskv) isCached(key string) bool { - d.mu.RLock() - defer d.mu.RUnlock() - _, ok := d.cache[key] - return ok -} - -func TestWriteReadErase(t *testing.T) { - d := New(Options{ - BasePath: "test-data", - CacheSizeMax: 1024, - }) - defer d.EraseAll() - k, v := "a", []byte{'b'} - if err := d.Write(k, v); err != nil { - t.Fatalf("write: %s", err) - } - if readVal, err := d.Read(k); err != nil { - t.Fatalf("read: %s", err) - } else if bytes.Compare(v, readVal) != 0 { - t.Fatalf("read: expected %s, got %s", v, readVal) - } - if err := d.Erase(k); err != nil { - t.Fatalf("erase: %s", err) - } -} - -func TestWRECache(t *testing.T) { - d := New(Options{ - BasePath: "test-data", - CacheSizeMax: 1024, - }) - defer d.EraseAll() - k, v := "xxx", []byte{' ', ' ', ' '} - if d.isCached(k) { - t.Fatalf("key cached before Write and Read") - } - if err := d.Write(k, v); err != nil { - t.Fatalf("write: %s", err) - } - if d.isCached(k) { - t.Fatalf("key cached before Read") - } - if readVal, err := d.Read(k); err != nil { - t.Fatalf("read: %s", err) - } else if bytes.Compare(v, readVal) != 0 { - t.Fatalf("read: expected %s, got %s", v, readVal) - } - for i := 0; i < 10 && !d.isCached(k); i++ { - time.Sleep(10 * time.Millisecond) - } - if !d.isCached(k) { - t.Fatalf("key not cached after Read") - } - if err := d.Erase(k); err != nil { - t.Fatalf("erase: %s", err) - } - if d.isCached(k) { - t.Fatalf("key cached after Erase") - } -} - -func TestStrings(t *testing.T) { - d := New(Options{ - BasePath: "test-data", - CacheSizeMax: 1024, - }) - defer d.EraseAll() - - keys := map[string]bool{"a": false, "b": false, "c": false, "d": false} - v := []byte{'1'} - for k := range keys { - if err := d.Write(k, v); err != nil { - t.Fatalf("write: %s: %s", k, err) - } - } - - for k := range d.Keys(nil) { - if _, present := keys[k]; present { - t.Logf("got: %s", k) - keys[k] = true - } else { - t.Fatalf("strings() returns unknown key: %s", k) - } - } - - for k, found := range keys { - if !found { - t.Errorf("never got %s", k) - } - } -} - -func TestZeroByteCache(t *testing.T) { - d := New(Options{ - BasePath: "test-data", - CacheSizeMax: 0, - }) - defer d.EraseAll() - - k, v := "a", []byte{'1', '2', '3'} - if err := d.Write(k, v); err != nil { - t.Fatalf("Write: %s", err) - } - - if d.isCached(k) { - t.Fatalf("key cached, expected not-cached") - } - - if _, err := d.Read(k); err != nil { - t.Fatalf("Read: %s", err) - } - - if d.isCached(k) { - t.Fatalf("key cached, expected not-cached") - } -} - -func TestOneByteCache(t *testing.T) { - d := New(Options{ - BasePath: "test-data", - CacheSizeMax: 1, - }) - defer d.EraseAll() - - k1, k2, v1, v2 := "a", "b", []byte{'1'}, []byte{'1', '2'} - if err := d.Write(k1, v1); err != nil { - t.Fatal(err) - } - - if v, err := d.Read(k1); err != nil { - t.Fatal(err) - } else if !cmpBytes(v, v1) { - t.Fatalf("Read: expected %s, got %s", string(v1), string(v)) - } - - for i := 0; i < 10 && !d.isCached(k1); i++ { - time.Sleep(10 * time.Millisecond) - } - if !d.isCached(k1) { - t.Fatalf("expected 1-byte value to be cached, but it wasn't") - } - - if err := d.Write(k2, v2); err != nil { - t.Fatal(err) - } - if _, err := d.Read(k2); err != nil { - t.Fatalf("--> %s", err) - } - - for i := 0; i < 10 && (!d.isCached(k1) || d.isCached(k2)); i++ { - time.Sleep(10 * time.Millisecond) // just wait for lazy-cache - } - if !d.isCached(k1) { - t.Fatalf("1-byte value was uncached for no reason") - } - - if d.isCached(k2) { - t.Fatalf("2-byte value was cached, but cache max size is 1") - } -} - -func TestStaleCache(t *testing.T) { - d := New(Options{ - BasePath: "test-data", - CacheSizeMax: 1, - }) - defer d.EraseAll() - - k, first, second := "a", "first", "second" - if err := d.Write(k, []byte(first)); err != nil { - t.Fatal(err) - } - - v, err := d.Read(k) - if err != nil { - t.Fatal(err) - } - if string(v) != first { - t.Errorf("expected '%s', got '%s'", first, v) - } - - if err := d.Write(k, []byte(second)); err != nil { - t.Fatal(err) - } - - v, err = d.Read(k) - if err != nil { - t.Fatal(err) - } - - if string(v) != second { - t.Errorf("expected '%s', got '%s'", second, v) - } -} - -func TestHas(t *testing.T) { - d := New(Options{ - BasePath: "test-data", - CacheSizeMax: 1024, - }) - defer d.EraseAll() - - for k, v := range map[string]string{ - "a": "1", - "foo": "2", - "012345": "3", - } { - d.Write(k, []byte(v)) - } - - d.Read("foo") // cache one of them - if !d.isCached("foo") { - t.Errorf("'foo' didn't get cached") - } - - for _, tuple := range []struct { - key string - expected bool - }{ - {"a", true}, - {"b", false}, - {"foo", true}, - {"bar", false}, - {"01234", false}, - {"012345", true}, - {"0123456", false}, - } { - if expected, got := tuple.expected, d.Has(tuple.key); expected != got { - t.Errorf("Has(%s): expected %v, got %v", tuple.key, expected, got) - } - } -} diff --git a/vendor/github.com/peterbourgon/diskv/compression_test.go b/vendor/github.com/peterbourgon/diskv/compression_test.go deleted file mode 100644 index 2d614203725f..000000000000 --- a/vendor/github.com/peterbourgon/diskv/compression_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package diskv - -import ( - "compress/flate" - "fmt" - "math/rand" - "os" - "testing" - "time" -) - -func init() { - rand.Seed(time.Now().UnixNano()) -} - -func testCompressionWith(t *testing.T, c Compression, name string) { - d := New(Options{ - BasePath: "compression-test", - CacheSizeMax: 0, - Compression: c, - }) - defer d.EraseAll() - - sz := 4096 - val := make([]byte, sz) - for i := 0; i < sz; i++ { - val[i] = byte('a' + rand.Intn(26)) // {a-z}; should compress some - } - - key := "a" - if err := d.Write(key, val); err != nil { - t.Fatalf("write failed: %s", err) - } - - targetFile := fmt.Sprintf("%s%c%s", d.BasePath, os.PathSeparator, key) - fi, err := os.Stat(targetFile) - if err != nil { - t.Fatalf("%s: %s", targetFile, err) - } - - if fi.Size() >= int64(sz) { - t.Fatalf("%s: size=%d, expected smaller", targetFile, fi.Size()) - } - t.Logf("%s compressed %d to %d", name, sz, fi.Size()) - - readVal, err := d.Read(key) - if len(readVal) != sz { - t.Fatalf("read: expected size=%d, got size=%d", sz, len(readVal)) - } - - for i := 0; i < sz; i++ { - if readVal[i] != val[i] { - t.Fatalf("i=%d: expected %v, got %v", i, val[i], readVal[i]) - } - } -} - -func TestGzipDefault(t *testing.T) { - testCompressionWith(t, NewGzipCompression(), "gzip") -} - -func TestGzipBestCompression(t *testing.T) { - testCompressionWith(t, NewGzipCompressionLevel(flate.BestCompression), "gzip-max") -} - -func TestGzipBestSpeed(t *testing.T) { - testCompressionWith(t, NewGzipCompressionLevel(flate.BestSpeed), "gzip-min") -} - -func TestZlib(t *testing.T) { - testCompressionWith(t, NewZlibCompression(), "zlib") -} diff --git a/vendor/github.com/peterbourgon/diskv/import_test.go b/vendor/github.com/peterbourgon/diskv/import_test.go deleted file mode 100644 index a08ac7c70cb3..000000000000 --- a/vendor/github.com/peterbourgon/diskv/import_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package diskv_test - -import ( - "bytes" - "io/ioutil" - "os" - - "github.com/peterbourgon/diskv" - - "testing" -) - -func TestImportMove(t *testing.T) { - b := []byte(`0123456789`) - f, err := ioutil.TempFile("", "temp-test") - if err != nil { - t.Fatal(err) - } - if _, err := f.Write(b); err != nil { - t.Fatal(err) - } - f.Close() - - d := diskv.New(diskv.Options{ - BasePath: "test-import-move", - }) - defer d.EraseAll() - - key := "key" - - if err := d.Write(key, []byte(`TBD`)); err != nil { - t.Fatal(err) - } - - if err := d.Import(f.Name(), key, true); err != nil { - t.Fatal(err) - } - - if _, err := os.Stat(f.Name()); err == nil || !os.IsNotExist(err) { - t.Errorf("expected temp file to be gone, but err = %v", err) - } - - if !d.Has(key) { - t.Errorf("%q not present", key) - } - - if buf, err := d.Read(key); err != nil || bytes.Compare(b, buf) != 0 { - t.Errorf("want %q, have %q (err = %v)", string(b), string(buf), err) - } -} - -func TestImportCopy(t *testing.T) { - b := []byte(`¡åéîòü!`) - - f, err := ioutil.TempFile("", "temp-test") - if err != nil { - t.Fatal(err) - } - if _, err := f.Write(b); err != nil { - t.Fatal(err) - } - f.Close() - - d := diskv.New(diskv.Options{ - BasePath: "test-import-copy", - }) - defer d.EraseAll() - - if err := d.Import(f.Name(), "key", false); err != nil { - t.Fatal(err) - } - - if _, err := os.Stat(f.Name()); err != nil { - t.Errorf("expected temp file to remain, but got err = %v", err) - } -} diff --git a/vendor/github.com/peterbourgon/diskv/index_test.go b/vendor/github.com/peterbourgon/diskv/index_test.go deleted file mode 100644 index 72f52a9ff92e..000000000000 --- a/vendor/github.com/peterbourgon/diskv/index_test.go +++ /dev/null @@ -1,148 +0,0 @@ -package diskv - -import ( - "bytes" - "reflect" - "testing" - "time" -) - -func strLess(a, b string) bool { return a < b } - -func cmpStrings(a, b []string) bool { - if len(a) != len(b) { - return false - } - for i := 0; i < len(a); i++ { - if a[i] != b[i] { - return false - } - } - return true -} - -func (d *Diskv) isIndexed(key string) bool { - if d.Index == nil { - return false - } - - for _, got := range d.Index.Keys("", 1000) { - if got == key { - return true - } - } - return false -} - -func TestIndexOrder(t *testing.T) { - d := New(Options{ - BasePath: "index-test", - Transform: func(string) []string { return []string{} }, - CacheSizeMax: 1024, - Index: &BTreeIndex{}, - IndexLess: strLess, - }) - defer d.EraseAll() - - v := []byte{'1', '2', '3'} - d.Write("a", v) - if !d.isIndexed("a") { - t.Fatalf("'a' not indexed after write") - } - d.Write("1", v) - d.Write("m", v) - d.Write("-", v) - d.Write("A", v) - - expectedKeys := []string{"-", "1", "A", "a", "m"} - keys := []string{} - for _, key := range d.Index.Keys("", 100) { - keys = append(keys, key) - } - - if !cmpStrings(keys, expectedKeys) { - t.Fatalf("got %s, expected %s", keys, expectedKeys) - } -} - -func TestIndexLoad(t *testing.T) { - d1 := New(Options{ - BasePath: "index-test", - Transform: func(string) []string { return []string{} }, - CacheSizeMax: 1024, - }) - defer d1.EraseAll() - - val := []byte{'1', '2', '3'} - keys := []string{"a", "b", "c", "d", "e", "f", "g"} - for _, key := range keys { - d1.Write(key, val) - } - - d2 := New(Options{ - BasePath: "index-test", - Transform: func(string) []string { return []string{} }, - CacheSizeMax: 1024, - Index: &BTreeIndex{}, - IndexLess: strLess, - }) - defer d2.EraseAll() - - // check d2 has properly loaded existing d1 data - for _, key := range keys { - if !d2.isIndexed(key) { - t.Fatalf("key '%s' not indexed on secondary", key) - } - } - - // cache one - if readValue, err := d2.Read(keys[0]); err != nil { - t.Fatalf("%s", err) - } else if bytes.Compare(val, readValue) != 0 { - t.Fatalf("%s: got %s, expected %s", keys[0], readValue, val) - } - - // make sure it got cached - for i := 0; i < 10 && !d2.isCached(keys[0]); i++ { - time.Sleep(10 * time.Millisecond) - } - if !d2.isCached(keys[0]) { - t.Fatalf("key '%s' not cached", keys[0]) - } - - // kill the disk - d1.EraseAll() - - // cached value should still be there in the second - if readValue, err := d2.Read(keys[0]); err != nil { - t.Fatalf("%s", err) - } else if bytes.Compare(val, readValue) != 0 { - t.Fatalf("%s: got %s, expected %s", keys[0], readValue, val) - } - - // but not in the original - if _, err := d1.Read(keys[0]); err == nil { - t.Fatalf("expected error reading from flushed store") - } -} - -func TestIndexKeysEmptyFrom(t *testing.T) { - d := New(Options{ - BasePath: "index-test", - Transform: func(string) []string { return []string{} }, - CacheSizeMax: 1024, - Index: &BTreeIndex{}, - IndexLess: strLess, - }) - defer d.EraseAll() - - for _, k := range []string{"a", "c", "z", "b", "x", "b", "y"} { - d.Write(k, []byte("1")) - } - - want := []string{"a", "b", "c", "x", "y", "z"} - have := d.Index.Keys("", 99) - if !reflect.DeepEqual(want, have) { - t.Errorf("want %v, have %v", want, have) - } -} diff --git a/vendor/github.com/peterbourgon/diskv/issues_test.go b/vendor/github.com/peterbourgon/diskv/issues_test.go deleted file mode 100644 index 0b0b10908237..000000000000 --- a/vendor/github.com/peterbourgon/diskv/issues_test.go +++ /dev/null @@ -1,121 +0,0 @@ -package diskv - -import ( - "bytes" - "io/ioutil" - "sync" - "testing" - "time" -) - -// ReadStream from cache shouldn't panic on a nil dereference from a nonexistent -// Compression :) -func TestIssue2A(t *testing.T) { - d := New(Options{ - BasePath: "test-issue-2a", - Transform: func(string) []string { return []string{} }, - CacheSizeMax: 1024, - }) - defer d.EraseAll() - - input := "abcdefghijklmnopqrstuvwxy" - key, writeBuf, sync := "a", bytes.NewBufferString(input), false - if err := d.WriteStream(key, writeBuf, sync); err != nil { - t.Fatal(err) - } - - for i := 0; i < 2; i++ { - began := time.Now() - rc, err := d.ReadStream(key, false) - if err != nil { - t.Fatal(err) - } - buf, err := ioutil.ReadAll(rc) - if err != nil { - t.Fatal(err) - } - if !cmpBytes(buf, []byte(input)) { - t.Fatalf("read #%d: '%s' != '%s'", i+1, string(buf), input) - } - rc.Close() - t.Logf("read #%d in %s", i+1, time.Since(began)) - } -} - -// ReadStream on a key that resolves to a directory should return an error. -func TestIssue2B(t *testing.T) { - blockTransform := func(s string) []string { - transformBlockSize := 3 - sliceSize := len(s) / transformBlockSize - pathSlice := make([]string, sliceSize) - for i := 0; i < sliceSize; i++ { - from, to := i*transformBlockSize, (i*transformBlockSize)+transformBlockSize - pathSlice[i] = s[from:to] - } - return pathSlice - } - - d := New(Options{ - BasePath: "test-issue-2b", - Transform: blockTransform, - CacheSizeMax: 0, - }) - defer d.EraseAll() - - v := []byte{'1', '2', '3'} - if err := d.Write("abcabc", v); err != nil { - t.Fatal(err) - } - - _, err := d.ReadStream("abc", false) - if err == nil { - t.Fatal("ReadStream('abc') should return error") - } - t.Logf("ReadStream('abc') returned error: %v", err) -} - -// Ensure ReadStream with direct=true isn't racy. -func TestIssue17(t *testing.T) { - var ( - basePath = "test-data" - ) - - dWrite := New(Options{ - BasePath: basePath, - CacheSizeMax: 0, - }) - defer dWrite.EraseAll() - - dRead := New(Options{ - BasePath: basePath, - CacheSizeMax: 50, - }) - - cases := map[string]string{ - "a": `1234567890`, - "b": `2345678901`, - "c": `3456789012`, - "d": `4567890123`, - "e": `5678901234`, - } - - for k, v := range cases { - if err := dWrite.Write(k, []byte(v)); err != nil { - t.Fatalf("during write: %s", err) - } - dRead.Read(k) // ensure it's added to cache - } - - var wg sync.WaitGroup - start := make(chan struct{}) - for k, v := range cases { - wg.Add(1) - go func(k, v string) { - <-start - dRead.ReadStream(k, true) - wg.Done() - }(k, v) - } - close(start) - wg.Wait() -} diff --git a/vendor/github.com/peterbourgon/diskv/keys_test.go b/vendor/github.com/peterbourgon/diskv/keys_test.go deleted file mode 100644 index 222e1c44414d..000000000000 --- a/vendor/github.com/peterbourgon/diskv/keys_test.go +++ /dev/null @@ -1,231 +0,0 @@ -package diskv_test - -import ( - "reflect" - "runtime" - "strings" - "testing" - - "github.com/peterbourgon/diskv" -) - -var ( - keysTestData = map[string]string{ - "ab01cd01": "When we started building CoreOS", - "ab01cd02": "we looked at all the various components available to us", - "ab01cd03": "re-using the best tools", - "ef01gh04": "and building the ones that did not exist", - "ef02gh05": "We believe strongly in the Unix philosophy", - "xxxxxxxx": "tools should be independently useful", - } - - prefixes = []string{ - "", // all - "a", - "ab", - "ab0", - "ab01", - "ab01cd0", - "ab01cd01", - "ab01cd01x", // none - "b", // none - "b0", // none - "0", // none - "01", // none - "e", - "ef", - "efx", // none - "ef01gh0", - "ef01gh04", - "ef01gh05", - "ef01gh06", // none - } -) - -func TestKeysFlat(t *testing.T) { - transform := func(s string) []string { - if s == "" { - t.Fatalf(`transform should not be called with ""`) - } - return []string{} - } - d := diskv.New(diskv.Options{ - BasePath: "test-data", - Transform: transform, - }) - defer d.EraseAll() - - for k, v := range keysTestData { - d.Write(k, []byte(v)) - } - - checkKeys(t, d.Keys(nil), keysTestData) -} - -func TestKeysNested(t *testing.T) { - d := diskv.New(diskv.Options{ - BasePath: "test-data", - Transform: blockTransform(2), - }) - defer d.EraseAll() - - for k, v := range keysTestData { - d.Write(k, []byte(v)) - } - - checkKeys(t, d.Keys(nil), keysTestData) -} - -func TestKeysPrefixFlat(t *testing.T) { - d := diskv.New(diskv.Options{ - BasePath: "test-data", - }) - defer d.EraseAll() - - for k, v := range keysTestData { - d.Write(k, []byte(v)) - } - - for _, prefix := range prefixes { - checkKeys(t, d.KeysPrefix(prefix, nil), filterPrefix(keysTestData, prefix)) - } -} - -func TestKeysPrefixNested(t *testing.T) { - d := diskv.New(diskv.Options{ - BasePath: "test-data", - Transform: blockTransform(2), - }) - defer d.EraseAll() - - for k, v := range keysTestData { - d.Write(k, []byte(v)) - } - - for _, prefix := range prefixes { - checkKeys(t, d.KeysPrefix(prefix, nil), filterPrefix(keysTestData, prefix)) - } -} - -func TestKeysCancel(t *testing.T) { - d := diskv.New(diskv.Options{ - BasePath: "test-data", - }) - defer d.EraseAll() - - for k, v := range keysTestData { - d.Write(k, []byte(v)) - } - - var ( - cancel = make(chan struct{}) - received = 0 - cancelAfter = len(keysTestData) / 2 - ) - - for key := range d.Keys(cancel) { - received++ - - if received >= cancelAfter { - close(cancel) - runtime.Gosched() // allow walker to detect cancel - } - - t.Logf("received %d: %q", received, key) - } - - if want, have := cancelAfter, received; want != have { - t.Errorf("want %d, have %d") - } -} - -func checkKeys(t *testing.T, c <-chan string, want map[string]string) { - for k := range c { - if _, ok := want[k]; !ok { - t.Errorf("%q yielded but not expected", k) - continue - } - - delete(want, k) - t.Logf("%q yielded OK", k) - } - - if len(want) != 0 { - t.Errorf("%d expected key(s) not yielded: %s", len(want), strings.Join(flattenKeys(want), ", ")) - } -} - -func blockTransform(blockSize int) func(string) []string { - return func(s string) []string { - var ( - sliceSize = len(s) / blockSize - pathSlice = make([]string, sliceSize) - ) - for i := 0; i < sliceSize; i++ { - from, to := i*blockSize, (i*blockSize)+blockSize - pathSlice[i] = s[from:to] - } - return pathSlice - } -} - -func filterPrefix(in map[string]string, prefix string) map[string]string { - out := map[string]string{} - for k, v := range in { - if strings.HasPrefix(k, prefix) { - out[k] = v - } - } - return out -} - -func TestFilterPrefix(t *testing.T) { - input := map[string]string{ - "all": "", - "and": "", - "at": "", - "available": "", - "best": "", - "building": "", - "components": "", - "coreos": "", - "did": "", - "exist": "", - "looked": "", - "not": "", - "ones": "", - "re-using": "", - "started": "", - "that": "", - "the": "", - "to": "", - "tools": "", - "us": "", - "various": "", - "we": "", - "when": "", - } - - for prefix, want := range map[string]map[string]string{ - "a": map[string]string{"all": "", "and": "", "at": "", "available": ""}, - "al": map[string]string{"all": ""}, - "all": map[string]string{"all": ""}, - "alll": map[string]string{}, - "c": map[string]string{"components": "", "coreos": ""}, - "co": map[string]string{"components": "", "coreos": ""}, - "com": map[string]string{"components": ""}, - } { - have := filterPrefix(input, prefix) - if !reflect.DeepEqual(want, have) { - t.Errorf("%q: want %v, have %v", prefix, flattenKeys(want), flattenKeys(have)) - } - } -} - -func flattenKeys(m map[string]string) []string { - a := make([]string, 0, len(m)) - for k := range m { - a = append(a, k) - } - return a -} diff --git a/vendor/github.com/peterbourgon/diskv/speed_test.go b/vendor/github.com/peterbourgon/diskv/speed_test.go deleted file mode 100644 index 67d05ff27e0b..000000000000 --- a/vendor/github.com/peterbourgon/diskv/speed_test.go +++ /dev/null @@ -1,153 +0,0 @@ -package diskv - -import ( - "fmt" - "math/rand" - "testing" -) - -func shuffle(keys []string) { - ints := rand.Perm(len(keys)) - for i := range keys { - keys[i], keys[ints[i]] = keys[ints[i]], keys[i] - } -} - -func genValue(size int) []byte { - v := make([]byte, size) - for i := 0; i < size; i++ { - v[i] = uint8((rand.Int() % 26) + 97) // a-z - } - return v -} - -const ( - keyCount = 1000 -) - -func genKeys() []string { - keys := make([]string, keyCount) - for i := 0; i < keyCount; i++ { - keys[i] = fmt.Sprintf("%d", i) - } - return keys -} - -func (d *Diskv) load(keys []string, val []byte) { - for _, key := range keys { - d.Write(key, val) - } -} - -func benchRead(b *testing.B, size, cachesz int) { - b.StopTimer() - d := New(Options{ - BasePath: "speed-test", - Transform: func(string) []string { return []string{} }, - CacheSizeMax: uint64(cachesz), - }) - defer d.EraseAll() - - keys := genKeys() - value := genValue(size) - d.load(keys, value) - shuffle(keys) - b.SetBytes(int64(size)) - - b.StartTimer() - for i := 0; i < b.N; i++ { - _, _ = d.Read(keys[i%len(keys)]) - } - b.StopTimer() -} - -func benchWrite(b *testing.B, size int, withIndex bool) { - b.StopTimer() - - options := Options{ - BasePath: "speed-test", - Transform: func(string) []string { return []string{} }, - CacheSizeMax: 0, - } - if withIndex { - options.Index = &BTreeIndex{} - options.IndexLess = strLess - } - - d := New(options) - defer d.EraseAll() - keys := genKeys() - value := genValue(size) - shuffle(keys) - b.SetBytes(int64(size)) - - b.StartTimer() - for i := 0; i < b.N; i++ { - d.Write(keys[i%len(keys)], value) - } - b.StopTimer() -} - -func BenchmarkWrite__32B_NoIndex(b *testing.B) { - benchWrite(b, 32, false) -} - -func BenchmarkWrite__1KB_NoIndex(b *testing.B) { - benchWrite(b, 1024, false) -} - -func BenchmarkWrite__4KB_NoIndex(b *testing.B) { - benchWrite(b, 4096, false) -} - -func BenchmarkWrite_10KB_NoIndex(b *testing.B) { - benchWrite(b, 10240, false) -} - -func BenchmarkWrite__32B_WithIndex(b *testing.B) { - benchWrite(b, 32, true) -} - -func BenchmarkWrite__1KB_WithIndex(b *testing.B) { - benchWrite(b, 1024, true) -} - -func BenchmarkWrite__4KB_WithIndex(b *testing.B) { - benchWrite(b, 4096, true) -} - -func BenchmarkWrite_10KB_WithIndex(b *testing.B) { - benchWrite(b, 10240, true) -} - -func BenchmarkRead__32B_NoCache(b *testing.B) { - benchRead(b, 32, 0) -} - -func BenchmarkRead__1KB_NoCache(b *testing.B) { - benchRead(b, 1024, 0) -} - -func BenchmarkRead__4KB_NoCache(b *testing.B) { - benchRead(b, 4096, 0) -} - -func BenchmarkRead_10KB_NoCache(b *testing.B) { - benchRead(b, 10240, 0) -} - -func BenchmarkRead__32B_WithCache(b *testing.B) { - benchRead(b, 32, keyCount*32*2) -} - -func BenchmarkRead__1KB_WithCache(b *testing.B) { - benchRead(b, 1024, keyCount*1024*2) -} - -func BenchmarkRead__4KB_WithCache(b *testing.B) { - benchRead(b, 4096, keyCount*4096*2) -} - -func BenchmarkRead_10KB_WithCache(b *testing.B) { - benchRead(b, 10240, keyCount*4096*2) -} diff --git a/vendor/github.com/peterbourgon/diskv/stream_test.go b/vendor/github.com/peterbourgon/diskv/stream_test.go deleted file mode 100644 index 7991dbff28d7..000000000000 --- a/vendor/github.com/peterbourgon/diskv/stream_test.go +++ /dev/null @@ -1,117 +0,0 @@ -package diskv - -import ( - "bytes" - "io/ioutil" - "testing" -) - -func TestBasicStreamCaching(t *testing.T) { - d := New(Options{ - BasePath: "test-data", - CacheSizeMax: 1024, - }) - defer d.EraseAll() - - input := "a1b2c3" - key, writeBuf, sync := "a", bytes.NewBufferString(input), true - if err := d.WriteStream(key, writeBuf, sync); err != nil { - t.Fatal(err) - } - - if d.isCached(key) { - t.Fatalf("'%s' cached, but shouldn't be (yet)", key) - } - - rc, err := d.ReadStream(key, false) - if err != nil { - t.Fatal(err) - } - - readBuf, err := ioutil.ReadAll(rc) - if err != nil { - t.Fatal(err) - } - - if !cmpBytes(readBuf, []byte(input)) { - t.Fatalf("'%s' != '%s'", string(readBuf), input) - } - - if !d.isCached(key) { - t.Fatalf("'%s' isn't cached, but should be", key) - } -} - -func TestReadStreamDirect(t *testing.T) { - var ( - basePath = "test-data" - ) - dWrite := New(Options{ - BasePath: basePath, - CacheSizeMax: 0, - }) - defer dWrite.EraseAll() - dRead := New(Options{ - BasePath: basePath, - CacheSizeMax: 1024, - }) - - // Write - key, val1, val2 := "a", []byte(`1234567890`), []byte(`aaaaaaaaaa`) - if err := dWrite.Write(key, val1); err != nil { - t.Fatalf("during first write: %s", err) - } - - // First, caching read. - val, err := dRead.Read(key) - if err != nil { - t.Fatalf("during initial read: %s", err) - } - t.Logf("read 1: %s => %s", key, string(val)) - if !cmpBytes(val1, val) { - t.Errorf("expected %q, got %q", string(val1), string(val)) - } - if !dRead.isCached(key) { - t.Errorf("%q should be cached, but isn't", key) - } - - // Write a different value. - if err := dWrite.Write(key, val2); err != nil { - t.Fatalf("during second write: %s", err) - } - - // Second read, should hit cache and get the old value. - val, err = dRead.Read(key) - if err != nil { - t.Fatalf("during second (cache-hit) read: %s", err) - } - t.Logf("read 2: %s => %s", key, string(val)) - if !cmpBytes(val1, val) { - t.Errorf("expected %q, got %q", string(val1), string(val)) - } - - // Third, direct read, should get the updated value. - rc, err := dRead.ReadStream(key, true) - if err != nil { - t.Fatalf("during third (direct) read, ReadStream: %s", err) - } - defer rc.Close() - val, err = ioutil.ReadAll(rc) - if err != nil { - t.Fatalf("during third (direct) read, ReadAll: %s", err) - } - t.Logf("read 3: %s => %s", key, string(val)) - if !cmpBytes(val2, val) { - t.Errorf("expected %q, got %q", string(val1), string(val)) - } - - // Fourth read, should hit cache and get the new value. - val, err = dRead.Read(key) - if err != nil { - t.Fatalf("during fourth (cache-hit) read: %s", err) - } - t.Logf("read 4: %s => %s", key, string(val)) - if !cmpBytes(val2, val) { - t.Errorf("expected %q, got %q", string(val1), string(val)) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/BUILD b/vendor/github.com/prometheus/client_golang/prometheus/BUILD index 93cc06465e37..7f9c65ac9a65 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/BUILD +++ b/vendor/github.com/prometheus/client_golang/prometheus/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -33,47 +33,6 @@ go_library( ], ) -go_test( - name = "go_default_test", - srcs = [ - "benchmark_test.go", - "counter_test.go", - "gauge_test.go", - "go_collector_test.go", - "histogram_test.go", - "http_test.go", - "metric_test.go", - "process_collector_test.go", - "summary_test.go", - "vec_test.go", - ], - importpath = "github.com/prometheus/client_golang/prometheus", - library = ":go_default_library", - deps = [ - "//vendor/github.com/prometheus/client_model/go:go_default_library", - "//vendor/github.com/prometheus/common/expfmt:go_default_library", - "//vendor/github.com/prometheus/procfs:go_default_library", - ], -) - -go_test( - name = "go_default_xtest", - srcs = [ - "example_clustermanager_test.go", - "examples_test.go", - "expvar_collector_test.go", - "registry_test.go", - ], - importpath = "github.com/prometheus/client_golang/prometheus_test", - deps = [ - ":go_default_library", - "//vendor/github.com/golang/protobuf/proto:go_default_library", - "//vendor/github.com/prometheus/client_golang/prometheus/promhttp:go_default_library", - "//vendor/github.com/prometheus/client_model/go:go_default_library", - "//vendor/github.com/prometheus/common/expfmt:go_default_library", - ], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go b/vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go deleted file mode 100644 index a3d86698bfc7..000000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "sync" - "testing" -) - -func BenchmarkCounterWithLabelValues(b *testing.B) { - m := NewCounterVec( - CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Inc() - } -} - -func BenchmarkCounterWithLabelValuesConcurrent(b *testing.B) { - m := NewCounterVec( - CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - wg := sync.WaitGroup{} - for i := 0; i < 10; i++ { - wg.Add(1) - go func() { - for j := 0; j < b.N/10; j++ { - m.WithLabelValues("eins", "zwei", "drei").Inc() - } - wg.Done() - }() - } - wg.Wait() -} - -func BenchmarkCounterWithMappedLabels(b *testing.B) { - m := NewCounterVec( - CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.With(Labels{"two": "zwei", "one": "eins", "three": "drei"}).Inc() - } -} - -func BenchmarkCounterWithPreparedMappedLabels(b *testing.B) { - m := NewCounterVec( - CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - labels := Labels{"two": "zwei", "one": "eins", "three": "drei"} - for i := 0; i < b.N; i++ { - m.With(labels).Inc() - } -} - -func BenchmarkCounterNoLabels(b *testing.B) { - m := NewCounter(CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Inc() - } -} - -func BenchmarkGaugeWithLabelValues(b *testing.B) { - m := NewGaugeVec( - GaugeOpts{ - Name: "benchmark_gauge", - Help: "A gauge to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Set(3.1415) - } -} - -func BenchmarkGaugeNoLabels(b *testing.B) { - m := NewGauge(GaugeOpts{ - Name: "benchmark_gauge", - Help: "A gauge to benchmark it.", - }) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Set(3.1415) - } -} - -func BenchmarkSummaryWithLabelValues(b *testing.B) { - m := NewSummaryVec( - SummaryOpts{ - Name: "benchmark_summary", - Help: "A summary to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Observe(3.1415) - } -} - -func BenchmarkSummaryNoLabels(b *testing.B) { - m := NewSummary(SummaryOpts{ - Name: "benchmark_summary", - Help: "A summary to benchmark it.", - }, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Observe(3.1415) - } -} - -func BenchmarkHistogramWithLabelValues(b *testing.B) { - m := NewHistogramVec( - HistogramOpts{ - Name: "benchmark_histogram", - Help: "A histogram to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Observe(3.1415) - } -} - -func BenchmarkHistogramNoLabels(b *testing.B) { - m := NewHistogram(HistogramOpts{ - Name: "benchmark_histogram", - Help: "A histogram to benchmark it.", - }, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Observe(3.1415) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/counter_test.go b/vendor/github.com/prometheus/client_golang/prometheus/counter_test.go deleted file mode 100644 index 67391a23aa8c..000000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/counter_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "math" - "testing" - - dto "github.com/prometheus/client_model/go" -) - -func TestCounterAdd(t *testing.T) { - counter := NewCounter(CounterOpts{ - Name: "test", - Help: "test help", - ConstLabels: Labels{"a": "1", "b": "2"}, - }).(*counter) - counter.Inc() - if expected, got := 1., math.Float64frombits(counter.valBits); expected != got { - t.Errorf("Expected %f, got %f.", expected, got) - } - counter.Add(42) - if expected, got := 43., math.Float64frombits(counter.valBits); expected != got { - t.Errorf("Expected %f, got %f.", expected, got) - } - - if expected, got := "counter cannot decrease in value", decreaseCounter(counter).Error(); expected != got { - t.Errorf("Expected error %q, got %q.", expected, got) - } - - m := &dto.Metric{} - counter.Write(m) - - if expected, got := `label: label: counter: `, m.String(); expected != got { - t.Errorf("expected %q, got %q", expected, got) - } -} - -func decreaseCounter(c *counter) (err error) { - defer func() { - if e := recover(); e != nil { - err = e.(error) - } - }() - c.Add(-1) - return nil -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go b/vendor/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go deleted file mode 100644 index 260c1b52ded4..000000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus_test - -import "github.com/prometheus/client_golang/prometheus" - -// ClusterManager is an example for a system that might have been built without -// Prometheus in mind. It models a central manager of jobs running in a -// cluster. To turn it into something that collects Prometheus metrics, we -// simply add the two methods required for the Collector interface. -// -// An additional challenge is that multiple instances of the ClusterManager are -// run within the same binary, each in charge of a different zone. We need to -// make use of ConstLabels to be able to register each ClusterManager instance -// with Prometheus. -type ClusterManager struct { - Zone string - OOMCountDesc *prometheus.Desc - RAMUsageDesc *prometheus.Desc - // ... many more fields -} - -// ReallyExpensiveAssessmentOfTheSystemState is a mock for the data gathering a -// real cluster manager would have to do. Since it may actually be really -// expensive, it must only be called once per collection. This implementation, -// obviously, only returns some made-up data. -func (c *ClusterManager) ReallyExpensiveAssessmentOfTheSystemState() ( - oomCountByHost map[string]int, ramUsageByHost map[string]float64, -) { - // Just example fake data. - oomCountByHost = map[string]int{ - "foo.example.org": 42, - "bar.example.org": 2001, - } - ramUsageByHost = map[string]float64{ - "foo.example.org": 6.023e23, - "bar.example.org": 3.14, - } - return -} - -// Describe simply sends the two Descs in the struct to the channel. -func (c *ClusterManager) Describe(ch chan<- *prometheus.Desc) { - ch <- c.OOMCountDesc - ch <- c.RAMUsageDesc -} - -// Collect first triggers the ReallyExpensiveAssessmentOfTheSystemState. Then it -// creates constant metrics for each host on the fly based on the returned data. -// -// Note that Collect could be called concurrently, so we depend on -// ReallyExpensiveAssessmentOfTheSystemState to be concurrency-safe. -func (c *ClusterManager) Collect(ch chan<- prometheus.Metric) { - oomCountByHost, ramUsageByHost := c.ReallyExpensiveAssessmentOfTheSystemState() - for host, oomCount := range oomCountByHost { - ch <- prometheus.MustNewConstMetric( - c.OOMCountDesc, - prometheus.CounterValue, - float64(oomCount), - host, - ) - } - for host, ramUsage := range ramUsageByHost { - ch <- prometheus.MustNewConstMetric( - c.RAMUsageDesc, - prometheus.GaugeValue, - ramUsage, - host, - ) - } -} - -// NewClusterManager creates the two Descs OOMCountDesc and RAMUsageDesc. Note -// that the zone is set as a ConstLabel. (It's different in each instance of the -// ClusterManager, but constant over the lifetime of an instance.) Then there is -// a variable label "host", since we want to partition the collected metrics by -// host. Since all Descs created in this way are consistent across instances, -// with a guaranteed distinction by the "zone" label, we can register different -// ClusterManager instances with the same registry. -func NewClusterManager(zone string) *ClusterManager { - return &ClusterManager{ - Zone: zone, - OOMCountDesc: prometheus.NewDesc( - "clustermanager_oom_crashes_total", - "Number of OOM crashes.", - []string{"host"}, - prometheus.Labels{"zone": zone}, - ), - RAMUsageDesc: prometheus.NewDesc( - "clustermanager_ram_usage_bytes", - "RAM usage as reported to the cluster manager.", - []string{"host"}, - prometheus.Labels{"zone": zone}, - ), - } -} - -func ExampleCollector() { - workerDB := NewClusterManager("db") - workerCA := NewClusterManager("ca") - - // Since we are dealing with custom Collector implementations, it might - // be a good idea to try it out with a pedantic registry. - reg := prometheus.NewPedanticRegistry() - reg.MustRegister(workerDB) - reg.MustRegister(workerCA) -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/examples_test.go b/vendor/github.com/prometheus/client_golang/prometheus/examples_test.go deleted file mode 100644 index f87f21a8f4f3..000000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/examples_test.go +++ /dev/null @@ -1,751 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus_test - -import ( - "bytes" - "fmt" - "math" - "net/http" - "runtime" - "sort" - "strings" - - dto "github.com/prometheus/client_model/go" - "github.com/prometheus/common/expfmt" - - "github.com/golang/protobuf/proto" - - "github.com/prometheus/client_golang/prometheus" -) - -func ExampleGauge() { - opsQueued := prometheus.NewGauge(prometheus.GaugeOpts{ - Namespace: "our_company", - Subsystem: "blob_storage", - Name: "ops_queued", - Help: "Number of blob storage operations waiting to be processed.", - }) - prometheus.MustRegister(opsQueued) - - // 10 operations queued by the goroutine managing incoming requests. - opsQueued.Add(10) - // A worker goroutine has picked up a waiting operation. - opsQueued.Dec() - // And once more... - opsQueued.Dec() -} - -func ExampleGaugeVec() { - opsQueued := prometheus.NewGaugeVec( - prometheus.GaugeOpts{ - Namespace: "our_company", - Subsystem: "blob_storage", - Name: "ops_queued", - Help: "Number of blob storage operations waiting to be processed, partitioned by user and type.", - }, - []string{ - // Which user has requested the operation? - "user", - // Of what type is the operation? - "type", - }, - ) - prometheus.MustRegister(opsQueued) - - // Increase a value using compact (but order-sensitive!) WithLabelValues(). - opsQueued.WithLabelValues("bob", "put").Add(4) - // Increase a value with a map using WithLabels. More verbose, but order - // doesn't matter anymore. - opsQueued.With(prometheus.Labels{"type": "delete", "user": "alice"}).Inc() -} - -func ExampleGaugeFunc() { - if err := prometheus.Register(prometheus.NewGaugeFunc( - prometheus.GaugeOpts{ - Subsystem: "runtime", - Name: "goroutines_count", - Help: "Number of goroutines that currently exist.", - }, - func() float64 { return float64(runtime.NumGoroutine()) }, - )); err == nil { - fmt.Println("GaugeFunc 'goroutines_count' registered.") - } - // Note that the count of goroutines is a gauge (and not a counter) as - // it can go up and down. - - // Output: - // GaugeFunc 'goroutines_count' registered. -} - -func ExampleCounter() { - pushCounter := prometheus.NewCounter(prometheus.CounterOpts{ - Name: "repository_pushes", // Note: No help string... - }) - err := prometheus.Register(pushCounter) // ... so this will return an error. - if err != nil { - fmt.Println("Push counter couldn't be registered, no counting will happen:", err) - return - } - - // Try it once more, this time with a help string. - pushCounter = prometheus.NewCounter(prometheus.CounterOpts{ - Name: "repository_pushes", - Help: "Number of pushes to external repository.", - }) - err = prometheus.Register(pushCounter) - if err != nil { - fmt.Println("Push counter couldn't be registered AGAIN, no counting will happen:", err) - return - } - - pushComplete := make(chan struct{}) - // TODO: Start a goroutine that performs repository pushes and reports - // each completion via the channel. - for _ = range pushComplete { - pushCounter.Inc() - } - // Output: - // Push counter couldn't be registered, no counting will happen: descriptor Desc{fqName: "repository_pushes", help: "", constLabels: {}, variableLabels: []} is invalid: empty help string -} - -func ExampleCounterVec() { - httpReqs := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "http_requests_total", - Help: "How many HTTP requests processed, partitioned by status code and HTTP method.", - }, - []string{"code", "method"}, - ) - prometheus.MustRegister(httpReqs) - - httpReqs.WithLabelValues("404", "POST").Add(42) - - // If you have to access the same set of labels very frequently, it - // might be good to retrieve the metric only once and keep a handle to - // it. But beware of deletion of that metric, see below! - m := httpReqs.WithLabelValues("200", "GET") - for i := 0; i < 1000000; i++ { - m.Inc() - } - // Delete a metric from the vector. If you have previously kept a handle - // to that metric (as above), future updates via that handle will go - // unseen (even if you re-create a metric with the same label set - // later). - httpReqs.DeleteLabelValues("200", "GET") - // Same thing with the more verbose Labels syntax. - httpReqs.Delete(prometheus.Labels{"method": "GET", "code": "200"}) -} - -func ExampleInstrumentHandler() { - // Handle the "/doc" endpoint with the standard http.FileServer handler. - // By wrapping the handler with InstrumentHandler, request count, - // request and response sizes, and request latency are automatically - // exported to Prometheus, partitioned by HTTP status code and method - // and by the handler name (here "fileserver"). - http.Handle("/doc", prometheus.InstrumentHandler( - "fileserver", http.FileServer(http.Dir("/usr/share/doc")), - )) - // The Prometheus handler still has to be registered to handle the - // "/metrics" endpoint. The handler returned by prometheus.Handler() is - // already instrumented - with "prometheus" as the handler name. In this - // example, we want the handler name to be "metrics", so we instrument - // the uninstrumented Prometheus handler ourselves. - http.Handle("/metrics", prometheus.InstrumentHandler( - "metrics", prometheus.UninstrumentedHandler(), - )) -} - -func ExampleLabelPairSorter() { - labelPairs := []*dto.LabelPair{ - &dto.LabelPair{Name: proto.String("status"), Value: proto.String("404")}, - &dto.LabelPair{Name: proto.String("method"), Value: proto.String("get")}, - } - - sort.Sort(prometheus.LabelPairSorter(labelPairs)) - - fmt.Println(labelPairs) - // Output: - // [name:"method" value:"get" name:"status" value:"404" ] -} - -func ExampleRegister() { - // Imagine you have a worker pool and want to count the tasks completed. - taskCounter := prometheus.NewCounter(prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks_total", - Help: "Total number of tasks completed.", - }) - // This will register fine. - if err := prometheus.Register(taskCounter); err != nil { - fmt.Println(err) - } else { - fmt.Println("taskCounter registered.") - } - // Don't forget to tell the HTTP server about the Prometheus handler. - // (In a real program, you still need to start the HTTP server...) - http.Handle("/metrics", prometheus.Handler()) - - // Now you can start workers and give every one of them a pointer to - // taskCounter and let it increment it whenever it completes a task. - taskCounter.Inc() // This has to happen somewhere in the worker code. - - // But wait, you want to see how individual workers perform. So you need - // a vector of counters, with one element for each worker. - taskCounterVec := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks_total", - Help: "Total number of tasks completed.", - }, - []string{"worker_id"}, - ) - - // Registering will fail because we already have a metric of that name. - if err := prometheus.Register(taskCounterVec); err != nil { - fmt.Println("taskCounterVec not registered:", err) - } else { - fmt.Println("taskCounterVec registered.") - } - - // To fix, first unregister the old taskCounter. - if prometheus.Unregister(taskCounter) { - fmt.Println("taskCounter unregistered.") - } - - // Try registering taskCounterVec again. - if err := prometheus.Register(taskCounterVec); err != nil { - fmt.Println("taskCounterVec not registered:", err) - } else { - fmt.Println("taskCounterVec registered.") - } - // Bummer! Still doesn't work. - - // Prometheus will not allow you to ever export metrics with - // inconsistent help strings or label names. After unregistering, the - // unregistered metrics will cease to show up in the /metrics HTTP - // response, but the registry still remembers that those metrics had - // been exported before. For this example, we will now choose a - // different name. (In a real program, you would obviously not export - // the obsolete metric in the first place.) - taskCounterVec = prometheus.NewCounterVec( - prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks_by_id", - Help: "Total number of tasks completed.", - }, - []string{"worker_id"}, - ) - if err := prometheus.Register(taskCounterVec); err != nil { - fmt.Println("taskCounterVec not registered:", err) - } else { - fmt.Println("taskCounterVec registered.") - } - // Finally it worked! - - // The workers have to tell taskCounterVec their id to increment the - // right element in the metric vector. - taskCounterVec.WithLabelValues("42").Inc() // Code from worker 42. - - // Each worker could also keep a reference to their own counter element - // around. Pick the counter at initialization time of the worker. - myCounter := taskCounterVec.WithLabelValues("42") // From worker 42 initialization code. - myCounter.Inc() // Somewhere in the code of that worker. - - // Note that something like WithLabelValues("42", "spurious arg") would - // panic (because you have provided too many label values). If you want - // to get an error instead, use GetMetricWithLabelValues(...) instead. - notMyCounter, err := taskCounterVec.GetMetricWithLabelValues("42", "spurious arg") - if err != nil { - fmt.Println("Worker initialization failed:", err) - } - if notMyCounter == nil { - fmt.Println("notMyCounter is nil.") - } - - // A different (and somewhat tricky) approach is to use - // ConstLabels. ConstLabels are pairs of label names and label values - // that never change. You might ask what those labels are good for (and - // rightfully so - if they never change, they could as well be part of - // the metric name). There are essentially two use-cases: The first is - // if labels are constant throughout the lifetime of a binary execution, - // but they vary over time or between different instances of a running - // binary. The second is what we have here: Each worker creates and - // registers an own Counter instance where the only difference is in the - // value of the ConstLabels. Those Counters can all be registered - // because the different ConstLabel values guarantee that each worker - // will increment a different Counter metric. - counterOpts := prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks", - Help: "Total number of tasks completed.", - ConstLabels: prometheus.Labels{"worker_id": "42"}, - } - taskCounterForWorker42 := prometheus.NewCounter(counterOpts) - if err := prometheus.Register(taskCounterForWorker42); err != nil { - fmt.Println("taskCounterVForWorker42 not registered:", err) - } else { - fmt.Println("taskCounterForWorker42 registered.") - } - // Obviously, in real code, taskCounterForWorker42 would be a member - // variable of a worker struct, and the "42" would be retrieved with a - // GetId() method or something. The Counter would be created and - // registered in the initialization code of the worker. - - // For the creation of the next Counter, we can recycle - // counterOpts. Just change the ConstLabels. - counterOpts.ConstLabels = prometheus.Labels{"worker_id": "2001"} - taskCounterForWorker2001 := prometheus.NewCounter(counterOpts) - if err := prometheus.Register(taskCounterForWorker2001); err != nil { - fmt.Println("taskCounterVForWorker2001 not registered:", err) - } else { - fmt.Println("taskCounterForWorker2001 registered.") - } - - taskCounterForWorker2001.Inc() - taskCounterForWorker42.Inc() - taskCounterForWorker2001.Inc() - - // Yet another approach would be to turn the workers themselves into - // Collectors and register them. See the Collector example for details. - - // Output: - // taskCounter registered. - // taskCounterVec not registered: a previously registered descriptor with the same fully-qualified name as Desc{fqName: "worker_pool_completed_tasks_total", help: "Total number of tasks completed.", constLabels: {}, variableLabels: [worker_id]} has different label names or a different help string - // taskCounter unregistered. - // taskCounterVec not registered: a previously registered descriptor with the same fully-qualified name as Desc{fqName: "worker_pool_completed_tasks_total", help: "Total number of tasks completed.", constLabels: {}, variableLabels: [worker_id]} has different label names or a different help string - // taskCounterVec registered. - // Worker initialization failed: inconsistent label cardinality - // notMyCounter is nil. - // taskCounterForWorker42 registered. - // taskCounterForWorker2001 registered. -} - -func ExampleSummary() { - temps := prometheus.NewSummary(prometheus.SummaryOpts{ - Name: "pond_temperature_celsius", - Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells. - }) - - // Simulate some observations. - for i := 0; i < 1000; i++ { - temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10) - } - - // Just for demonstration, let's check the state of the summary by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - temps.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // summary: < - // sample_count: 1000 - // sample_sum: 29969.50000000001 - // quantile: < - // quantile: 0.5 - // value: 31.1 - // > - // quantile: < - // quantile: 0.9 - // value: 41.3 - // > - // quantile: < - // quantile: 0.99 - // value: 41.9 - // > - // > -} - -func ExampleSummaryVec() { - temps := prometheus.NewSummaryVec( - prometheus.SummaryOpts{ - Name: "pond_temperature_celsius", - Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells. - }, - []string{"species"}, - ) - - // Simulate some observations. - for i := 0; i < 1000; i++ { - temps.WithLabelValues("litoria-caerulea").Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10) - temps.WithLabelValues("lithobates-catesbeianus").Observe(32 + math.Floor(100*math.Cos(float64(i)*0.11))/10) - } - - // Create a Summary without any observations. - temps.WithLabelValues("leiopelma-hochstetteri") - - // Just for demonstration, let's check the state of the summary vector - // by registering it with a custom registry and then let it collect the - // metrics. - reg := prometheus.NewRegistry() - reg.MustRegister(temps) - - metricFamilies, err := reg.Gather() - if err != nil || len(metricFamilies) != 1 { - panic("unexpected behavior of custom test registry") - } - fmt.Println(proto.MarshalTextString(metricFamilies[0])) - - // Output: - // name: "pond_temperature_celsius" - // help: "The temperature of the frog pond." - // type: SUMMARY - // metric: < - // label: < - // name: "species" - // value: "leiopelma-hochstetteri" - // > - // summary: < - // sample_count: 0 - // sample_sum: 0 - // quantile: < - // quantile: 0.5 - // value: nan - // > - // quantile: < - // quantile: 0.9 - // value: nan - // > - // quantile: < - // quantile: 0.99 - // value: nan - // > - // > - // > - // metric: < - // label: < - // name: "species" - // value: "lithobates-catesbeianus" - // > - // summary: < - // sample_count: 1000 - // sample_sum: 31956.100000000017 - // quantile: < - // quantile: 0.5 - // value: 32.4 - // > - // quantile: < - // quantile: 0.9 - // value: 41.4 - // > - // quantile: < - // quantile: 0.99 - // value: 41.9 - // > - // > - // > - // metric: < - // label: < - // name: "species" - // value: "litoria-caerulea" - // > - // summary: < - // sample_count: 1000 - // sample_sum: 29969.50000000001 - // quantile: < - // quantile: 0.5 - // value: 31.1 - // > - // quantile: < - // quantile: 0.9 - // value: 41.3 - // > - // quantile: < - // quantile: 0.99 - // value: 41.9 - // > - // > - // > -} - -func ExampleNewConstSummary() { - desc := prometheus.NewDesc( - "http_request_duration_seconds", - "A summary of the HTTP request durations.", - []string{"code", "method"}, - prometheus.Labels{"owner": "example"}, - ) - - // Create a constant summary from values we got from a 3rd party telemetry system. - s := prometheus.MustNewConstSummary( - desc, - 4711, 403.34, - map[float64]float64{0.5: 42.3, 0.9: 323.3}, - "200", "get", - ) - - // Just for demonstration, let's check the state of the summary by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - s.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // label: < - // name: "code" - // value: "200" - // > - // label: < - // name: "method" - // value: "get" - // > - // label: < - // name: "owner" - // value: "example" - // > - // summary: < - // sample_count: 4711 - // sample_sum: 403.34 - // quantile: < - // quantile: 0.5 - // value: 42.3 - // > - // quantile: < - // quantile: 0.9 - // value: 323.3 - // > - // > -} - -func ExampleHistogram() { - temps := prometheus.NewHistogram(prometheus.HistogramOpts{ - Name: "pond_temperature_celsius", - Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells. - Buckets: prometheus.LinearBuckets(20, 5, 5), // 5 buckets, each 5 centigrade wide. - }) - - // Simulate some observations. - for i := 0; i < 1000; i++ { - temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10) - } - - // Just for demonstration, let's check the state of the histogram by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - temps.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // histogram: < - // sample_count: 1000 - // sample_sum: 29969.50000000001 - // bucket: < - // cumulative_count: 192 - // upper_bound: 20 - // > - // bucket: < - // cumulative_count: 366 - // upper_bound: 25 - // > - // bucket: < - // cumulative_count: 501 - // upper_bound: 30 - // > - // bucket: < - // cumulative_count: 638 - // upper_bound: 35 - // > - // bucket: < - // cumulative_count: 816 - // upper_bound: 40 - // > - // > -} - -func ExampleNewConstHistogram() { - desc := prometheus.NewDesc( - "http_request_duration_seconds", - "A histogram of the HTTP request durations.", - []string{"code", "method"}, - prometheus.Labels{"owner": "example"}, - ) - - // Create a constant histogram from values we got from a 3rd party telemetry system. - h := prometheus.MustNewConstHistogram( - desc, - 4711, 403.34, - map[float64]uint64{25: 121, 50: 2403, 100: 3221, 200: 4233}, - "200", "get", - ) - - // Just for demonstration, let's check the state of the histogram by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - h.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // label: < - // name: "code" - // value: "200" - // > - // label: < - // name: "method" - // value: "get" - // > - // label: < - // name: "owner" - // value: "example" - // > - // histogram: < - // sample_count: 4711 - // sample_sum: 403.34 - // bucket: < - // cumulative_count: 121 - // upper_bound: 25 - // > - // bucket: < - // cumulative_count: 2403 - // upper_bound: 50 - // > - // bucket: < - // cumulative_count: 3221 - // upper_bound: 100 - // > - // bucket: < - // cumulative_count: 4233 - // upper_bound: 200 - // > - // > -} - -func ExampleAlreadyRegisteredError() { - reqCounter := prometheus.NewCounter(prometheus.CounterOpts{ - Name: "requests_total", - Help: "The total number of requests served.", - }) - if err := prometheus.Register(reqCounter); err != nil { - if are, ok := err.(prometheus.AlreadyRegisteredError); ok { - // A counter for that metric has been registered before. - // Use the old counter from now on. - reqCounter = are.ExistingCollector.(prometheus.Counter) - } else { - // Something else went wrong! - panic(err) - } - } -} - -func ExampleGatherers() { - reg := prometheus.NewRegistry() - temp := prometheus.NewGaugeVec( - prometheus.GaugeOpts{ - Name: "temperature_kelvin", - Help: "Temperature in Kelvin.", - }, - []string{"location"}, - ) - reg.MustRegister(temp) - temp.WithLabelValues("outside").Set(273.14) - temp.WithLabelValues("inside").Set(298.44) - - var parser expfmt.TextParser - - text := ` -# TYPE humidity_percent gauge -# HELP humidity_percent Humidity in %. -humidity_percent{location="outside"} 45.4 -humidity_percent{location="inside"} 33.2 -# TYPE temperature_kelvin gauge -# HELP temperature_kelvin Temperature in Kelvin. -temperature_kelvin{location="somewhere else"} 4.5 -` - - parseText := func() ([]*dto.MetricFamily, error) { - parsed, err := parser.TextToMetricFamilies(strings.NewReader(text)) - if err != nil { - return nil, err - } - var result []*dto.MetricFamily - for _, mf := range parsed { - result = append(result, mf) - } - return result, nil - } - - gatherers := prometheus.Gatherers{ - reg, - prometheus.GathererFunc(parseText), - } - - gathering, err := gatherers.Gather() - if err != nil { - fmt.Println(err) - } - - out := &bytes.Buffer{} - for _, mf := range gathering { - if _, err := expfmt.MetricFamilyToText(out, mf); err != nil { - panic(err) - } - } - fmt.Print(out.String()) - fmt.Println("----------") - - // Note how the temperature_kelvin metric family has been merged from - // different sources. Now try - text = ` -# TYPE humidity_percent gauge -# HELP humidity_percent Humidity in %. -humidity_percent{location="outside"} 45.4 -humidity_percent{location="inside"} 33.2 -# TYPE temperature_kelvin gauge -# HELP temperature_kelvin Temperature in Kelvin. -# Duplicate metric: -temperature_kelvin{location="outside"} 265.3 - # Wrong labels: -temperature_kelvin 4.5 -` - - gathering, err = gatherers.Gather() - if err != nil { - fmt.Println(err) - } - // Note that still as many metrics as possible are returned: - out.Reset() - for _, mf := range gathering { - if _, err := expfmt.MetricFamilyToText(out, mf); err != nil { - panic(err) - } - } - fmt.Print(out.String()) - - // Output: - // # HELP humidity_percent Humidity in %. - // # TYPE humidity_percent gauge - // humidity_percent{location="inside"} 33.2 - // humidity_percent{location="outside"} 45.4 - // # HELP temperature_kelvin Temperature in Kelvin. - // # TYPE temperature_kelvin gauge - // temperature_kelvin{location="inside"} 298.44 - // temperature_kelvin{location="outside"} 273.14 - // temperature_kelvin{location="somewhere else"} 4.5 - // ---------- - // 2 error(s) occurred: - // * collected metric temperature_kelvin label: gauge: was collected before with the same name and label values - // * collected metric temperature_kelvin gauge: has label dimensions inconsistent with previously collected metrics in the same metric family - // # HELP humidity_percent Humidity in %. - // # TYPE humidity_percent gauge - // humidity_percent{location="inside"} 33.2 - // humidity_percent{location="outside"} 45.4 - // # HELP temperature_kelvin Temperature in Kelvin. - // # TYPE temperature_kelvin gauge - // temperature_kelvin{location="inside"} 298.44 - // temperature_kelvin{location="outside"} 273.14 -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector_test.go b/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector_test.go deleted file mode 100644 index 5d3128faed68..000000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector_test.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus_test - -import ( - "expvar" - "fmt" - "sort" - "strings" - - dto "github.com/prometheus/client_model/go" - - "github.com/prometheus/client_golang/prometheus" -) - -func ExampleExpvarCollector() { - expvarCollector := prometheus.NewExpvarCollector(map[string]*prometheus.Desc{ - "memstats": prometheus.NewDesc( - "expvar_memstats", - "All numeric memstats as one metric family. Not a good role-model, actually... ;-)", - []string{"type"}, nil, - ), - "lone-int": prometheus.NewDesc( - "expvar_lone_int", - "Just an expvar int as an example.", - nil, nil, - ), - "http-request-map": prometheus.NewDesc( - "expvar_http_request_total", - "How many http requests processed, partitioned by status code and http method.", - []string{"code", "method"}, nil, - ), - }) - prometheus.MustRegister(expvarCollector) - - // The Prometheus part is done here. But to show that this example is - // doing anything, we have to manually export something via expvar. In - // real-life use-cases, some library would already have exported via - // expvar what we want to re-export as Prometheus metrics. - expvar.NewInt("lone-int").Set(42) - expvarMap := expvar.NewMap("http-request-map") - var ( - expvarMap1, expvarMap2 expvar.Map - expvarInt11, expvarInt12, expvarInt21, expvarInt22 expvar.Int - ) - expvarMap1.Init() - expvarMap2.Init() - expvarInt11.Set(3) - expvarInt12.Set(13) - expvarInt21.Set(11) - expvarInt22.Set(212) - expvarMap1.Set("POST", &expvarInt11) - expvarMap1.Set("GET", &expvarInt12) - expvarMap2.Set("POST", &expvarInt21) - expvarMap2.Set("GET", &expvarInt22) - expvarMap.Set("404", &expvarMap1) - expvarMap.Set("200", &expvarMap2) - // Results in the following expvar map: - // "http-request-count": {"200": {"POST": 11, "GET": 212}, "404": {"POST": 3, "GET": 13}} - - // Let's see what the scrape would yield, but exclude the memstats metrics. - metricStrings := []string{} - metric := dto.Metric{} - metricChan := make(chan prometheus.Metric) - go func() { - expvarCollector.Collect(metricChan) - close(metricChan) - }() - for m := range metricChan { - if strings.Index(m.Desc().String(), "expvar_memstats") == -1 { - metric.Reset() - m.Write(&metric) - metricStrings = append(metricStrings, metric.String()) - } - } - sort.Strings(metricStrings) - for _, s := range metricStrings { - fmt.Println(strings.TrimRight(s, " ")) - } - // Output: - // label: label: untyped: - // label: label: untyped: - // label: label: untyped: - // label: label: untyped: - // untyped: -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/gauge_test.go b/vendor/github.com/prometheus/client_golang/prometheus/gauge_test.go deleted file mode 100644 index 48cab463671b..000000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/gauge_test.go +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "math" - "math/rand" - "sync" - "testing" - "testing/quick" - - dto "github.com/prometheus/client_model/go" -) - -func listenGaugeStream(vals, result chan float64, done chan struct{}) { - var sum float64 -outer: - for { - select { - case <-done: - close(vals) - for v := range vals { - sum += v - } - break outer - case v := <-vals: - sum += v - } - } - result <- sum - close(result) -} - -func TestGaugeConcurrency(t *testing.T) { - it := func(n uint32) bool { - mutations := int(n % 10000) - concLevel := int(n%15 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sStream := make(chan float64, mutations*concLevel) - result := make(chan float64) - done := make(chan struct{}) - - go listenGaugeStream(sStream, result, done) - go func() { - end.Wait() - close(done) - }() - - gge := NewGauge(GaugeOpts{ - Name: "test_gauge", - Help: "no help can be found here", - }) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - for j := 0; j < mutations; j++ { - vals[j] = rand.Float64() - 0.5 - } - - go func(vals []float64) { - start.Wait() - for _, v := range vals { - sStream <- v - gge.Add(v) - } - end.Done() - }(vals) - } - start.Done() - - if expected, got := <-result, math.Float64frombits(gge.(*value).valBits); math.Abs(expected-got) > 0.000001 { - t.Fatalf("expected approx. %f, got %f", expected, got) - return false - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Fatal(err) - } -} - -func TestGaugeVecConcurrency(t *testing.T) { - it := func(n uint32) bool { - mutations := int(n % 10000) - concLevel := int(n%15 + 1) - vecLength := int(n%5 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sStreams := make([]chan float64, vecLength) - results := make([]chan float64, vecLength) - done := make(chan struct{}) - - for i := 0; i < vecLength; i++ { - sStreams[i] = make(chan float64, mutations*concLevel) - results[i] = make(chan float64) - go listenGaugeStream(sStreams[i], results[i], done) - } - - go func() { - end.Wait() - close(done) - }() - - gge := NewGaugeVec( - GaugeOpts{ - Name: "test_gauge", - Help: "no help can be found here", - }, - []string{"label"}, - ) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - pick := make([]int, mutations) - for j := 0; j < mutations; j++ { - vals[j] = rand.Float64() - 0.5 - pick[j] = rand.Intn(vecLength) - } - - go func(vals []float64) { - start.Wait() - for i, v := range vals { - sStreams[pick[i]] <- v - gge.WithLabelValues(string('A' + pick[i])).Add(v) - } - end.Done() - }(vals) - } - start.Done() - - for i := range sStreams { - if expected, got := <-results[i], math.Float64frombits(gge.WithLabelValues(string('A'+i)).(*value).valBits); math.Abs(expected-got) > 0.000001 { - t.Fatalf("expected approx. %f, got %f", expected, got) - return false - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Fatal(err) - } -} - -func TestGaugeFunc(t *testing.T) { - gf := NewGaugeFunc( - GaugeOpts{ - Name: "test_name", - Help: "test help", - ConstLabels: Labels{"a": "1", "b": "2"}, - }, - func() float64 { return 3.1415 }, - ) - - if expected, got := `Desc{fqName: "test_name", help: "test help", constLabels: {a="1",b="2"}, variableLabels: []}`, gf.Desc().String(); expected != got { - t.Errorf("expected %q, got %q", expected, got) - } - - m := &dto.Metric{} - gf.Write(m) - - if expected, got := `label: label: gauge: `, m.String(); expected != got { - t.Errorf("expected %q, got %q", expected, got) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go b/vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go deleted file mode 100644 index 9a8858cbd2b8..000000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go +++ /dev/null @@ -1,123 +0,0 @@ -package prometheus - -import ( - "runtime" - "testing" - "time" - - dto "github.com/prometheus/client_model/go" -) - -func TestGoCollector(t *testing.T) { - var ( - c = NewGoCollector() - ch = make(chan Metric) - waitc = make(chan struct{}) - closec = make(chan struct{}) - old = -1 - ) - defer close(closec) - - go func() { - c.Collect(ch) - go func(c <-chan struct{}) { - <-c - }(closec) - <-waitc - c.Collect(ch) - }() - - for { - select { - case metric := <-ch: - switch m := metric.(type) { - // Attention, this also catches Counter... - case Gauge: - pb := &dto.Metric{} - m.Write(pb) - if pb.GetGauge() == nil { - continue - } - - if old == -1 { - old = int(pb.GetGauge().GetValue()) - close(waitc) - continue - } - - if diff := int(pb.GetGauge().GetValue()) - old; diff != 1 { - // TODO: This is flaky in highly concurrent situations. - t.Errorf("want 1 new goroutine, got %d", diff) - } - - // GoCollector performs two sends per call. - // On line 27 we need to receive the second send - // to shut down cleanly. - <-ch - return - } - case <-time.After(1 * time.Second): - t.Fatalf("expected collect timed out") - } - } -} - -func TestGCCollector(t *testing.T) { - var ( - c = NewGoCollector() - ch = make(chan Metric) - waitc = make(chan struct{}) - closec = make(chan struct{}) - oldGC uint64 - oldPause float64 - ) - defer close(closec) - - go func() { - c.Collect(ch) - // force GC - runtime.GC() - <-waitc - c.Collect(ch) - }() - - first := true - for { - select { - case metric := <-ch: - switch m := metric.(type) { - case *constSummary, *value: - pb := &dto.Metric{} - m.Write(pb) - if pb.GetSummary() == nil { - continue - } - - if len(pb.GetSummary().Quantile) != 5 { - t.Errorf("expected 4 buckets, got %d", len(pb.GetSummary().Quantile)) - } - for idx, want := range []float64{0.0, 0.25, 0.5, 0.75, 1.0} { - if *pb.GetSummary().Quantile[idx].Quantile != want { - t.Errorf("bucket #%d is off, got %f, want %f", idx, *pb.GetSummary().Quantile[idx].Quantile, want) - } - } - if first { - first = false - oldGC = *pb.GetSummary().SampleCount - oldPause = *pb.GetSummary().SampleSum - close(waitc) - continue - } - if diff := *pb.GetSummary().SampleCount - oldGC; diff != 1 { - t.Errorf("want 1 new garbage collection run, got %d", diff) - } - if diff := *pb.GetSummary().SampleSum - oldPause; diff <= 0 { - t.Errorf("want moar pause, got %f", diff) - } - return - } - case <-time.After(1 * time.Second): - t.Fatalf("expected collect timed out") - } - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go b/vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go deleted file mode 100644 index d1242e08d6ae..000000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go +++ /dev/null @@ -1,326 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "math" - "math/rand" - "reflect" - "sort" - "sync" - "testing" - "testing/quick" - - dto "github.com/prometheus/client_model/go" -) - -func benchmarkHistogramObserve(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewHistogram(HistogramOpts{}) - - for i := 0; i < w; i++ { - go func() { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Observe(float64(i)) - } - - wg.Done() - }() - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkHistogramObserve1(b *testing.B) { - benchmarkHistogramObserve(1, b) -} - -func BenchmarkHistogramObserve2(b *testing.B) { - benchmarkHistogramObserve(2, b) -} - -func BenchmarkHistogramObserve4(b *testing.B) { - benchmarkHistogramObserve(4, b) -} - -func BenchmarkHistogramObserve8(b *testing.B) { - benchmarkHistogramObserve(8, b) -} - -func benchmarkHistogramWrite(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewHistogram(HistogramOpts{}) - - for i := 0; i < 1000000; i++ { - s.Observe(float64(i)) - } - - for j := 0; j < w; j++ { - outs := make([]dto.Metric, b.N) - - go func(o []dto.Metric) { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Write(&o[i]) - } - - wg.Done() - }(outs) - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkHistogramWrite1(b *testing.B) { - benchmarkHistogramWrite(1, b) -} - -func BenchmarkHistogramWrite2(b *testing.B) { - benchmarkHistogramWrite(2, b) -} - -func BenchmarkHistogramWrite4(b *testing.B) { - benchmarkHistogramWrite(4, b) -} - -func BenchmarkHistogramWrite8(b *testing.B) { - benchmarkHistogramWrite(8, b) -} - -// Intentionally adding +Inf here to test if that case is handled correctly. -// Also, getCumulativeCounts depends on it. -var testBuckets = []float64{-2, -1, -0.5, 0, 0.5, 1, 2, math.Inf(+1)} - -func TestHistogramConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%5 + 1) - total := mutations * concLevel - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sum := NewHistogram(HistogramOpts{ - Name: "test_histogram", - Help: "helpless", - Buckets: testBuckets, - }) - - allVars := make([]float64, total) - var sampleSum float64 - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - allVars[i*mutations+j] = v - sampleSum += v - } - - go func(vals []float64) { - start.Wait() - for _, v := range vals { - sum.Observe(v) - } - end.Done() - }(vals) - } - sort.Float64s(allVars) - start.Done() - end.Wait() - - m := &dto.Metric{} - sum.Write(m) - if got, want := int(*m.Histogram.SampleCount), total; got != want { - t.Errorf("got sample count %d, want %d", got, want) - } - if got, want := *m.Histogram.SampleSum, sampleSum; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f, want %f", got, want) - } - - wantCounts := getCumulativeCounts(allVars) - - if got, want := len(m.Histogram.Bucket), len(testBuckets)-1; got != want { - t.Errorf("got %d buckets in protobuf, want %d", got, want) - } - for i, wantBound := range testBuckets { - if i == len(testBuckets)-1 { - break // No +Inf bucket in protobuf. - } - if gotBound := *m.Histogram.Bucket[i].UpperBound; gotBound != wantBound { - t.Errorf("got bound %f, want %f", gotBound, wantBound) - } - if gotCount, wantCount := *m.Histogram.Bucket[i].CumulativeCount, wantCounts[i]; gotCount != wantCount { - t.Errorf("got count %d, want %d", gotCount, wantCount) - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func TestHistogramVecConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - objectives := make([]float64, 0, len(DefObjectives)) - for qu := range DefObjectives { - - objectives = append(objectives, qu) - } - sort.Float64s(objectives) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%7 + 1) - vecLength := int(n%3 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - his := NewHistogramVec( - HistogramOpts{ - Name: "test_histogram", - Help: "helpless", - Buckets: []float64{-2, -1, -0.5, 0, 0.5, 1, 2, math.Inf(+1)}, - }, - []string{"label"}, - ) - - allVars := make([][]float64, vecLength) - sampleSums := make([]float64, vecLength) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - picks := make([]int, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - pick := rand.Intn(vecLength) - picks[j] = pick - allVars[pick] = append(allVars[pick], v) - sampleSums[pick] += v - } - - go func(vals []float64) { - start.Wait() - for i, v := range vals { - his.WithLabelValues(string('A' + picks[i])).Observe(v) - } - end.Done() - }(vals) - } - for _, vars := range allVars { - sort.Float64s(vars) - } - start.Done() - end.Wait() - - for i := 0; i < vecLength; i++ { - m := &dto.Metric{} - s := his.WithLabelValues(string('A' + i)) - s.Write(m) - - if got, want := len(m.Histogram.Bucket), len(testBuckets)-1; got != want { - t.Errorf("got %d buckets in protobuf, want %d", got, want) - } - if got, want := int(*m.Histogram.SampleCount), len(allVars[i]); got != want { - t.Errorf("got sample count %d, want %d", got, want) - } - if got, want := *m.Histogram.SampleSum, sampleSums[i]; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f, want %f", got, want) - } - - wantCounts := getCumulativeCounts(allVars[i]) - - for j, wantBound := range testBuckets { - if j == len(testBuckets)-1 { - break // No +Inf bucket in protobuf. - } - if gotBound := *m.Histogram.Bucket[j].UpperBound; gotBound != wantBound { - t.Errorf("got bound %f, want %f", gotBound, wantBound) - } - if gotCount, wantCount := *m.Histogram.Bucket[j].CumulativeCount, wantCounts[j]; gotCount != wantCount { - t.Errorf("got count %d, want %d", gotCount, wantCount) - } - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func getCumulativeCounts(vars []float64) []uint64 { - counts := make([]uint64, len(testBuckets)) - for _, v := range vars { - for i := len(testBuckets) - 1; i >= 0; i-- { - if v > testBuckets[i] { - break - } - counts[i]++ - } - } - return counts -} - -func TestBuckets(t *testing.T) { - got := LinearBuckets(-15, 5, 6) - want := []float64{-15, -10, -5, 0, 5, 10} - if !reflect.DeepEqual(got, want) { - t.Errorf("linear buckets: got %v, want %v", got, want) - } - - got = ExponentialBuckets(100, 1.2, 3) - want = []float64{100, 120, 144} - if !reflect.DeepEqual(got, want) { - t.Errorf("linear buckets: got %v, want %v", got, want) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/http_test.go b/vendor/github.com/prometheus/client_golang/prometheus/http_test.go deleted file mode 100644 index ffe0418cf879..000000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/http_test.go +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "net/http" - "net/http/httptest" - "testing" - "time" - - dto "github.com/prometheus/client_model/go" -) - -type respBody string - -func (b respBody) ServeHTTP(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusTeapot) - w.Write([]byte(b)) -} - -func TestInstrumentHandler(t *testing.T) { - defer func(n nower) { - now = n.(nower) - }(now) - - instant := time.Now() - end := instant.Add(30 * time.Second) - now = nowSeries(instant, end) - respBody := respBody("Howdy there!") - - hndlr := InstrumentHandler("test-handler", respBody) - - opts := SummaryOpts{ - Subsystem: "http", - ConstLabels: Labels{"handler": "test-handler"}, - } - - reqCnt := MustRegisterOrGet(NewCounterVec( - CounterOpts{ - Namespace: opts.Namespace, - Subsystem: opts.Subsystem, - Name: "requests_total", - Help: "Total number of HTTP requests made.", - ConstLabels: opts.ConstLabels, - }, - instLabels, - )).(*CounterVec) - - opts.Name = "request_duration_microseconds" - opts.Help = "The HTTP request latencies in microseconds." - reqDur := MustRegisterOrGet(NewSummary(opts)).(Summary) - - opts.Name = "request_size_bytes" - opts.Help = "The HTTP request sizes in bytes." - MustRegisterOrGet(NewSummary(opts)) - - opts.Name = "response_size_bytes" - opts.Help = "The HTTP response sizes in bytes." - MustRegisterOrGet(NewSummary(opts)) - - reqCnt.Reset() - - resp := httptest.NewRecorder() - req := &http.Request{ - Method: "GET", - } - - hndlr.ServeHTTP(resp, req) - - if resp.Code != http.StatusTeapot { - t.Fatalf("expected status %d, got %d", http.StatusTeapot, resp.Code) - } - if string(resp.Body.Bytes()) != "Howdy there!" { - t.Fatalf("expected body %s, got %s", "Howdy there!", string(resp.Body.Bytes())) - } - - out := &dto.Metric{} - reqDur.Write(out) - if want, got := "test-handler", out.Label[0].GetValue(); want != got { - t.Errorf("want label value %q in reqDur, got %q", want, got) - } - if want, got := uint64(1), out.Summary.GetSampleCount(); want != got { - t.Errorf("want sample count %d in reqDur, got %d", want, got) - } - - out.Reset() - if want, got := 1, len(reqCnt.children); want != got { - t.Errorf("want %d children in reqCnt, got %d", want, got) - } - cnt, err := reqCnt.GetMetricWithLabelValues("get", "418") - if err != nil { - t.Fatal(err) - } - cnt.Write(out) - if want, got := "418", out.Label[0].GetValue(); want != got { - t.Errorf("want label value %q in reqCnt, got %q", want, got) - } - if want, got := "test-handler", out.Label[1].GetValue(); want != got { - t.Errorf("want label value %q in reqCnt, got %q", want, got) - } - if want, got := "get", out.Label[2].GetValue(); want != got { - t.Errorf("want label value %q in reqCnt, got %q", want, got) - } - if out.Counter == nil { - t.Fatal("expected non-nil counter in reqCnt") - } - if want, got := 1., out.Counter.GetValue(); want != got { - t.Errorf("want reqCnt of %f, got %f", want, got) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/metric_test.go b/vendor/github.com/prometheus/client_golang/prometheus/metric_test.go deleted file mode 100644 index 7145f5e53c35..000000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/metric_test.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import "testing" - -func TestBuildFQName(t *testing.T) { - scenarios := []struct{ namespace, subsystem, name, result string }{ - {"a", "b", "c", "a_b_c"}, - {"", "b", "c", "b_c"}, - {"a", "", "c", "a_c"}, - {"", "", "c", "c"}, - {"a", "b", "", ""}, - {"a", "", "", ""}, - {"", "b", "", ""}, - {" ", "", "", ""}, - } - - for i, s := range scenarios { - if want, got := s.result, BuildFQName(s.namespace, s.subsystem, s.name); want != got { - t.Errorf("%d. want %s, got %s", i, want, got) - } - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go deleted file mode 100644 index d3362dae72e5..000000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package prometheus - -import ( - "bytes" - "os" - "regexp" - "testing" - - "github.com/prometheus/common/expfmt" - "github.com/prometheus/procfs" -) - -func TestProcessCollector(t *testing.T) { - if _, err := procfs.Self(); err != nil { - t.Skipf("skipping TestProcessCollector, procfs not available: %s", err) - } - - registry := NewRegistry() - if err := registry.Register(NewProcessCollector(os.Getpid(), "")); err != nil { - t.Fatal(err) - } - if err := registry.Register(NewProcessCollectorPIDFn( - func() (int, error) { return os.Getpid(), nil }, "foobar"), - ); err != nil { - t.Fatal(err) - } - - mfs, err := registry.Gather() - if err != nil { - t.Fatal(err) - } - - var buf bytes.Buffer - for _, mf := range mfs { - if _, err := expfmt.MetricFamilyToText(&buf, mf); err != nil { - t.Fatal(err) - } - } - - for _, re := range []*regexp.Regexp{ - regexp.MustCompile("process_cpu_seconds_total [0-9]"), - regexp.MustCompile("process_max_fds [1-9]"), - regexp.MustCompile("process_open_fds [1-9]"), - regexp.MustCompile("process_virtual_memory_bytes [1-9]"), - regexp.MustCompile("process_resident_memory_bytes [1-9]"), - regexp.MustCompile("process_start_time_seconds [0-9.]{10,}"), - regexp.MustCompile("foobar_process_cpu_seconds_total [0-9]"), - regexp.MustCompile("foobar_process_max_fds [1-9]"), - regexp.MustCompile("foobar_process_open_fds [1-9]"), - regexp.MustCompile("foobar_process_virtual_memory_bytes [1-9]"), - regexp.MustCompile("foobar_process_resident_memory_bytes [1-9]"), - regexp.MustCompile("foobar_process_start_time_seconds [0-9.]{10,}"), - } { - if !re.Match(buf.Bytes()) { - t.Errorf("want body to match %s\n%s", re, buf.String()) - } - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/BUILD b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/BUILD index 324359c01976..e0ff3789eecb 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/BUILD +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -11,14 +11,6 @@ go_library( ], ) -go_test( - name = "go_default_test", - srcs = ["http_test.go"], - importpath = "github.com/prometheus/client_golang/prometheus/promhttp", - library = ":go_default_library", - deps = ["//vendor/github.com/prometheus/client_golang/prometheus:go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http_test.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http_test.go deleted file mode 100644 index d4a7d4a7b57f..000000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http_test.go +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2016 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Copyright (c) 2013, The Prometheus Authors -// All rights reserved. -// -// Use of this source code is governed by a BSD-style license that can be found -// in the LICENSE file. - -package promhttp - -import ( - "bytes" - "errors" - "log" - "net/http" - "net/http/httptest" - "testing" - - "github.com/prometheus/client_golang/prometheus" -) - -type errorCollector struct{} - -func (e errorCollector) Describe(ch chan<- *prometheus.Desc) { - ch <- prometheus.NewDesc("invalid_metric", "not helpful", nil, nil) -} - -func (e errorCollector) Collect(ch chan<- prometheus.Metric) { - ch <- prometheus.NewInvalidMetric( - prometheus.NewDesc("invalid_metric", "not helpful", nil, nil), - errors.New("collect error"), - ) -} - -func TestHandlerErrorHandling(t *testing.T) { - - // Create a registry that collects a MetricFamily with two elements, - // another with one, and reports an error. - reg := prometheus.NewRegistry() - - cnt := prometheus.NewCounter(prometheus.CounterOpts{ - Name: "the_count", - Help: "Ah-ah-ah! Thunder and lightning!", - }) - reg.MustRegister(cnt) - - cntVec := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "name", - Help: "docstring", - ConstLabels: prometheus.Labels{"constname": "constvalue"}, - }, - []string{"labelname"}, - ) - cntVec.WithLabelValues("val1").Inc() - cntVec.WithLabelValues("val2").Inc() - reg.MustRegister(cntVec) - - reg.MustRegister(errorCollector{}) - - logBuf := &bytes.Buffer{} - logger := log.New(logBuf, "", 0) - - writer := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/", nil) - request.Header.Add("Accept", "test/plain") - - errorHandler := HandlerFor(reg, HandlerOpts{ - ErrorLog: logger, - ErrorHandling: HTTPErrorOnError, - }) - continueHandler := HandlerFor(reg, HandlerOpts{ - ErrorLog: logger, - ErrorHandling: ContinueOnError, - }) - panicHandler := HandlerFor(reg, HandlerOpts{ - ErrorLog: logger, - ErrorHandling: PanicOnError, - }) - wantMsg := `error gathering metrics: error collecting metric Desc{fqName: "invalid_metric", help: "not helpful", constLabels: {}, variableLabels: []}: collect error -` - wantErrorBody := `An error has occurred during metrics gathering: - -error collecting metric Desc{fqName: "invalid_metric", help: "not helpful", constLabels: {}, variableLabels: []}: collect error -` - wantOKBody := `# HELP name docstring -# TYPE name counter -name{constname="constvalue",labelname="val1"} 1 -name{constname="constvalue",labelname="val2"} 1 -# HELP the_count Ah-ah-ah! Thunder and lightning! -# TYPE the_count counter -the_count 0 -` - - errorHandler.ServeHTTP(writer, request) - if got, want := writer.Code, http.StatusInternalServerError; got != want { - t.Errorf("got HTTP status code %d, want %d", got, want) - } - if got := logBuf.String(); got != wantMsg { - t.Errorf("got log message:\n%s\nwant log mesage:\n%s\n", got, wantMsg) - } - if got := writer.Body.String(); got != wantErrorBody { - t.Errorf("got body:\n%s\nwant body:\n%s\n", got, wantErrorBody) - } - logBuf.Reset() - writer.Body.Reset() - writer.Code = http.StatusOK - - continueHandler.ServeHTTP(writer, request) - if got, want := writer.Code, http.StatusOK; got != want { - t.Errorf("got HTTP status code %d, want %d", got, want) - } - if got := logBuf.String(); got != wantMsg { - t.Errorf("got log message %q, want %q", got, wantMsg) - } - if got := writer.Body.String(); got != wantOKBody { - t.Errorf("got body %q, want %q", got, wantOKBody) - } - - defer func() { - if err := recover(); err == nil { - t.Error("expected panic from panicHandler") - } - }() - panicHandler.ServeHTTP(writer, request) -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/push/BUILD b/vendor/github.com/prometheus/client_golang/prometheus/push/BUILD index 71bbfbb9463f..5f7cceab96e1 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/push/BUILD +++ b/vendor/github.com/prometheus/client_golang/prometheus/push/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -12,27 +12,6 @@ go_library( ], ) -go_test( - name = "go_default_test", - srcs = ["push_test.go"], - importpath = "github.com/prometheus/client_golang/prometheus/push", - library = ":go_default_library", - deps = [ - "//vendor/github.com/prometheus/client_golang/prometheus:go_default_library", - "//vendor/github.com/prometheus/common/expfmt:go_default_library", - ], -) - -go_test( - name = "go_default_xtest", - srcs = ["examples_test.go"], - importpath = "github.com/prometheus/client_golang/prometheus/push_test", - deps = [ - ":go_default_library", - "//vendor/github.com/prometheus/client_golang/prometheus:go_default_library", - ], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/prometheus/client_golang/prometheus/push/examples_test.go b/vendor/github.com/prometheus/client_golang/prometheus/push/examples_test.go deleted file mode 100644 index 7f17ca29137a..000000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/push/examples_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2016 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package push_test - -import ( - "fmt" - "time" - - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/push" -) - -func ExampleCollectors() { - completionTime := prometheus.NewGauge(prometheus.GaugeOpts{ - Name: "db_backup_last_completion_timestamp_seconds", - Help: "The timestamp of the last succesful completion of a DB backup.", - }) - completionTime.Set(float64(time.Now().Unix())) - if err := push.Collectors( - "db_backup", push.HostnameGroupingKey(), - "http://pushgateway:9091", - completionTime, - ); err != nil { - fmt.Println("Could not push completion time to Pushgateway:", err) - } -} - -func ExampleRegistry() { - registry := prometheus.NewRegistry() - - completionTime := prometheus.NewGauge(prometheus.GaugeOpts{ - Name: "db_backup_last_completion_timestamp_seconds", - Help: "The timestamp of the last succesful completion of a DB backup.", - }) - registry.MustRegister(completionTime) - - completionTime.Set(float64(time.Now().Unix())) - if err := push.FromGatherer( - "db_backup", push.HostnameGroupingKey(), - "http://pushgateway:9091", - registry, - ); err != nil { - fmt.Println("Could not push completion time to Pushgateway:", err) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/push/push_test.go b/vendor/github.com/prometheus/client_golang/prometheus/push/push_test.go deleted file mode 100644 index 28ed9b74b69a..000000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/push/push_test.go +++ /dev/null @@ -1,176 +0,0 @@ -// Copyright 2016 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Copyright (c) 2013, The Prometheus Authors -// All rights reserved. -// -// Use of this source code is governed by a BSD-style license that can be found -// in the LICENSE file. - -package push - -import ( - "bytes" - "io/ioutil" - "net/http" - "net/http/httptest" - "os" - "testing" - - "github.com/prometheus/common/expfmt" - - "github.com/prometheus/client_golang/prometheus" -) - -func TestPush(t *testing.T) { - - var ( - lastMethod string - lastBody []byte - lastPath string - ) - - host, err := os.Hostname() - if err != nil { - t.Error(err) - } - - // Fake a Pushgateway that always responds with 202. - pgwOK := httptest.NewServer( - http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - lastMethod = r.Method - var err error - lastBody, err = ioutil.ReadAll(r.Body) - if err != nil { - t.Fatal(err) - } - lastPath = r.URL.EscapedPath() - w.Header().Set("Content-Type", `text/plain; charset=utf-8`) - w.WriteHeader(http.StatusAccepted) - }), - ) - defer pgwOK.Close() - - // Fake a Pushgateway that always responds with 500. - pgwErr := httptest.NewServer( - http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - http.Error(w, "fake error", http.StatusInternalServerError) - }), - ) - defer pgwErr.Close() - - metric1 := prometheus.NewCounter(prometheus.CounterOpts{ - Name: "testname1", - Help: "testhelp1", - }) - metric2 := prometheus.NewGauge(prometheus.GaugeOpts{ - Name: "testname2", - Help: "testhelp2", - ConstLabels: prometheus.Labels{"foo": "bar", "dings": "bums"}, - }) - - reg := prometheus.NewRegistry() - reg.MustRegister(metric1) - reg.MustRegister(metric2) - - mfs, err := reg.Gather() - if err != nil { - t.Fatal(err) - } - - buf := &bytes.Buffer{} - enc := expfmt.NewEncoder(buf, expfmt.FmtProtoDelim) - - for _, mf := range mfs { - if err := enc.Encode(mf); err != nil { - t.Fatal(err) - } - } - wantBody := buf.Bytes() - - // PushCollectors, all good. - if err := Collectors("testjob", HostnameGroupingKey(), pgwOK.URL, metric1, metric2); err != nil { - t.Fatal(err) - } - if lastMethod != "PUT" { - t.Error("want method PUT for PushCollectors, got", lastMethod) - } - if bytes.Compare(lastBody, wantBody) != 0 { - t.Errorf("got body %v, want %v", lastBody, wantBody) - } - if lastPath != "/metrics/job/testjob/instance/"+host { - t.Error("unexpected path:", lastPath) - } - - // PushAddCollectors, with nil grouping, all good. - if err := AddCollectors("testjob", nil, pgwOK.URL, metric1, metric2); err != nil { - t.Fatal(err) - } - if lastMethod != "POST" { - t.Error("want method POST for PushAddCollectors, got", lastMethod) - } - if bytes.Compare(lastBody, wantBody) != 0 { - t.Errorf("got body %v, want %v", lastBody, wantBody) - } - if lastPath != "/metrics/job/testjob" { - t.Error("unexpected path:", lastPath) - } - - // PushCollectors with a broken PGW. - if err := Collectors("testjob", nil, pgwErr.URL, metric1, metric2); err == nil { - t.Error("push to broken Pushgateway succeeded") - } else { - if got, want := err.Error(), "unexpected status code 500 while pushing to "+pgwErr.URL+"/metrics/job/testjob: fake error\n"; got != want { - t.Errorf("got error %q, want %q", got, want) - } - } - - // PushCollectors with invalid grouping or job. - if err := Collectors("testjob", map[string]string{"foo": "bums"}, pgwErr.URL, metric1, metric2); err == nil { - t.Error("push with grouping contained in metrics succeeded") - } - if err := Collectors("test/job", nil, pgwErr.URL, metric1, metric2); err == nil { - t.Error("push with invalid job value succeeded") - } - if err := Collectors("testjob", map[string]string{"foo/bar": "bums"}, pgwErr.URL, metric1, metric2); err == nil { - t.Error("push with invalid grouping succeeded") - } - if err := Collectors("testjob", map[string]string{"foo-bar": "bums"}, pgwErr.URL, metric1, metric2); err == nil { - t.Error("push with invalid grouping succeeded") - } - - // Push registry, all good. - if err := FromGatherer("testjob", HostnameGroupingKey(), pgwOK.URL, reg); err != nil { - t.Fatal(err) - } - if lastMethod != "PUT" { - t.Error("want method PUT for Push, got", lastMethod) - } - if bytes.Compare(lastBody, wantBody) != 0 { - t.Errorf("got body %v, want %v", lastBody, wantBody) - } - - // PushAdd registry, all good. - if err := AddFromGatherer("testjob", map[string]string{"a": "x", "b": "y"}, pgwOK.URL, reg); err != nil { - t.Fatal(err) - } - if lastMethod != "POST" { - t.Error("want method POSTT for PushAdd, got", lastMethod) - } - if bytes.Compare(lastBody, wantBody) != 0 { - t.Errorf("got body %v, want %v", lastBody, wantBody) - } - if lastPath != "/metrics/job/testjob/a/x/b/y" && lastPath != "/metrics/job/testjob/b/y/a/x" { - t.Error("unexpected path:", lastPath) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/registry_test.go b/vendor/github.com/prometheus/client_golang/prometheus/registry_test.go deleted file mode 100644 index 9dacb6256dd7..000000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/registry_test.go +++ /dev/null @@ -1,545 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Copyright (c) 2013, The Prometheus Authors -// All rights reserved. -// -// Use of this source code is governed by a BSD-style license that can be found -// in the LICENSE file. - -package prometheus_test - -import ( - "bytes" - "net/http" - "net/http/httptest" - "testing" - - dto "github.com/prometheus/client_model/go" - - "github.com/golang/protobuf/proto" - "github.com/prometheus/common/expfmt" - - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" -) - -func testHandler(t testing.TB) { - - metricVec := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "name", - Help: "docstring", - ConstLabels: prometheus.Labels{"constname": "constvalue"}, - }, - []string{"labelname"}, - ) - - metricVec.WithLabelValues("val1").Inc() - metricVec.WithLabelValues("val2").Inc() - - externalMetricFamily := &dto.MetricFamily{ - Name: proto.String("externalname"), - Help: proto.String("externaldocstring"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("externalconstname"), - Value: proto.String("externalconstvalue"), - }, - { - Name: proto.String("externallabelname"), - Value: proto.String("externalval1"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(1), - }, - }, - }, - } - externalBuf := &bytes.Buffer{} - enc := expfmt.NewEncoder(externalBuf, expfmt.FmtProtoDelim) - if err := enc.Encode(externalMetricFamily); err != nil { - t.Fatal(err) - } - externalMetricFamilyAsBytes := externalBuf.Bytes() - externalMetricFamilyAsText := []byte(`# HELP externalname externaldocstring -# TYPE externalname counter -externalname{externalconstname="externalconstvalue",externallabelname="externalval1"} 1 -`) - externalMetricFamilyAsProtoText := []byte(`name: "externalname" -help: "externaldocstring" -type: COUNTER -metric: < - label: < - name: "externalconstname" - value: "externalconstvalue" - > - label: < - name: "externallabelname" - value: "externalval1" - > - counter: < - value: 1 - > -> - -`) - externalMetricFamilyAsProtoCompactText := []byte(`name:"externalname" help:"externaldocstring" type:COUNTER metric: label: counter: > -`) - - expectedMetricFamily := &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("docstring"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("constname"), - Value: proto.String("constvalue"), - }, - { - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(1), - }, - }, - { - Label: []*dto.LabelPair{ - { - Name: proto.String("constname"), - Value: proto.String("constvalue"), - }, - { - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(1), - }, - }, - }, - } - buf := &bytes.Buffer{} - enc = expfmt.NewEncoder(buf, expfmt.FmtProtoDelim) - if err := enc.Encode(expectedMetricFamily); err != nil { - t.Fatal(err) - } - expectedMetricFamilyAsBytes := buf.Bytes() - expectedMetricFamilyAsText := []byte(`# HELP name docstring -# TYPE name counter -name{constname="constvalue",labelname="val1"} 1 -name{constname="constvalue",labelname="val2"} 1 -`) - expectedMetricFamilyAsProtoText := []byte(`name: "name" -help: "docstring" -type: COUNTER -metric: < - label: < - name: "constname" - value: "constvalue" - > - label: < - name: "labelname" - value: "val1" - > - counter: < - value: 1 - > -> -metric: < - label: < - name: "constname" - value: "constvalue" - > - label: < - name: "labelname" - value: "val2" - > - counter: < - value: 1 - > -> - -`) - expectedMetricFamilyAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric: label: counter: > metric: label: counter: > -`) - - externalMetricFamilyWithSameName := &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("docstring"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("constname"), - Value: proto.String("constvalue"), - }, - { - Name: proto.String("labelname"), - Value: proto.String("different_val"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(42), - }, - }, - }, - } - - expectedMetricFamilyMergedWithExternalAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric: label: counter: > metric: label: counter: > metric: label: counter: > -`) - - type output struct { - headers map[string]string - body []byte - } - - var scenarios = []struct { - headers map[string]string - out output - collector prometheus.Collector - externalMF []*dto.MetricFamily - }{ - { // 0 - headers: map[string]string{ - "Accept": "foo/bar;q=0.2, dings/bums;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 1 - headers: map[string]string{ - "Accept": "foo/bar;q=0.2, application/quark;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 2 - headers: map[string]string{ - "Accept": "foo/bar;q=0.2, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 3 - headers: map[string]string{ - "Accept": "text/plain;q=0.2, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: []byte{}, - }, - }, - { // 4 - headers: map[string]string{ - "Accept": "application/json", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: expectedMetricFamilyAsText, - }, - collector: metricVec, - }, - { // 5 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: expectedMetricFamilyAsBytes, - }, - collector: metricVec, - }, - { // 6 - headers: map[string]string{ - "Accept": "application/json", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: externalMetricFamilyAsText, - }, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 7 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: externalMetricFamilyAsBytes, - }, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 8 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsBytes, - expectedMetricFamilyAsBytes, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 9 - headers: map[string]string{ - "Accept": "text/plain", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 10 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.2, text/plain;q=0.5", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: expectedMetricFamilyAsText, - }, - collector: metricVec, - }, - { // 11 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.2, text/plain;q=0.5;version=0.0.4", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsText, - expectedMetricFamilyAsText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 12 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.2, text/plain;q=0.5;version=0.0.2", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsBytes, - expectedMetricFamilyAsBytes, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 13 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=text;q=0.5, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.4", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=text`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsProtoText, - expectedMetricFamilyAsProtoText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 14 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=compact-text", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=compact-text`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsProtoCompactText, - expectedMetricFamilyAsProtoCompactText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 15 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=compact-text", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=compact-text`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsProtoCompactText, - expectedMetricFamilyMergedWithExternalAsProtoCompactText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{ - externalMetricFamily, - externalMetricFamilyWithSameName, - }, - }, - } - for i, scenario := range scenarios { - registry := prometheus.NewPedanticRegistry() - gatherer := prometheus.Gatherer(registry) - if scenario.externalMF != nil { - gatherer = prometheus.Gatherers{ - registry, - prometheus.GathererFunc(func() ([]*dto.MetricFamily, error) { - return scenario.externalMF, nil - }), - } - } - - if scenario.collector != nil { - registry.Register(scenario.collector) - } - writer := httptest.NewRecorder() - handler := prometheus.InstrumentHandler("prometheus", promhttp.HandlerFor(gatherer, promhttp.HandlerOpts{})) - request, _ := http.NewRequest("GET", "/", nil) - for key, value := range scenario.headers { - request.Header.Add(key, value) - } - handler(writer, request) - - for key, value := range scenario.out.headers { - if writer.HeaderMap.Get(key) != value { - t.Errorf( - "%d. expected %q for header %q, got %q", - i, value, key, writer.Header().Get(key), - ) - } - } - - if !bytes.Equal(scenario.out.body, writer.Body.Bytes()) { - t.Errorf( - "%d. expected body:\n%s\ngot body:\n%s\n", - i, scenario.out.body, writer.Body.Bytes(), - ) - } - } -} - -func TestHandler(t *testing.T) { - testHandler(t) -} - -func BenchmarkHandler(b *testing.B) { - for i := 0; i < b.N; i++ { - testHandler(b) - } -} - -func TestRegisterWithOrGet(t *testing.T) { - // Replace the default registerer just to be sure. This is bad, but this - // whole test will go away once RegisterOrGet is removed. - oldRegisterer := prometheus.DefaultRegisterer - defer func() { - prometheus.DefaultRegisterer = oldRegisterer - }() - prometheus.DefaultRegisterer = prometheus.NewRegistry() - original := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "test", - Help: "help", - }, - []string{"foo", "bar"}, - ) - equalButNotSame := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "test", - Help: "help", - }, - []string{"foo", "bar"}, - ) - if err := prometheus.Register(original); err != nil { - t.Fatal(err) - } - if err := prometheus.Register(equalButNotSame); err == nil { - t.Fatal("expected error when registringe equal collector") - } - existing, err := prometheus.RegisterOrGet(equalButNotSame) - if err != nil { - t.Fatal(err) - } - if existing != original { - t.Error("expected original collector but got something else") - } - if existing == equalButNotSame { - t.Error("expected original callector but got new one") - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/summary_test.go b/vendor/github.com/prometheus/client_golang/prometheus/summary_test.go deleted file mode 100644 index c4575ffbd21b..000000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/summary_test.go +++ /dev/null @@ -1,347 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "math" - "math/rand" - "sort" - "sync" - "testing" - "testing/quick" - "time" - - dto "github.com/prometheus/client_model/go" -) - -func benchmarkSummaryObserve(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewSummary(SummaryOpts{}) - - for i := 0; i < w; i++ { - go func() { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Observe(float64(i)) - } - - wg.Done() - }() - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkSummaryObserve1(b *testing.B) { - benchmarkSummaryObserve(1, b) -} - -func BenchmarkSummaryObserve2(b *testing.B) { - benchmarkSummaryObserve(2, b) -} - -func BenchmarkSummaryObserve4(b *testing.B) { - benchmarkSummaryObserve(4, b) -} - -func BenchmarkSummaryObserve8(b *testing.B) { - benchmarkSummaryObserve(8, b) -} - -func benchmarkSummaryWrite(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewSummary(SummaryOpts{}) - - for i := 0; i < 1000000; i++ { - s.Observe(float64(i)) - } - - for j := 0; j < w; j++ { - outs := make([]dto.Metric, b.N) - - go func(o []dto.Metric) { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Write(&o[i]) - } - - wg.Done() - }(outs) - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkSummaryWrite1(b *testing.B) { - benchmarkSummaryWrite(1, b) -} - -func BenchmarkSummaryWrite2(b *testing.B) { - benchmarkSummaryWrite(2, b) -} - -func BenchmarkSummaryWrite4(b *testing.B) { - benchmarkSummaryWrite(4, b) -} - -func BenchmarkSummaryWrite8(b *testing.B) { - benchmarkSummaryWrite(8, b) -} - -func TestSummaryConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%5 + 1) - total := mutations * concLevel - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sum := NewSummary(SummaryOpts{ - Name: "test_summary", - Help: "helpless", - }) - - allVars := make([]float64, total) - var sampleSum float64 - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - allVars[i*mutations+j] = v - sampleSum += v - } - - go func(vals []float64) { - start.Wait() - for _, v := range vals { - sum.Observe(v) - } - end.Done() - }(vals) - } - sort.Float64s(allVars) - start.Done() - end.Wait() - - m := &dto.Metric{} - sum.Write(m) - if got, want := int(*m.Summary.SampleCount), total; got != want { - t.Errorf("got sample count %d, want %d", got, want) - } - if got, want := *m.Summary.SampleSum, sampleSum; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f, want %f", got, want) - } - - objectives := make([]float64, 0, len(DefObjectives)) - for qu := range DefObjectives { - objectives = append(objectives, qu) - } - sort.Float64s(objectives) - - for i, wantQ := range objectives { - ε := DefObjectives[wantQ] - gotQ := *m.Summary.Quantile[i].Quantile - gotV := *m.Summary.Quantile[i].Value - min, max := getBounds(allVars, wantQ, ε) - if gotQ != wantQ { - t.Errorf("got quantile %f, want %f", gotQ, wantQ) - } - if gotV < min || gotV > max { - t.Errorf("got %f for quantile %f, want [%f,%f]", gotV, gotQ, min, max) - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func TestSummaryVecConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - objectives := make([]float64, 0, len(DefObjectives)) - for qu := range DefObjectives { - - objectives = append(objectives, qu) - } - sort.Float64s(objectives) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%7 + 1) - vecLength := int(n%3 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sum := NewSummaryVec( - SummaryOpts{ - Name: "test_summary", - Help: "helpless", - }, - []string{"label"}, - ) - - allVars := make([][]float64, vecLength) - sampleSums := make([]float64, vecLength) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - picks := make([]int, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - pick := rand.Intn(vecLength) - picks[j] = pick - allVars[pick] = append(allVars[pick], v) - sampleSums[pick] += v - } - - go func(vals []float64) { - start.Wait() - for i, v := range vals { - sum.WithLabelValues(string('A' + picks[i])).Observe(v) - } - end.Done() - }(vals) - } - for _, vars := range allVars { - sort.Float64s(vars) - } - start.Done() - end.Wait() - - for i := 0; i < vecLength; i++ { - m := &dto.Metric{} - s := sum.WithLabelValues(string('A' + i)) - s.Write(m) - if got, want := int(*m.Summary.SampleCount), len(allVars[i]); got != want { - t.Errorf("got sample count %d for label %c, want %d", got, 'A'+i, want) - } - if got, want := *m.Summary.SampleSum, sampleSums[i]; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f for label %c, want %f", got, 'A'+i, want) - } - for j, wantQ := range objectives { - ε := DefObjectives[wantQ] - gotQ := *m.Summary.Quantile[j].Quantile - gotV := *m.Summary.Quantile[j].Value - min, max := getBounds(allVars[i], wantQ, ε) - if gotQ != wantQ { - t.Errorf("got quantile %f for label %c, want %f", gotQ, 'A'+i, wantQ) - } - if gotV < min || gotV > max { - t.Errorf("got %f for quantile %f for label %c, want [%f,%f]", gotV, gotQ, 'A'+i, min, max) - } - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func TestSummaryDecay(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - // More because it depends on timing than because it is particularly long... - } - - sum := NewSummary(SummaryOpts{ - Name: "test_summary", - Help: "helpless", - MaxAge: 100 * time.Millisecond, - Objectives: map[float64]float64{0.1: 0.001}, - AgeBuckets: 10, - }) - - m := &dto.Metric{} - i := 0 - tick := time.NewTicker(time.Millisecond) - for _ = range tick.C { - i++ - sum.Observe(float64(i)) - if i%10 == 0 { - sum.Write(m) - if got, want := *m.Summary.Quantile[0].Value, math.Max(float64(i)/10, float64(i-90)); math.Abs(got-want) > 20 { - t.Errorf("%d. got %f, want %f", i, got, want) - } - m.Reset() - } - if i >= 1000 { - break - } - } - tick.Stop() - // Wait for MaxAge without observations and make sure quantiles are NaN. - time.Sleep(100 * time.Millisecond) - sum.Write(m) - if got := *m.Summary.Quantile[0].Value; !math.IsNaN(got) { - t.Errorf("got %f, want NaN after expiration", got) - } -} - -func getBounds(vars []float64, q, ε float64) (min, max float64) { - // TODO(beorn7): This currently tolerates an error of up to 2*ε. The - // error must be at most ε, but for some reason, it's sometimes slightly - // higher. That's a bug. - n := float64(len(vars)) - lower := int((q - 2*ε) * n) - upper := int(math.Ceil((q + 2*ε) * n)) - min = vars[0] - if lower > 1 { - min = vars[lower-1] - } - max = vars[len(vars)-1] - if upper < len(vars) { - max = vars[upper-1] - } - return -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/vec_test.go b/vendor/github.com/prometheus/client_golang/prometheus/vec_test.go deleted file mode 100644 index 445a6b39fe0d..000000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/vec_test.go +++ /dev/null @@ -1,312 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "fmt" - "testing" - - dto "github.com/prometheus/client_model/go" -) - -func TestDelete(t *testing.T) { - vec := NewUntypedVec( - UntypedOpts{ - Name: "test", - Help: "helpless", - }, - []string{"l1", "l2"}, - ) - testDelete(t, vec) -} - -func TestDeleteWithCollisions(t *testing.T) { - vec := NewUntypedVec( - UntypedOpts{ - Name: "test", - Help: "helpless", - }, - []string{"l1", "l2"}, - ) - vec.hashAdd = func(h uint64, s string) uint64 { return 1 } - vec.hashAddByte = func(h uint64, b byte) uint64 { return 1 } - testDelete(t, vec) -} - -func testDelete(t *testing.T, vec *UntypedVec) { - if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), true; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - if got, want := vec.Delete(Labels{"l2": "v2", "l1": "v1"}), true; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.Delete(Labels{"l2": "v2", "l1": "v1"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - if got, want := vec.Delete(Labels{"l2": "v1", "l1": "v2"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.Delete(Labels{"l1": "v1"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } -} - -func TestDeleteLabelValues(t *testing.T) { - vec := NewUntypedVec( - UntypedOpts{ - Name: "test", - Help: "helpless", - }, - []string{"l1", "l2"}, - ) - testDeleteLabelValues(t, vec) -} - -func TestDeleteLabelValuesWithCollisions(t *testing.T) { - vec := NewUntypedVec( - UntypedOpts{ - Name: "test", - Help: "helpless", - }, - []string{"l1", "l2"}, - ) - vec.hashAdd = func(h uint64, s string) uint64 { return 1 } - vec.hashAddByte = func(h uint64, b byte) uint64 { return 1 } - testDeleteLabelValues(t, vec) -} - -func testDeleteLabelValues(t *testing.T, vec *UntypedVec) { - if got, want := vec.DeleteLabelValues("v1", "v2"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - vec.With(Labels{"l1": "v1", "l2": "v3"}).(Untyped).Set(42) // Add junk data for collision. - if got, want := vec.DeleteLabelValues("v1", "v2"), true; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.DeleteLabelValues("v1", "v2"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.DeleteLabelValues("v1", "v3"), true; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - // Delete out of order. - if got, want := vec.DeleteLabelValues("v2", "v1"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.DeleteLabelValues("v1"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } -} - -func TestMetricVec(t *testing.T) { - vec := NewUntypedVec( - UntypedOpts{ - Name: "test", - Help: "helpless", - }, - []string{"l1", "l2"}, - ) - testMetricVec(t, vec) -} - -func TestMetricVecWithCollisions(t *testing.T) { - vec := NewUntypedVec( - UntypedOpts{ - Name: "test", - Help: "helpless", - }, - []string{"l1", "l2"}, - ) - vec.hashAdd = func(h uint64, s string) uint64 { return 1 } - vec.hashAddByte = func(h uint64, b byte) uint64 { return 1 } - testMetricVec(t, vec) -} - -func testMetricVec(t *testing.T, vec *UntypedVec) { - vec.Reset() // Actually test Reset now! - - var pair [2]string - // Keep track of metrics. - expected := map[[2]string]int{} - - for i := 0; i < 1000; i++ { - pair[0], pair[1] = fmt.Sprint(i%4), fmt.Sprint(i%5) // Varying combinations multiples. - expected[pair]++ - vec.WithLabelValues(pair[0], pair[1]).Inc() - - expected[[2]string{"v1", "v2"}]++ - vec.WithLabelValues("v1", "v2").(Untyped).Inc() - } - - var total int - for _, metrics := range vec.children { - for _, metric := range metrics { - total++ - copy(pair[:], metric.values) - - var metricOut dto.Metric - if err := metric.metric.Write(&metricOut); err != nil { - t.Fatal(err) - } - actual := *metricOut.Untyped.Value - - var actualPair [2]string - for i, label := range metricOut.Label { - actualPair[i] = *label.Value - } - - // Test output pair against metric.values to ensure we've selected - // the right one. We check this to ensure the below check means - // anything at all. - if actualPair != pair { - t.Fatalf("unexpected pair association in metric map: %v != %v", actualPair, pair) - } - - if actual != float64(expected[pair]) { - t.Fatalf("incorrect counter value for %v: %v != %v", pair, actual, expected[pair]) - } - } - } - - if total != len(expected) { - t.Fatalf("unexpected number of metrics: %v != %v", total, len(expected)) - } - - vec.Reset() - - if len(vec.children) > 0 { - t.Fatalf("reset failed") - } -} - -func TestCounterVecEndToEndWithCollision(t *testing.T) { - vec := NewCounterVec( - CounterOpts{ - Name: "test", - Help: "helpless", - }, - []string{"labelname"}, - ) - vec.WithLabelValues("77kepQFQ8Kl").Inc() - vec.WithLabelValues("!0IC=VloaY").Add(2) - - m := &dto.Metric{} - if err := vec.WithLabelValues("77kepQFQ8Kl").Write(m); err != nil { - t.Fatal(err) - } - if got, want := m.GetLabel()[0].GetValue(), "77kepQFQ8Kl"; got != want { - t.Errorf("got label value %q, want %q", got, want) - } - if got, want := m.GetCounter().GetValue(), 1.; got != want { - t.Errorf("got value %f, want %f", got, want) - } - m.Reset() - if err := vec.WithLabelValues("!0IC=VloaY").Write(m); err != nil { - t.Fatal(err) - } - if got, want := m.GetLabel()[0].GetValue(), "!0IC=VloaY"; got != want { - t.Errorf("got label value %q, want %q", got, want) - } - if got, want := m.GetCounter().GetValue(), 2.; got != want { - t.Errorf("got value %f, want %f", got, want) - } -} - -func BenchmarkMetricVecWithLabelValuesBasic(b *testing.B) { - benchmarkMetricVecWithLabelValues(b, map[string][]string{ - "l1": []string{"onevalue"}, - "l2": []string{"twovalue"}, - }) -} - -func BenchmarkMetricVecWithLabelValues2Keys10ValueCardinality(b *testing.B) { - benchmarkMetricVecWithLabelValuesCardinality(b, 2, 10) -} - -func BenchmarkMetricVecWithLabelValues4Keys10ValueCardinality(b *testing.B) { - benchmarkMetricVecWithLabelValuesCardinality(b, 4, 10) -} - -func BenchmarkMetricVecWithLabelValues2Keys100ValueCardinality(b *testing.B) { - benchmarkMetricVecWithLabelValuesCardinality(b, 2, 100) -} - -func BenchmarkMetricVecWithLabelValues10Keys100ValueCardinality(b *testing.B) { - benchmarkMetricVecWithLabelValuesCardinality(b, 10, 100) -} - -func BenchmarkMetricVecWithLabelValues10Keys1000ValueCardinality(b *testing.B) { - benchmarkMetricVecWithLabelValuesCardinality(b, 10, 1000) -} - -func benchmarkMetricVecWithLabelValuesCardinality(b *testing.B, nkeys, nvalues int) { - labels := map[string][]string{} - - for i := 0; i < nkeys; i++ { - var ( - k = fmt.Sprintf("key-%v", i) - vs = make([]string, 0, nvalues) - ) - for j := 0; j < nvalues; j++ { - vs = append(vs, fmt.Sprintf("value-%v", j)) - } - labels[k] = vs - } - - benchmarkMetricVecWithLabelValues(b, labels) -} - -func benchmarkMetricVecWithLabelValues(b *testing.B, labels map[string][]string) { - var keys []string - for k := range labels { // Map order dependent, who cares though. - keys = append(keys, k) - } - - values := make([]string, len(labels)) // Value cache for permutations. - vec := NewUntypedVec( - UntypedOpts{ - Name: "test", - Help: "helpless", - }, - keys, - ) - - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - // Varies input across provide map entries based on key size. - for j, k := range keys { - candidates := labels[k] - values[j] = candidates[i%len(candidates)] - } - - vec.WithLabelValues(values...) - } -} diff --git a/vendor/github.com/prometheus/common/expfmt/BUILD b/vendor/github.com/prometheus/common/expfmt/BUILD index 31faa8f6d99b..d0693d58957a 100644 --- a/vendor/github.com/prometheus/common/expfmt/BUILD +++ b/vendor/github.com/prometheus/common/expfmt/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -21,25 +21,6 @@ go_library( ], ) -go_test( - name = "go_default_test", - srcs = [ - "bench_test.go", - "decode_test.go", - "json_decode_test.go", - "text_create_test.go", - "text_parse_test.go", - ], - importpath = "github.com/prometheus/common/expfmt", - library = ":go_default_library", - deps = [ - "//vendor/github.com/golang/protobuf/proto:go_default_library", - "//vendor/github.com/matttproud/golang_protobuf_extensions/pbutil:go_default_library", - "//vendor/github.com/prometheus/client_model/go:go_default_library", - "//vendor/github.com/prometheus/common/model:go_default_library", - ], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/prometheus/common/expfmt/bench_test.go b/vendor/github.com/prometheus/common/expfmt/bench_test.go deleted file mode 100644 index 92b16a028aad..000000000000 --- a/vendor/github.com/prometheus/common/expfmt/bench_test.go +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package expfmt - -import ( - "bytes" - "compress/gzip" - "io" - "io/ioutil" - "testing" - - "github.com/matttproud/golang_protobuf_extensions/pbutil" - - dto "github.com/prometheus/client_model/go" -) - -var parser TextParser - -// Benchmarks to show how much penalty text format parsing actually inflicts. -// -// Example results on Linux 3.13.0, Intel(R) Core(TM) i7-4700MQ CPU @ 2.40GHz, go1.4. -// -// BenchmarkParseText 1000 1188535 ns/op 205085 B/op 6135 allocs/op -// BenchmarkParseTextGzip 1000 1376567 ns/op 246224 B/op 6151 allocs/op -// BenchmarkParseProto 10000 172790 ns/op 52258 B/op 1160 allocs/op -// BenchmarkParseProtoGzip 5000 324021 ns/op 94931 B/op 1211 allocs/op -// BenchmarkParseProtoMap 10000 187946 ns/op 58714 B/op 1203 allocs/op -// -// CONCLUSION: The overhead for the map is negligible. Text format needs ~5x more allocations. -// Without compression, it needs ~7x longer, but with compression (the more relevant scenario), -// the difference becomes less relevant, only ~4x. -// -// The test data contains 248 samples. -// -// BenchmarkProcessor002ParseOnly in the extraction package is not quite -// comparable to the benchmarks here, but it gives an idea: JSON parsing is even -// slower than text parsing and needs a comparable amount of allocs. - -// BenchmarkParseText benchmarks the parsing of a text-format scrape into metric -// family DTOs. -func BenchmarkParseText(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/text") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - if _, err := parser.TextToMetricFamilies(bytes.NewReader(data)); err != nil { - b.Fatal(err) - } - } -} - -// BenchmarkParseTextGzip benchmarks the parsing of a gzipped text-format scrape -// into metric family DTOs. -func BenchmarkParseTextGzip(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/text.gz") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - in, err := gzip.NewReader(bytes.NewReader(data)) - if err != nil { - b.Fatal(err) - } - if _, err := parser.TextToMetricFamilies(in); err != nil { - b.Fatal(err) - } - } -} - -// BenchmarkParseProto benchmarks the parsing of a protobuf-format scrape into -// metric family DTOs. Note that this does not build a map of metric families -// (as the text version does), because it is not required for Prometheus -// ingestion either. (However, it is required for the text-format parsing, as -// the metric family might be sprinkled all over the text, while the -// protobuf-format guarantees bundling at one place.) -func BenchmarkParseProto(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/protobuf") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - family := &dto.MetricFamily{} - in := bytes.NewReader(data) - for { - family.Reset() - if _, err := pbutil.ReadDelimited(in, family); err != nil { - if err == io.EOF { - break - } - b.Fatal(err) - } - } - } -} - -// BenchmarkParseProtoGzip is like BenchmarkParseProto above, but parses gzipped -// protobuf format. -func BenchmarkParseProtoGzip(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/protobuf.gz") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - family := &dto.MetricFamily{} - in, err := gzip.NewReader(bytes.NewReader(data)) - if err != nil { - b.Fatal(err) - } - for { - family.Reset() - if _, err := pbutil.ReadDelimited(in, family); err != nil { - if err == io.EOF { - break - } - b.Fatal(err) - } - } - } -} - -// BenchmarkParseProtoMap is like BenchmarkParseProto but DOES put the parsed -// metric family DTOs into a map. This is not happening during Prometheus -// ingestion. It is just here to measure the overhead of that map creation and -// separate it from the overhead of the text format parsing. -func BenchmarkParseProtoMap(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/protobuf") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - families := map[string]*dto.MetricFamily{} - in := bytes.NewReader(data) - for { - family := &dto.MetricFamily{} - if _, err := pbutil.ReadDelimited(in, family); err != nil { - if err == io.EOF { - break - } - b.Fatal(err) - } - families[family.GetName()] = family - } - } -} diff --git a/vendor/github.com/prometheus/common/expfmt/decode_test.go b/vendor/github.com/prometheus/common/expfmt/decode_test.go deleted file mode 100644 index 9f78d9dabc2f..000000000000 --- a/vendor/github.com/prometheus/common/expfmt/decode_test.go +++ /dev/null @@ -1,356 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package expfmt - -import ( - "io" - "net/http" - "reflect" - "sort" - "strings" - "testing" - - "github.com/prometheus/common/model" -) - -func TestTextDecoder(t *testing.T) { - var ( - ts = model.Now() - in = ` -# Only a quite simple scenario with two metric families. -# More complicated tests of the parser itself can be found in the text package. -# TYPE mf2 counter -mf2 3 -mf1{label="value1"} -3.14 123456 -mf1{label="value2"} 42 -mf2 4 -` - out = model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf1", - "label": "value1", - }, - Value: -3.14, - Timestamp: 123456, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf1", - "label": "value2", - }, - Value: 42, - Timestamp: ts, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf2", - }, - Value: 3, - Timestamp: ts, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf2", - }, - Value: 4, - Timestamp: ts, - }, - } - ) - - dec := &SampleDecoder{ - Dec: &textDecoder{r: strings.NewReader(in)}, - Opts: &DecodeOptions{ - Timestamp: ts, - }, - } - var all model.Vector - for { - var smpls model.Vector - err := dec.Decode(&smpls) - if err == io.EOF { - break - } - if err != nil { - t.Fatal(err) - } - all = append(all, smpls...) - } - sort.Sort(all) - sort.Sort(out) - if !reflect.DeepEqual(all, out) { - t.Fatalf("output does not match") - } -} - -func TestProtoDecoder(t *testing.T) { - - var testTime = model.Now() - - scenarios := []struct { - in string - expected model.Vector - }{ - { - in: "", - }, - { - in: "\x8f\x01\n\rrequest_count\x12\x12Number of requests\x18\x00\"0\n#\n\x0fsome_label_name\x12\x10some_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00E\xc0\"6\n)\n\x12another_label_name\x12\x13another_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00U@", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "some_label_name": "some_label_value", - }, - Value: -42, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "another_label_name": "another_label_value", - }, - Value: 84, - Timestamp: testTime, - }, - }, - }, - { - in: "\xb9\x01\n\rrequest_count\x12\x12Number of requests\x18\x02\"O\n#\n\x0fsome_label_name\x12\x10some_label_value\"(\x1a\x12\t\xaeG\xe1z\x14\xae\xef?\x11\x00\x00\x00\x00\x00\x00E\xc0\x1a\x12\t+\x87\x16\xd9\xce\xf7\xef?\x11\x00\x00\x00\x00\x00\x00U\xc0\"A\n)\n\x12another_label_name\x12\x13another_label_value\"\x14\x1a\x12\t\x00\x00\x00\x00\x00\x00\xe0?\x11\x00\x00\x00\x00\x00\x00$@", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_count", - "some_label_name": "some_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_sum", - "some_label_name": "some_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "some_label_name": "some_label_value", - "quantile": "0.99", - }, - Value: -42, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "some_label_name": "some_label_value", - "quantile": "0.999", - }, - Value: -84, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_count", - "another_label_name": "another_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_sum", - "another_label_name": "another_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "another_label_name": "another_label_value", - "quantile": "0.5", - }, - Value: 10, - Timestamp: testTime, - }, - }, - }, - { - in: "\x8d\x01\n\x1drequest_duration_microseconds\x12\x15The response latency.\x18\x04\"S:Q\b\x85\x15\x11\xcd\xcc\xccL\x8f\xcb:A\x1a\v\b{\x11\x00\x00\x00\x00\x00\x00Y@\x1a\f\b\x9c\x03\x11\x00\x00\x00\x00\x00\x00^@\x1a\f\b\xd0\x04\x11\x00\x00\x00\x00\x00\x00b@\x1a\f\b\xf4\v\x11\x9a\x99\x99\x99\x99\x99e@\x1a\f\b\x85\x15\x11\x00\x00\x00\x00\x00\x00\xf0\u007f", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "100", - }, - Value: 123, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "120", - }, - Value: 412, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "144", - }, - Value: 592, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "172.8", - }, - Value: 1524, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "+Inf", - }, - Value: 2693, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_sum", - }, - Value: 1756047.3, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_count", - }, - Value: 2693, - Timestamp: testTime, - }, - }, - }, - { - // The metric type is unset in this protobuf, which needs to be handled - // correctly by the decoder. - in: "\x1c\n\rrequest_count\"\v\x1a\t\t\x00\x00\x00\x00\x00\x00\xf0?", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - }, - Value: 1, - Timestamp: testTime, - }, - }, - }, - } - - for i, scenario := range scenarios { - dec := &SampleDecoder{ - Dec: &protoDecoder{r: strings.NewReader(scenario.in)}, - Opts: &DecodeOptions{ - Timestamp: testTime, - }, - } - - var all model.Vector - for { - var smpls model.Vector - err := dec.Decode(&smpls) - if err == io.EOF { - break - } - if err != nil { - t.Fatal(err) - } - all = append(all, smpls...) - } - sort.Sort(all) - sort.Sort(scenario.expected) - if !reflect.DeepEqual(all, scenario.expected) { - t.Fatalf("%d. output does not match, want: %#v, got %#v", i, scenario.expected, all) - } - } -} - -func testDiscriminatorHTTPHeader(t testing.TB) { - var scenarios = []struct { - input map[string]string - output Format - err error - }{ - { - input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="io.prometheus.client.MetricFamily"; encoding="delimited"`}, - output: FmtProtoDelim, - }, - { - input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="illegal"; encoding="delimited"`}, - output: FmtUnknown, - }, - { - input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="io.prometheus.client.MetricFamily"; encoding="illegal"`}, - output: FmtUnknown, - }, - { - input: map[string]string{"Content-Type": `text/plain; version=0.0.4`}, - output: FmtText, - }, - { - input: map[string]string{"Content-Type": `text/plain`}, - output: FmtText, - }, - { - input: map[string]string{"Content-Type": `text/plain; version=0.0.3`}, - output: FmtUnknown, - }, - } - - for i, scenario := range scenarios { - var header http.Header - - if len(scenario.input) > 0 { - header = http.Header{} - } - - for key, value := range scenario.input { - header.Add(key, value) - } - - actual := ResponseFormat(header) - - if scenario.output != actual { - t.Errorf("%d. expected %s, got %s", i, scenario.output, actual) - } - } -} - -func TestDiscriminatorHTTPHeader(t *testing.T) { - testDiscriminatorHTTPHeader(t) -} - -func BenchmarkDiscriminatorHTTPHeader(b *testing.B) { - for i := 0; i < b.N; i++ { - testDiscriminatorHTTPHeader(b) - } -} diff --git a/vendor/github.com/prometheus/common/expfmt/json_decode_test.go b/vendor/github.com/prometheus/common/expfmt/json_decode_test.go deleted file mode 100644 index c98ea29e1768..000000000000 --- a/vendor/github.com/prometheus/common/expfmt/json_decode_test.go +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package expfmt - -import ( - "os" - "reflect" - "testing" - - "github.com/golang/protobuf/proto" - dto "github.com/prometheus/client_model/go" -) - -func TestJSON2Decode(t *testing.T) { - f, err := os.Open("testdata/json2") - if err != nil { - t.Fatal(err) - } - defer f.Close() - - dec := newJSON2Decoder(f) - - var v1 dto.MetricFamily - if err := dec.Decode(&v1); err != nil { - t.Fatal(err) - } - - exp1 := dto.MetricFamily{ - Type: dto.MetricType_UNTYPED.Enum(), - Help: proto.String("RPC calls."), - Name: proto.String("rpc_calls_total"), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("job"), - Value: proto.String("batch_job"), - }, { - Name: proto.String("service"), - Value: proto.String("zed"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(25), - }, - }, - { - Label: []*dto.LabelPair{ - { - Name: proto.String("job"), - Value: proto.String("batch_job"), - }, { - Name: proto.String("service"), - Value: proto.String("bar"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(24), - }, - }, - }, - } - - if !reflect.DeepEqual(v1, exp1) { - t.Fatalf("Expected %v, got %v", exp1, v1) - } - - var v2 dto.MetricFamily - if err := dec.Decode(&v2); err != nil { - t.Fatal(err) - } - - exp2 := dto.MetricFamily{ - Type: dto.MetricType_UNTYPED.Enum(), - Help: proto.String("RPC latency."), - Name: proto.String("rpc_latency_microseconds"), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("percentile"), - Value: proto.String("0.010000"), - }, { - Name: proto.String("service"), - Value: proto.String("foo"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(15), - }, - }, - { - Label: []*dto.LabelPair{ - { - Name: proto.String("percentile"), - Value: proto.String("0.990000"), - }, { - Name: proto.String("service"), - Value: proto.String("foo"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(17), - }, - }, - }, - } - - if !reflect.DeepEqual(v2, exp2) { - t.Fatalf("Expected %v, got %v", exp2, v2) - } - -} diff --git a/vendor/github.com/prometheus/common/expfmt/text_create_test.go b/vendor/github.com/prometheus/common/expfmt/text_create_test.go deleted file mode 100644 index e4cc5d803bb8..000000000000 --- a/vendor/github.com/prometheus/common/expfmt/text_create_test.go +++ /dev/null @@ -1,443 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package expfmt - -import ( - "bytes" - "math" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - - dto "github.com/prometheus/client_model/go" -) - -func testCreate(t testing.TB) { - var scenarios = []struct { - in *dto.MetricFamily - out string - }{ - // 0: Counter, NaN as value, timestamp given. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("two-line\n doc str\\ing"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(math.NaN()), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(.23), - }, - TimestampMs: proto.Int64(1234567890), - }, - }, - }, - out: `# HELP name two-line\n doc str\\ing -# TYPE name counter -name{labelname="val1",basename="basevalue"} NaN -name{labelname="val2",basename="basevalue"} 0.23 1234567890 -`, - }, - // 1: Gauge, some escaping required, +Inf as value, multi-byte characters in label values. - { - in: &dto.MetricFamily{ - Name: proto.String("gauge_name"), - Help: proto.String("gauge\ndoc\nstr\"ing"), - Type: dto.MetricType_GAUGE.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("val with\nnew line"), - }, - &dto.LabelPair{ - Name: proto.String("name_2"), - Value: proto.String("val with \\backslash and \"quotes\""), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(math.Inf(+1)), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("Björn"), - }, - &dto.LabelPair{ - Name: proto.String("name_2"), - Value: proto.String("佖佥"), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(3.14E42), - }, - }, - }, - }, - out: `# HELP gauge_name gauge\ndoc\nstr"ing -# TYPE gauge_name gauge -gauge_name{name_1="val with\nnew line",name_2="val with \\backslash and \"quotes\""} +Inf -gauge_name{name_1="Björn",name_2="佖佥"} 3.14e+42 -`, - }, - // 2: Untyped, no help, one sample with no labels and -Inf as value, another sample with one label. - { - in: &dto.MetricFamily{ - Name: proto.String("untyped_name"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("value 1"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(-1.23e-45), - }, - }, - }, - }, - out: `# TYPE untyped_name untyped -untyped_name -Inf -untyped_name{name_1="value 1"} -1.23e-45 -`, - }, - // 3: Summary. - { - in: &dto.MetricFamily{ - Name: proto.String("summary_name"), - Help: proto.String("summary docstring"), - Type: dto.MetricType_SUMMARY.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Summary: &dto.Summary{ - SampleCount: proto.Uint64(42), - SampleSum: proto.Float64(-3.4567), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.5), - Value: proto.Float64(-1.23), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.9), - Value: proto.Float64(.2342354), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.99), - Value: proto.Float64(0), - }, - }, - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("value 1"), - }, - &dto.LabelPair{ - Name: proto.String("name_2"), - Value: proto.String("value 2"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(4711), - SampleSum: proto.Float64(2010.1971), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.5), - Value: proto.Float64(1), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.9), - Value: proto.Float64(2), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.99), - Value: proto.Float64(3), - }, - }, - }, - }, - }, - }, - out: `# HELP summary_name summary docstring -# TYPE summary_name summary -summary_name{quantile="0.5"} -1.23 -summary_name{quantile="0.9"} 0.2342354 -summary_name{quantile="0.99"} 0 -summary_name_sum -3.4567 -summary_name_count 42 -summary_name{name_1="value 1",name_2="value 2",quantile="0.5"} 1 -summary_name{name_1="value 1",name_2="value 2",quantile="0.9"} 2 -summary_name{name_1="value 1",name_2="value 2",quantile="0.99"} 3 -summary_name_sum{name_1="value 1",name_2="value 2"} 2010.1971 -summary_name_count{name_1="value 1",name_2="value 2"} 4711 -`, - }, - // 4: Histogram - { - in: &dto.MetricFamily{ - Name: proto.String("request_duration_microseconds"), - Help: proto.String("The response latency."), - Type: dto.MetricType_HISTOGRAM.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Histogram: &dto.Histogram{ - SampleCount: proto.Uint64(2693), - SampleSum: proto.Float64(1756047.3), - Bucket: []*dto.Bucket{ - &dto.Bucket{ - UpperBound: proto.Float64(100), - CumulativeCount: proto.Uint64(123), - }, - &dto.Bucket{ - UpperBound: proto.Float64(120), - CumulativeCount: proto.Uint64(412), - }, - &dto.Bucket{ - UpperBound: proto.Float64(144), - CumulativeCount: proto.Uint64(592), - }, - &dto.Bucket{ - UpperBound: proto.Float64(172.8), - CumulativeCount: proto.Uint64(1524), - }, - &dto.Bucket{ - UpperBound: proto.Float64(math.Inf(+1)), - CumulativeCount: proto.Uint64(2693), - }, - }, - }, - }, - }, - }, - out: `# HELP request_duration_microseconds The response latency. -# TYPE request_duration_microseconds histogram -request_duration_microseconds_bucket{le="100"} 123 -request_duration_microseconds_bucket{le="120"} 412 -request_duration_microseconds_bucket{le="144"} 592 -request_duration_microseconds_bucket{le="172.8"} 1524 -request_duration_microseconds_bucket{le="+Inf"} 2693 -request_duration_microseconds_sum 1.7560473e+06 -request_duration_microseconds_count 2693 -`, - }, - // 5: Histogram with missing +Inf bucket. - { - in: &dto.MetricFamily{ - Name: proto.String("request_duration_microseconds"), - Help: proto.String("The response latency."), - Type: dto.MetricType_HISTOGRAM.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Histogram: &dto.Histogram{ - SampleCount: proto.Uint64(2693), - SampleSum: proto.Float64(1756047.3), - Bucket: []*dto.Bucket{ - &dto.Bucket{ - UpperBound: proto.Float64(100), - CumulativeCount: proto.Uint64(123), - }, - &dto.Bucket{ - UpperBound: proto.Float64(120), - CumulativeCount: proto.Uint64(412), - }, - &dto.Bucket{ - UpperBound: proto.Float64(144), - CumulativeCount: proto.Uint64(592), - }, - &dto.Bucket{ - UpperBound: proto.Float64(172.8), - CumulativeCount: proto.Uint64(1524), - }, - }, - }, - }, - }, - }, - out: `# HELP request_duration_microseconds The response latency. -# TYPE request_duration_microseconds histogram -request_duration_microseconds_bucket{le="100"} 123 -request_duration_microseconds_bucket{le="120"} 412 -request_duration_microseconds_bucket{le="144"} 592 -request_duration_microseconds_bucket{le="172.8"} 1524 -request_duration_microseconds_bucket{le="+Inf"} 2693 -request_duration_microseconds_sum 1.7560473e+06 -request_duration_microseconds_count 2693 -`, - }, - // 6: No metric type, should result in default type Counter. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("doc string"), - Metric: []*dto.Metric{ - &dto.Metric{ - Counter: &dto.Counter{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - out: `# HELP name doc string -# TYPE name counter -name -Inf -`, - }, - } - - for i, scenario := range scenarios { - out := bytes.NewBuffer(make([]byte, 0, len(scenario.out))) - n, err := MetricFamilyToText(out, scenario.in) - if err != nil { - t.Errorf("%d. error: %s", i, err) - continue - } - if expected, got := len(scenario.out), n; expected != got { - t.Errorf( - "%d. expected %d bytes written, got %d", - i, expected, got, - ) - } - if expected, got := scenario.out, out.String(); expected != got { - t.Errorf( - "%d. expected out=%q, got %q", - i, expected, got, - ) - } - } - -} - -func TestCreate(t *testing.T) { - testCreate(t) -} - -func BenchmarkCreate(b *testing.B) { - for i := 0; i < b.N; i++ { - testCreate(b) - } -} - -func testCreateError(t testing.TB) { - var scenarios = []struct { - in *dto.MetricFamily - err string - }{ - // 0: No metric. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("doc string"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{}, - }, - err: "MetricFamily has no metrics", - }, - // 1: No metric name. - { - in: &dto.MetricFamily{ - Help: proto.String("doc string"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - err: "MetricFamily has no name", - }, - // 2: Wrong type. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("doc string"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - err: "expected counter in metric", - }, - } - - for i, scenario := range scenarios { - var out bytes.Buffer - _, err := MetricFamilyToText(&out, scenario.in) - if err == nil { - t.Errorf("%d. expected error, got nil", i) - continue - } - if expected, got := scenario.err, err.Error(); strings.Index(got, expected) != 0 { - t.Errorf( - "%d. expected error starting with %q, got %q", - i, expected, got, - ) - } - } - -} - -func TestCreateError(t *testing.T) { - testCreateError(t) -} - -func BenchmarkCreateError(b *testing.B) { - for i := 0; i < b.N; i++ { - testCreateError(b) - } -} diff --git a/vendor/github.com/prometheus/common/expfmt/text_parse_test.go b/vendor/github.com/prometheus/common/expfmt/text_parse_test.go deleted file mode 100644 index 589c87a9d5fd..000000000000 --- a/vendor/github.com/prometheus/common/expfmt/text_parse_test.go +++ /dev/null @@ -1,586 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package expfmt - -import ( - "math" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - dto "github.com/prometheus/client_model/go" -) - -func testTextParse(t testing.TB) { - var scenarios = []struct { - in string - out []*dto.MetricFamily - }{ - // 0: Empty lines as input. - { - in: ` - -`, - out: []*dto.MetricFamily{}, - }, - // 1: Minimal case. - { - in: ` -minimal_metric 1.234 -another_metric -3e3 103948 -# Even that: -no_labels{} 3 -# HELP line for non-existing metric will be ignored. -`, - out: []*dto.MetricFamily{ - &dto.MetricFamily{ - Name: proto.String("minimal_metric"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(1.234), - }, - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("another_metric"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(-3e3), - }, - TimestampMs: proto.Int64(103948), - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("no_labels"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(3), - }, - }, - }, - }, - }, - }, - // 2: Counters & gauges, docstrings, various whitespace, escape sequences. - { - in: ` -# A normal comment. -# -# TYPE name counter -name{labelname="val1",basename="basevalue"} NaN -name {labelname="val2",basename="base\"v\\al\nue"} 0.23 1234567890 -# HELP name two-line\n doc str\\ing - - # HELP name2 doc str"ing 2 - # TYPE name2 gauge -name2{labelname="val2" ,basename = "basevalue2" } +Inf 54321 -name2{ labelname = "val1" , }-Inf -`, - out: []*dto.MetricFamily{ - &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("two-line\n doc str\\ing"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(math.NaN()), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("base\"v\\al\nue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(.23), - }, - TimestampMs: proto.Int64(1234567890), - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("name2"), - Help: proto.String("doc str\"ing 2"), - Type: dto.MetricType_GAUGE.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue2"), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(math.Inf(+1)), - }, - TimestampMs: proto.Int64(54321), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - }, - }, - // 3: The evil summary, mixed with other types and funny comments. - { - in: ` -# TYPE my_summary summary -my_summary{n1="val1",quantile="0.5"} 110 -decoy -1 -2 -my_summary{n1="val1",quantile="0.9"} 140 1 -my_summary_count{n1="val1"} 42 -# Latest timestamp wins in case of a summary. -my_summary_sum{n1="val1"} 4711 2 -fake_sum{n1="val1"} 2001 -# TYPE another_summary summary -another_summary_count{n2="val2",n1="val1"} 20 -my_summary_count{n2="val2",n1="val1"} 5 5 -another_summary{n1="val1",n2="val2",quantile=".3"} -1.2 -my_summary_sum{n1="val2"} 08 15 -my_summary{n1="val3", quantile="0.2"} 4711 - my_summary{n1="val1",n2="val2",quantile="-12.34",} NaN -# some -# funny comments -# HELP -# HELP -# HELP my_summary -# HELP my_summary -`, - out: []*dto.MetricFamily{ - &dto.MetricFamily{ - Name: proto.String("fake_sum"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(2001), - }, - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("decoy"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(-1), - }, - TimestampMs: proto.Int64(-2), - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("my_summary"), - Type: dto.MetricType_SUMMARY.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(42), - SampleSum: proto.Float64(4711), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.5), - Value: proto.Float64(110), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.9), - Value: proto.Float64(140), - }, - }, - }, - TimestampMs: proto.Int64(2), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n2"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(5), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(-12.34), - Value: proto.Float64(math.NaN()), - }, - }, - }, - TimestampMs: proto.Int64(5), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val2"), - }, - }, - Summary: &dto.Summary{ - SampleSum: proto.Float64(8), - }, - TimestampMs: proto.Int64(15), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val3"), - }, - }, - Summary: &dto.Summary{ - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.2), - Value: proto.Float64(4711), - }, - }, - }, - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("another_summary"), - Type: dto.MetricType_SUMMARY.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n2"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(20), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.3), - Value: proto.Float64(-1.2), - }, - }, - }, - }, - }, - }, - }, - }, - // 4: The histogram. - { - in: ` -# HELP request_duration_microseconds The response latency. -# TYPE request_duration_microseconds histogram -request_duration_microseconds_bucket{le="100"} 123 -request_duration_microseconds_bucket{le="120"} 412 -request_duration_microseconds_bucket{le="144"} 592 -request_duration_microseconds_bucket{le="172.8"} 1524 -request_duration_microseconds_bucket{le="+Inf"} 2693 -request_duration_microseconds_sum 1.7560473e+06 -request_duration_microseconds_count 2693 -`, - out: []*dto.MetricFamily{ - { - Name: proto.String("request_duration_microseconds"), - Help: proto.String("The response latency."), - Type: dto.MetricType_HISTOGRAM.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Histogram: &dto.Histogram{ - SampleCount: proto.Uint64(2693), - SampleSum: proto.Float64(1756047.3), - Bucket: []*dto.Bucket{ - &dto.Bucket{ - UpperBound: proto.Float64(100), - CumulativeCount: proto.Uint64(123), - }, - &dto.Bucket{ - UpperBound: proto.Float64(120), - CumulativeCount: proto.Uint64(412), - }, - &dto.Bucket{ - UpperBound: proto.Float64(144), - CumulativeCount: proto.Uint64(592), - }, - &dto.Bucket{ - UpperBound: proto.Float64(172.8), - CumulativeCount: proto.Uint64(1524), - }, - &dto.Bucket{ - UpperBound: proto.Float64(math.Inf(+1)), - CumulativeCount: proto.Uint64(2693), - }, - }, - }, - }, - }, - }, - }, - }, - } - - for i, scenario := range scenarios { - out, err := parser.TextToMetricFamilies(strings.NewReader(scenario.in)) - if err != nil { - t.Errorf("%d. error: %s", i, err) - continue - } - if expected, got := len(scenario.out), len(out); expected != got { - t.Errorf( - "%d. expected %d MetricFamilies, got %d", - i, expected, got, - ) - } - for _, expected := range scenario.out { - got, ok := out[expected.GetName()] - if !ok { - t.Errorf( - "%d. expected MetricFamily %q, found none", - i, expected.GetName(), - ) - continue - } - if expected.String() != got.String() { - t.Errorf( - "%d. expected MetricFamily %s, got %s", - i, expected, got, - ) - } - } - } -} - -func TestTextParse(t *testing.T) { - testTextParse(t) -} - -func BenchmarkTextParse(b *testing.B) { - for i := 0; i < b.N; i++ { - testTextParse(b) - } -} - -func testTextParseError(t testing.TB) { - var scenarios = []struct { - in string - err string - }{ - // 0: No new-line at end of input. - { - in: `bla 3.14`, - err: "EOF", - }, - // 1: Invalid escape sequence in label value. - { - in: `metric{label="\t"} 3.14`, - err: "text format parsing error in line 1: invalid escape sequence", - }, - // 2: Newline in label value. - { - in: ` -metric{label="new -line"} 3.14 -`, - err: `text format parsing error in line 2: label value "new" contains unescaped new-line`, - }, - // 3: - { - in: `metric{@="bla"} 3.14`, - err: "text format parsing error in line 1: invalid label name for metric", - }, - // 4: - { - in: `metric{__name__="bla"} 3.14`, - err: `text format parsing error in line 1: label name "__name__" is reserved`, - }, - // 5: - { - in: `metric{label+="bla"} 3.14`, - err: "text format parsing error in line 1: expected '=' after label name", - }, - // 6: - { - in: `metric{label=bla} 3.14`, - err: "text format parsing error in line 1: expected '\"' at start of label value", - }, - // 7: - { - in: ` -# TYPE metric summary -metric{quantile="bla"} 3.14 -`, - err: "text format parsing error in line 3: expected float as value for 'quantile' label", - }, - // 8: - { - in: `metric{label="bla"+} 3.14`, - err: "text format parsing error in line 1: unexpected end of label value", - }, - // 9: - { - in: `metric{label="bla"} 3.14 2.72 -`, - err: "text format parsing error in line 1: expected integer as timestamp", - }, - // 10: - { - in: `metric{label="bla"} 3.14 2 3 -`, - err: "text format parsing error in line 1: spurious string after timestamp", - }, - // 11: - { - in: `metric{label="bla"} blubb -`, - err: "text format parsing error in line 1: expected float as value", - }, - // 12: - { - in: ` -# HELP metric one -# HELP metric two -`, - err: "text format parsing error in line 3: second HELP line for metric name", - }, - // 13: - { - in: ` -# TYPE metric counter -# TYPE metric untyped -`, - err: `text format parsing error in line 3: second TYPE line for metric name "metric", or TYPE reported after samples`, - }, - // 14: - { - in: ` -metric 4.12 -# TYPE metric counter -`, - err: `text format parsing error in line 3: second TYPE line for metric name "metric", or TYPE reported after samples`, - }, - // 14: - { - in: ` -# TYPE metric bla -`, - err: "text format parsing error in line 2: unknown metric type", - }, - // 15: - { - in: ` -# TYPE met-ric -`, - err: "text format parsing error in line 2: invalid metric name in comment", - }, - // 16: - { - in: `@invalidmetric{label="bla"} 3.14 2`, - err: "text format parsing error in line 1: invalid metric name", - }, - // 17: - { - in: `{label="bla"} 3.14 2`, - err: "text format parsing error in line 1: invalid metric name", - }, - // 18: - { - in: ` -# TYPE metric histogram -metric_bucket{le="bla"} 3.14 -`, - err: "text format parsing error in line 3: expected float as value for 'le' label", - }, - } - - for i, scenario := range scenarios { - _, err := parser.TextToMetricFamilies(strings.NewReader(scenario.in)) - if err == nil { - t.Errorf("%d. expected error, got nil", i) - continue - } - if expected, got := scenario.err, err.Error(); strings.Index(got, expected) != 0 { - t.Errorf( - "%d. expected error starting with %q, got %q", - i, expected, got, - ) - } - } - -} - -func TestTextParseError(t *testing.T) { - testTextParseError(t) -} - -func BenchmarkParseError(b *testing.B) { - for i := 0; i < b.N; i++ { - testTextParseError(b) - } -} diff --git a/vendor/github.com/prometheus/common/model/BUILD b/vendor/github.com/prometheus/common/model/BUILD index e28a566b739b..3cfb2e5b3a6a 100644 --- a/vendor/github.com/prometheus/common/model/BUILD +++ b/vendor/github.com/prometheus/common/model/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -18,19 +18,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = [ - "labels_test.go", - "metric_test.go", - "signature_test.go", - "time_test.go", - "value_test.go", - ], - importpath = "github.com/prometheus/common/model", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/prometheus/common/model/labels_test.go b/vendor/github.com/prometheus/common/model/labels_test.go deleted file mode 100644 index ab17025c76aa..000000000000 --- a/vendor/github.com/prometheus/common/model/labels_test.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2013 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model - -import ( - "sort" - "testing" -) - -func testLabelNames(t testing.TB) { - var scenarios = []struct { - in LabelNames - out LabelNames - }{ - { - in: LabelNames{"ZZZ", "zzz"}, - out: LabelNames{"ZZZ", "zzz"}, - }, - { - in: LabelNames{"aaa", "AAA"}, - out: LabelNames{"AAA", "aaa"}, - }, - } - - for i, scenario := range scenarios { - sort.Sort(scenario.in) - - for j, expected := range scenario.out { - if expected != scenario.in[j] { - t.Errorf("%d.%d expected %s, got %s", i, j, expected, scenario.in[j]) - } - } - } -} - -func TestLabelNames(t *testing.T) { - testLabelNames(t) -} - -func BenchmarkLabelNames(b *testing.B) { - for i := 0; i < b.N; i++ { - testLabelNames(b) - } -} - -func testLabelValues(t testing.TB) { - var scenarios = []struct { - in LabelValues - out LabelValues - }{ - { - in: LabelValues{"ZZZ", "zzz"}, - out: LabelValues{"ZZZ", "zzz"}, - }, - { - in: LabelValues{"aaa", "AAA"}, - out: LabelValues{"AAA", "aaa"}, - }, - } - - for i, scenario := range scenarios { - sort.Sort(scenario.in) - - for j, expected := range scenario.out { - if expected != scenario.in[j] { - t.Errorf("%d.%d expected %s, got %s", i, j, expected, scenario.in[j]) - } - } - } -} - -func TestLabelValues(t *testing.T) { - testLabelValues(t) -} - -func BenchmarkLabelValues(b *testing.B) { - for i := 0; i < b.N; i++ { - testLabelValues(b) - } -} diff --git a/vendor/github.com/prometheus/common/model/metric_test.go b/vendor/github.com/prometheus/common/model/metric_test.go deleted file mode 100644 index 5c7cfceafe96..000000000000 --- a/vendor/github.com/prometheus/common/model/metric_test.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2013 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model - -import "testing" - -func testMetric(t testing.TB) { - var scenarios = []struct { - input LabelSet - fingerprint Fingerprint - fastFingerprint Fingerprint - }{ - { - input: LabelSet{}, - fingerprint: 14695981039346656037, - fastFingerprint: 14695981039346656037, - }, - { - input: LabelSet{ - "first_name": "electro", - "occupation": "robot", - "manufacturer": "westinghouse", - }, - fingerprint: 5911716720268894962, - fastFingerprint: 11310079640881077873, - }, - { - input: LabelSet{ - "x": "y", - }, - fingerprint: 8241431561484471700, - fastFingerprint: 13948396922932177635, - }, - { - input: LabelSet{ - "a": "bb", - "b": "c", - }, - fingerprint: 3016285359649981711, - fastFingerprint: 3198632812309449502, - }, - { - input: LabelSet{ - "a": "b", - "bb": "c", - }, - fingerprint: 7122421792099404749, - fastFingerprint: 5774953389407657638, - }, - } - - for i, scenario := range scenarios { - input := Metric(scenario.input) - - if scenario.fingerprint != input.Fingerprint() { - t.Errorf("%d. expected %d, got %d", i, scenario.fingerprint, input.Fingerprint()) - } - if scenario.fastFingerprint != input.FastFingerprint() { - t.Errorf("%d. expected %d, got %d", i, scenario.fastFingerprint, input.FastFingerprint()) - } - } -} - -func TestMetric(t *testing.T) { - testMetric(t) -} - -func BenchmarkMetric(b *testing.B) { - for i := 0; i < b.N; i++ { - testMetric(b) - } -} diff --git a/vendor/github.com/prometheus/common/model/signature_test.go b/vendor/github.com/prometheus/common/model/signature_test.go deleted file mode 100644 index d9c665f8c79e..000000000000 --- a/vendor/github.com/prometheus/common/model/signature_test.go +++ /dev/null @@ -1,304 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model - -import ( - "runtime" - "sync" - "testing" -) - -func TestLabelsToSignature(t *testing.T) { - var scenarios = []struct { - in map[string]string - out uint64 - }{ - { - in: map[string]string{}, - out: 14695981039346656037, - }, - { - in: map[string]string{"name": "garland, briggs", "fear": "love is not enough"}, - out: 5799056148416392346, - }, - } - - for i, scenario := range scenarios { - actual := LabelsToSignature(scenario.in) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestMetricToFingerprint(t *testing.T) { - var scenarios = []struct { - in LabelSet - out Fingerprint - }{ - { - in: LabelSet{}, - out: 14695981039346656037, - }, - { - in: LabelSet{"name": "garland, briggs", "fear": "love is not enough"}, - out: 5799056148416392346, - }, - } - - for i, scenario := range scenarios { - actual := labelSetToFingerprint(scenario.in) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestMetricToFastFingerprint(t *testing.T) { - var scenarios = []struct { - in LabelSet - out Fingerprint - }{ - { - in: LabelSet{}, - out: 14695981039346656037, - }, - { - in: LabelSet{"name": "garland, briggs", "fear": "love is not enough"}, - out: 12952432476264840823, - }, - } - - for i, scenario := range scenarios { - actual := labelSetToFastFingerprint(scenario.in) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestSignatureForLabels(t *testing.T) { - var scenarios = []struct { - in Metric - labels LabelNames - out uint64 - }{ - { - in: Metric{}, - labels: nil, - out: 14695981039346656037, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: LabelNames{"fear", "name"}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough", "foo": "bar"}, - labels: LabelNames{"fear", "name"}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: LabelNames{}, - out: 14695981039346656037, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: nil, - out: 14695981039346656037, - }, - } - - for i, scenario := range scenarios { - actual := SignatureForLabels(scenario.in, scenario.labels...) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestSignatureWithoutLabels(t *testing.T) { - var scenarios = []struct { - in Metric - labels map[LabelName]struct{} - out uint64 - }{ - { - in: Metric{}, - labels: nil, - out: 14695981039346656037, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: map[LabelName]struct{}{"fear": struct{}{}, "name": struct{}{}}, - out: 14695981039346656037, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough", "foo": "bar"}, - labels: map[LabelName]struct{}{"foo": struct{}{}}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: map[LabelName]struct{}{}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: nil, - out: 5799056148416392346, - }, - } - - for i, scenario := range scenarios { - actual := SignatureWithoutLabels(scenario.in, scenario.labels) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func benchmarkLabelToSignature(b *testing.B, l map[string]string, e uint64) { - for i := 0; i < b.N; i++ { - if a := LabelsToSignature(l); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, l, a) - } - } -} - -func BenchmarkLabelToSignatureScalar(b *testing.B) { - benchmarkLabelToSignature(b, nil, 14695981039346656037) -} - -func BenchmarkLabelToSignatureSingle(b *testing.B) { - benchmarkLabelToSignature(b, map[string]string{"first-label": "first-label-value"}, 5146282821936882169) -} - -func BenchmarkLabelToSignatureDouble(b *testing.B) { - benchmarkLabelToSignature(b, map[string]string{"first-label": "first-label-value", "second-label": "second-label-value"}, 3195800080984914717) -} - -func BenchmarkLabelToSignatureTriple(b *testing.B) { - benchmarkLabelToSignature(b, map[string]string{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 13843036195897128121) -} - -func benchmarkMetricToFingerprint(b *testing.B, ls LabelSet, e Fingerprint) { - for i := 0; i < b.N; i++ { - if a := labelSetToFingerprint(ls); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, ls, a) - } - } -} - -func BenchmarkMetricToFingerprintScalar(b *testing.B) { - benchmarkMetricToFingerprint(b, nil, 14695981039346656037) -} - -func BenchmarkMetricToFingerprintSingle(b *testing.B) { - benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value"}, 5146282821936882169) -} - -func BenchmarkMetricToFingerprintDouble(b *testing.B) { - benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value"}, 3195800080984914717) -} - -func BenchmarkMetricToFingerprintTriple(b *testing.B) { - benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 13843036195897128121) -} - -func benchmarkMetricToFastFingerprint(b *testing.B, ls LabelSet, e Fingerprint) { - for i := 0; i < b.N; i++ { - if a := labelSetToFastFingerprint(ls); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, ls, a) - } - } -} - -func BenchmarkMetricToFastFingerprintScalar(b *testing.B) { - benchmarkMetricToFastFingerprint(b, nil, 14695981039346656037) -} - -func BenchmarkMetricToFastFingerprintSingle(b *testing.B) { - benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value"}, 5147259542624943964) -} - -func BenchmarkMetricToFastFingerprintDouble(b *testing.B) { - benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value"}, 18269973311206963528) -} - -func BenchmarkMetricToFastFingerprintTriple(b *testing.B) { - benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676) -} - -func BenchmarkEmptyLabelSignature(b *testing.B) { - input := []map[string]string{nil, {}} - - var ms runtime.MemStats - runtime.ReadMemStats(&ms) - - alloc := ms.Alloc - - for _, labels := range input { - LabelsToSignature(labels) - } - - runtime.ReadMemStats(&ms) - - if got := ms.Alloc; alloc != got { - b.Fatal("expected LabelsToSignature with empty labels not to perform allocations") - } -} - -func benchmarkMetricToFastFingerprintConc(b *testing.B, ls LabelSet, e Fingerprint, concLevel int) { - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - for i := 0; i < concLevel; i++ { - go func() { - start.Wait() - for j := b.N / concLevel; j >= 0; j-- { - if a := labelSetToFastFingerprint(ls); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, ls, a) - } - } - end.Done() - }() - } - b.ResetTimer() - start.Done() - end.Wait() -} - -func BenchmarkMetricToFastFingerprintTripleConc1(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 1) -} - -func BenchmarkMetricToFastFingerprintTripleConc2(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 2) -} - -func BenchmarkMetricToFastFingerprintTripleConc4(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 4) -} - -func BenchmarkMetricToFastFingerprintTripleConc8(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 8) -} diff --git a/vendor/github.com/prometheus/common/model/time_test.go b/vendor/github.com/prometheus/common/model/time_test.go deleted file mode 100644 index 9013a62775b1..000000000000 --- a/vendor/github.com/prometheus/common/model/time_test.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2013 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model - -import ( - "testing" - "time" -) - -func TestComparators(t *testing.T) { - t1a := TimeFromUnix(0) - t1b := TimeFromUnix(0) - t2 := TimeFromUnix(2*second - 1) - - if !t1a.Equal(t1b) { - t.Fatalf("Expected %s to be equal to %s", t1a, t1b) - } - if t1a.Equal(t2) { - t.Fatalf("Expected %s to not be equal to %s", t1a, t2) - } - - if !t1a.Before(t2) { - t.Fatalf("Expected %s to be before %s", t1a, t2) - } - if t1a.Before(t1b) { - t.Fatalf("Expected %s to not be before %s", t1a, t1b) - } - - if !t2.After(t1a) { - t.Fatalf("Expected %s to be after %s", t2, t1a) - } - if t1b.After(t1a) { - t.Fatalf("Expected %s to not be after %s", t1b, t1a) - } -} - -func TestTimeConversions(t *testing.T) { - unixSecs := int64(1136239445) - unixNsecs := int64(123456789) - unixNano := unixSecs*1e9 + unixNsecs - - t1 := time.Unix(unixSecs, unixNsecs-unixNsecs%nanosPerTick) - t2 := time.Unix(unixSecs, unixNsecs) - - ts := TimeFromUnixNano(unixNano) - if !ts.Time().Equal(t1) { - t.Fatalf("Expected %s, got %s", t1, ts.Time()) - } - - // Test available precision. - ts = TimeFromUnixNano(t2.UnixNano()) - if !ts.Time().Equal(t1) { - t.Fatalf("Expected %s, got %s", t1, ts.Time()) - } - - if ts.UnixNano() != unixNano-unixNano%nanosPerTick { - t.Fatalf("Expected %d, got %d", unixNano, ts.UnixNano()) - } -} - -func TestDuration(t *testing.T) { - duration := time.Second + time.Minute + time.Hour - goTime := time.Unix(1136239445, 0) - - ts := TimeFromUnix(goTime.Unix()) - if !goTime.Add(duration).Equal(ts.Add(duration).Time()) { - t.Fatalf("Expected %s to be equal to %s", goTime.Add(duration), ts.Add(duration)) - } - - earlier := ts.Add(-duration) - delta := ts.Sub(earlier) - if delta != duration { - t.Fatalf("Expected %s to be equal to %s", delta, duration) - } -} diff --git a/vendor/github.com/prometheus/common/model/value_test.go b/vendor/github.com/prometheus/common/model/value_test.go deleted file mode 100644 index 2e9c7eb09d1a..000000000000 --- a/vendor/github.com/prometheus/common/model/value_test.go +++ /dev/null @@ -1,362 +0,0 @@ -// Copyright 2013 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model - -import ( - "encoding/json" - "math" - "reflect" - "sort" - "testing" -) - -func TestSamplePairJSON(t *testing.T) { - input := []struct { - plain string - value SamplePair - }{ - { - plain: `[1234.567,"123.1"]`, - value: SamplePair{ - Value: 123.1, - Timestamp: 1234567, - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sp SamplePair - err = json.Unmarshal(b, &sp) - if err != nil { - t.Error(err) - continue - } - - if sp != test.value { - t.Errorf("decoding error: expected %v, got %v", test.value, sp) - } - } -} - -func TestSampleJSON(t *testing.T) { - input := []struct { - plain string - value Sample - }{ - { - plain: `{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]}`, - value: Sample{ - Metric: Metric{ - MetricNameLabel: "test_metric", - }, - Value: 123.1, - Timestamp: 1234567, - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sv Sample - err = json.Unmarshal(b, &sv) - if err != nil { - t.Error(err) - continue - } - - if !reflect.DeepEqual(sv, test.value) { - t.Errorf("decoding error: expected %v, got %v", test.value, sv) - } - } -} - -func TestVectorJSON(t *testing.T) { - input := []struct { - plain string - value Vector - }{ - { - plain: `[]`, - value: Vector{}, - }, - { - plain: `[{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]}]`, - value: Vector{&Sample{ - Metric: Metric{ - MetricNameLabel: "test_metric", - }, - Value: 123.1, - Timestamp: 1234567, - }}, - }, - { - plain: `[{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]},{"metric":{"foo":"bar"},"value":[1.234,"+Inf"]}]`, - value: Vector{ - &Sample{ - Metric: Metric{ - MetricNameLabel: "test_metric", - }, - Value: 123.1, - Timestamp: 1234567, - }, - &Sample{ - Metric: Metric{ - "foo": "bar", - }, - Value: SampleValue(math.Inf(1)), - Timestamp: 1234, - }, - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var vec Vector - err = json.Unmarshal(b, &vec) - if err != nil { - t.Error(err) - continue - } - - if !reflect.DeepEqual(vec, test.value) { - t.Errorf("decoding error: expected %v, got %v", test.value, vec) - } - } -} - -func TestScalarJSON(t *testing.T) { - input := []struct { - plain string - value Scalar - }{ - { - plain: `[123.456,"456"]`, - value: Scalar{ - Timestamp: 123456, - Value: 456, - }, - }, - { - plain: `[123123.456,"+Inf"]`, - value: Scalar{ - Timestamp: 123123456, - Value: SampleValue(math.Inf(1)), - }, - }, - { - plain: `[123123.456,"-Inf"]`, - value: Scalar{ - Timestamp: 123123456, - Value: SampleValue(math.Inf(-1)), - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sv Scalar - err = json.Unmarshal(b, &sv) - if err != nil { - t.Error(err) - continue - } - - if sv != test.value { - t.Errorf("decoding error: expected %v, got %v", test.value, sv) - } - } -} - -func TestStringJSON(t *testing.T) { - input := []struct { - plain string - value String - }{ - { - plain: `[123.456,"test"]`, - value: String{ - Timestamp: 123456, - Value: "test", - }, - }, - { - plain: `[123123.456,"台北"]`, - value: String{ - Timestamp: 123123456, - Value: "台北", - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sv String - err = json.Unmarshal(b, &sv) - if err != nil { - t.Error(err) - continue - } - - if sv != test.value { - t.Errorf("decoding error: expected %v, got %v", test.value, sv) - } - } -} - -func TestVectorSort(t *testing.T) { - input := Vector{ - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 2, - }, - } - - expected := Vector{ - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 2, - }, - } - - sort.Sort(input) - - for i, actual := range input { - actualFp := actual.Metric.Fingerprint() - expectedFp := expected[i].Metric.Fingerprint() - - if actualFp != expectedFp { - t.Fatalf("%d. Incorrect fingerprint. Got %s; want %s", i, actualFp.String(), expectedFp.String()) - } - - if actual.Timestamp != expected[i].Timestamp { - t.Fatalf("%d. Incorrect timestamp. Got %s; want %s", i, actual.Timestamp, expected[i].Timestamp) - } - } -} diff --git a/vendor/github.com/prometheus/procfs/BUILD b/vendor/github.com/prometheus/procfs/BUILD index dfe6ad5ba4cb..4e047cf361d1 100644 --- a/vendor/github.com/prometheus/procfs/BUILD +++ b/vendor/github.com/prometheus/procfs/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -17,22 +17,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = [ - "fs_test.go", - "ipvs_test.go", - "mdstat_test.go", - "proc_io_test.go", - "proc_limits_test.go", - "proc_stat_test.go", - "proc_test.go", - "stat_test.go", - ], - importpath = "github.com/prometheus/procfs", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/prometheus/procfs/fs_test.go b/vendor/github.com/prometheus/procfs/fs_test.go deleted file mode 100644 index 91f1c6c97635..000000000000 --- a/vendor/github.com/prometheus/procfs/fs_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package procfs - -import "testing" - -func TestNewFS(t *testing.T) { - if _, err := NewFS("foobar"); err == nil { - t.Error("want NewFS to fail for non-existing mount point") - } - - if _, err := NewFS("procfs.go"); err == nil { - t.Error("want NewFS to fail if mount point is not a directory") - } -} diff --git a/vendor/github.com/prometheus/procfs/ipvs_test.go b/vendor/github.com/prometheus/procfs/ipvs_test.go deleted file mode 100644 index 6036cde84352..000000000000 --- a/vendor/github.com/prometheus/procfs/ipvs_test.go +++ /dev/null @@ -1,196 +0,0 @@ -package procfs - -import ( - "net" - "testing" -) - -var ( - expectedIPVSStats = IPVSStats{ - Connections: 23765872, - IncomingPackets: 3811989221, - OutgoingPackets: 0, - IncomingBytes: 89991519156915, - OutgoingBytes: 0, - } - expectedIPVSBackendStatuses = []IPVSBackendStatus{ - IPVSBackendStatus{ - LocalAddress: net.ParseIP("192.168.0.22"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.82.22"), - RemotePort: 3306, - Proto: "TCP", - Weight: 100, - ActiveConn: 248, - InactConn: 2, - }, - IPVSBackendStatus{ - LocalAddress: net.ParseIP("192.168.0.22"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.83.24"), - RemotePort: 3306, - Proto: "TCP", - Weight: 100, - ActiveConn: 248, - InactConn: 2, - }, - IPVSBackendStatus{ - LocalAddress: net.ParseIP("192.168.0.22"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.83.21"), - RemotePort: 3306, - Proto: "TCP", - Weight: 100, - ActiveConn: 248, - InactConn: 1, - }, - IPVSBackendStatus{ - LocalAddress: net.ParseIP("192.168.0.57"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.84.22"), - RemotePort: 3306, - Proto: "TCP", - Weight: 0, - ActiveConn: 0, - InactConn: 0, - }, - IPVSBackendStatus{ - LocalAddress: net.ParseIP("192.168.0.57"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.82.21"), - RemotePort: 3306, - Proto: "TCP", - Weight: 100, - ActiveConn: 1499, - InactConn: 0, - }, - IPVSBackendStatus{ - LocalAddress: net.ParseIP("192.168.0.57"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.50.21"), - RemotePort: 3306, - Proto: "TCP", - Weight: 100, - ActiveConn: 1498, - InactConn: 0, - }, - IPVSBackendStatus{ - LocalAddress: net.ParseIP("192.168.0.55"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.50.26"), - RemotePort: 3306, - Proto: "TCP", - Weight: 0, - ActiveConn: 0, - InactConn: 0, - }, - IPVSBackendStatus{ - LocalAddress: net.ParseIP("192.168.0.55"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.49.32"), - RemotePort: 3306, - Proto: "TCP", - Weight: 100, - ActiveConn: 0, - InactConn: 0, - }, - } -) - -func TestIPVSStats(t *testing.T) { - fs, err := NewFS("fixtures") - if err != nil { - t.Fatal(err) - } - stats, err := fs.NewIPVSStats() - if err != nil { - t.Fatal(err) - } - - if stats != expectedIPVSStats { - t.Errorf("want %+v, got %+v", expectedIPVSStats, stats) - } -} - -func TestParseIPPort(t *testing.T) { - ip := net.ParseIP("192.168.0.22") - port := uint16(3306) - - gotIP, gotPort, err := parseIPPort("C0A80016:0CEA") - if err != nil { - t.Fatal(err) - } - if !(gotIP.Equal(ip) && port == gotPort) { - t.Errorf("want %s:%d, got %s:%d", ip, port, gotIP, gotPort) - } -} - -func TestParseIPPortInvalid(t *testing.T) { - testcases := []string{ - "", - "C0A80016", - "C0A800:1234", - "FOOBARBA:1234", - "C0A80016:0CEA:1234", - } - - for _, s := range testcases { - ip, port, err := parseIPPort(s) - if ip != nil || port != uint16(0) || err == nil { - t.Errorf("Expected error for input %s, got ip = %s, port = %v, err = %v", s, ip, port, err) - } - } -} - -func TestParseIPPortIPv6(t *testing.T) { - ip := net.ParseIP("dead:beef::1") - port := uint16(8080) - - gotIP, gotPort, err := parseIPPort("DEADBEEF000000000000000000000001:1F90") - if err != nil { - t.Fatal(err) - } - if !(gotIP.Equal(ip) && port == gotPort) { - t.Errorf("want %s:%d, got %s:%d", ip, port, gotIP, gotPort) - } - -} - -func TestIPVSBackendStatus(t *testing.T) { - fs, err := NewFS("fixtures") - if err != nil { - t.Fatal(err) - } - - backendStats, err := fs.NewIPVSBackendStatus() - if err != nil { - t.Fatal(err) - } - - for idx, expect := range expectedIPVSBackendStatuses { - if !backendStats[idx].LocalAddress.Equal(expect.LocalAddress) { - t.Errorf("expected LocalAddress %s, got %s", expect.LocalAddress, backendStats[idx].LocalAddress) - } - if backendStats[idx].LocalPort != expect.LocalPort { - t.Errorf("expected LocalPort %d, got %d", expect.LocalPort, backendStats[idx].LocalPort) - } - if !backendStats[idx].RemoteAddress.Equal(expect.RemoteAddress) { - t.Errorf("expected RemoteAddress %s, got %s", expect.RemoteAddress, backendStats[idx].RemoteAddress) - } - if backendStats[idx].RemotePort != expect.RemotePort { - t.Errorf("expected RemotePort %d, got %d", expect.RemotePort, backendStats[idx].RemotePort) - } - if backendStats[idx].Proto != expect.Proto { - t.Errorf("expected Proto %s, got %s", expect.Proto, backendStats[idx].Proto) - } - if backendStats[idx].Weight != expect.Weight { - t.Errorf("expected Weight %d, got %d", expect.Weight, backendStats[idx].Weight) - } - if backendStats[idx].ActiveConn != expect.ActiveConn { - t.Errorf("expected ActiveConn %d, got %d", expect.ActiveConn, backendStats[idx].ActiveConn) - } - if backendStats[idx].InactConn != expect.InactConn { - t.Errorf("expected InactConn %d, got %d", expect.InactConn, backendStats[idx].InactConn) - } - } -} diff --git a/vendor/github.com/prometheus/procfs/mdstat_test.go b/vendor/github.com/prometheus/procfs/mdstat_test.go deleted file mode 100644 index 7b9a3a5f5fee..000000000000 --- a/vendor/github.com/prometheus/procfs/mdstat_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package procfs - -import ( - "testing" -) - -func TestMDStat(t *testing.T) { - fs := FS("fixtures") - mdStates, err := fs.ParseMDStat() - if err != nil { - t.Fatalf("parsing of reference-file failed entirely: %s", err) - } - - refs := map[string]MDStat{ - "md3": MDStat{"md3", "active", 8, 8, 5853468288, 5853468288}, - "md127": MDStat{"md127", "active", 2, 2, 312319552, 312319552}, - "md0": MDStat{"md0", "active", 2, 2, 248896, 248896}, - "md4": MDStat{"md4", "inactive", 2, 2, 4883648, 4883648}, - "md6": MDStat{"md6", "active", 1, 2, 195310144, 16775552}, - "md8": MDStat{"md8", "active", 2, 2, 195310144, 16775552}, - "md7": MDStat{"md7", "active", 3, 4, 7813735424, 7813735424}, - } - - for _, md := range mdStates { - if md != refs[md.Name] { - t.Errorf("failed parsing md-device %s correctly: want %v, got %v", md.Name, refs[md.Name], md) - } - } - - if want, have := len(refs), len(mdStates); want != have { - t.Errorf("want %d parsed md-devices, have %d", want, have) - } -} diff --git a/vendor/github.com/prometheus/procfs/proc_io_test.go b/vendor/github.com/prometheus/procfs/proc_io_test.go deleted file mode 100644 index 5ef524d8e0f8..000000000000 --- a/vendor/github.com/prometheus/procfs/proc_io_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package procfs - -import "testing" - -func TestProcIO(t *testing.T) { - fs, err := NewFS("fixtures") - if err != nil { - t.Fatal(err) - } - - p, err := fs.NewProc(26231) - if err != nil { - t.Fatal(err) - } - - s, err := p.NewIO() - if err != nil { - t.Fatal(err) - } - - for _, test := range []struct { - name string - want uint64 - got uint64 - }{ - {name: "RChar", want: 750339, got: s.RChar}, - {name: "WChar", want: 818609, got: s.WChar}, - {name: "SyscR", want: 7405, got: s.SyscR}, - {name: "SyscW", want: 5245, got: s.SyscW}, - {name: "ReadBytes", want: 1024, got: s.ReadBytes}, - {name: "WriteBytes", want: 2048, got: s.WriteBytes}, - } { - if test.want != test.got { - t.Errorf("want %s %d, got %d", test.name, test.want, test.got) - } - } - - for _, test := range []struct { - name string - want int64 - got int64 - }{ - {name: "CancelledWriteBytes", want: -1024, got: s.CancelledWriteBytes}, - } { - if test.want != test.got { - t.Errorf("want %s %d, got %d", test.name, test.want, test.got) - } - } -} diff --git a/vendor/github.com/prometheus/procfs/proc_limits_test.go b/vendor/github.com/prometheus/procfs/proc_limits_test.go deleted file mode 100644 index ca7a254da758..000000000000 --- a/vendor/github.com/prometheus/procfs/proc_limits_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package procfs - -import "testing" - -func TestNewLimits(t *testing.T) { - fs, err := NewFS("fixtures") - if err != nil { - t.Fatal(err) - } - - p, err := fs.NewProc(26231) - if err != nil { - t.Fatal(err) - } - - l, err := p.NewLimits() - if err != nil { - t.Fatal(err) - } - - for _, test := range []struct { - name string - want int - got int - }{ - {name: "cpu time", want: -1, got: l.CPUTime}, - {name: "open files", want: 2048, got: l.OpenFiles}, - {name: "msgqueue size", want: 819200, got: l.MsqqueueSize}, - {name: "nice priority", want: 0, got: l.NicePriority}, - {name: "address space", want: -1, got: l.AddressSpace}, - } { - if test.want != test.got { - t.Errorf("want %s %d, got %d", test.name, test.want, test.got) - } - } -} diff --git a/vendor/github.com/prometheus/procfs/proc_stat_test.go b/vendor/github.com/prometheus/procfs/proc_stat_test.go deleted file mode 100644 index e4d5cacfa4bf..000000000000 --- a/vendor/github.com/prometheus/procfs/proc_stat_test.go +++ /dev/null @@ -1,112 +0,0 @@ -package procfs - -import "testing" - -func TestProcStat(t *testing.T) { - fs, err := NewFS("fixtures") - if err != nil { - t.Fatal(err) - } - - p, err := fs.NewProc(26231) - if err != nil { - t.Fatal(err) - } - - s, err := p.NewStat() - if err != nil { - t.Fatal(err) - } - - for _, test := range []struct { - name string - want int - got int - }{ - {name: "pid", want: 26231, got: s.PID}, - {name: "user time", want: 1677, got: int(s.UTime)}, - {name: "system time", want: 44, got: int(s.STime)}, - {name: "start time", want: 82375, got: int(s.Starttime)}, - {name: "virtual memory size", want: 56274944, got: s.VSize}, - {name: "resident set size", want: 1981, got: s.RSS}, - } { - if test.want != test.got { - t.Errorf("want %s %d, got %d", test.name, test.want, test.got) - } - } -} - -func TestProcStatComm(t *testing.T) { - s1, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - if want, got := "vim", s1.Comm; want != got { - t.Errorf("want comm %s, got %s", want, got) - } - - s2, err := testProcStat(584) - if err != nil { - t.Fatal(err) - } - if want, got := "(a b ) ( c d) ", s2.Comm; want != got { - t.Errorf("want comm %s, got %s", want, got) - } -} - -func TestProcStatVirtualMemory(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - if want, got := 56274944, s.VirtualMemory(); want != got { - t.Errorf("want virtual memory %d, got %d", want, got) - } -} - -func TestProcStatResidentMemory(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - if want, got := 1981*4096, s.ResidentMemory(); want != got { - t.Errorf("want resident memory %d, got %d", want, got) - } -} - -func TestProcStatStartTime(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - time, err := s.StartTime() - if err != nil { - t.Fatal(err) - } - if want, got := 1418184099.75, time; want != got { - t.Errorf("want start time %f, got %f", want, got) - } -} - -func TestProcStatCPUTime(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - if want, got := 17.21, s.CPUTime(); want != got { - t.Errorf("want cpu time %f, got %f", want, got) - } -} - -func testProcStat(pid int) (ProcStat, error) { - p, err := testProcess(pid) - if err != nil { - return ProcStat{}, err - } - - return p.NewStat() -} diff --git a/vendor/github.com/prometheus/procfs/proc_test.go b/vendor/github.com/prometheus/procfs/proc_test.go deleted file mode 100644 index 4197282ca84d..000000000000 --- a/vendor/github.com/prometheus/procfs/proc_test.go +++ /dev/null @@ -1,146 +0,0 @@ -package procfs - -import ( - "reflect" - "sort" - "testing" -) - -func TestSelf(t *testing.T) { - fs := FS("fixtures") - - p1, err := fs.NewProc(26231) - if err != nil { - t.Fatal(err) - } - p2, err := fs.Self() - if err != nil { - t.Fatal(err) - } - - if !reflect.DeepEqual(p1, p2) { - t.Errorf("want process %v to equal %v", p1, p2) - } -} - -func TestAllProcs(t *testing.T) { - procs, err := FS("fixtures").AllProcs() - if err != nil { - t.Fatal(err) - } - sort.Sort(procs) - for i, p := range []*Proc{{PID: 584}, {PID: 26231}} { - if want, got := p.PID, procs[i].PID; want != got { - t.Errorf("want processes %d, got %d", want, got) - } - } -} - -func TestCmdLine(t *testing.T) { - for _, tt := range []struct { - process int - want []string - }{ - {process: 26231, want: []string{"vim", "test.go", "+10"}}, - {process: 26232, want: []string{}}, - } { - p1, err := testProcess(tt.process) - if err != nil { - t.Fatal(err) - } - c1, err := p1.CmdLine() - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(tt.want, c1) { - t.Errorf("want cmdline %v, got %v", tt.want, c1) - } - } -} - -func TestExecutable(t *testing.T) { - for _, tt := range []struct { - process int - want string - }{ - {process: 26231, want: "/usr/bin/vim"}, - {process: 26232, want: ""}, - } { - p, err := testProcess(tt.process) - if err != nil { - t.Fatal(err) - } - exe, err := p.Executable() - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(tt.want, exe) { - t.Errorf("want absolute path to cmdline %v, got %v", tt.want, exe) - } - } -} - -func TestFileDescriptors(t *testing.T) { - p1, err := testProcess(26231) - if err != nil { - t.Fatal(err) - } - fds, err := p1.FileDescriptors() - if err != nil { - t.Fatal(err) - } - sort.Sort(byUintptr(fds)) - if want := []uintptr{0, 1, 2, 3, 10}; !reflect.DeepEqual(want, fds) { - t.Errorf("want fds %v, got %v", want, fds) - } -} - -func TestFileDescriptorTargets(t *testing.T) { - p1, err := testProcess(26231) - if err != nil { - t.Fatal(err) - } - fds, err := p1.FileDescriptorTargets() - if err != nil { - t.Fatal(err) - } - sort.Strings(fds) - var want = []string{ - "../../symlinktargets/abc", - "../../symlinktargets/def", - "../../symlinktargets/ghi", - "../../symlinktargets/uvw", - "../../symlinktargets/xyz", - } - if !reflect.DeepEqual(want, fds) { - t.Errorf("want fds %v, got %v", want, fds) - } -} - -func TestFileDescriptorsLen(t *testing.T) { - p1, err := testProcess(26231) - if err != nil { - t.Fatal(err) - } - l, err := p1.FileDescriptorsLen() - if err != nil { - t.Fatal(err) - } - if want, got := 5, l; want != got { - t.Errorf("want fds %d, got %d", want, got) - } -} - -func testProcess(pid int) (Proc, error) { - fs, err := NewFS("fixtures") - if err != nil { - return Proc{}, err - } - return fs.NewProc(pid) -} - -type byUintptr []uintptr - -func (a byUintptr) Len() int { return len(a) } -func (a byUintptr) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byUintptr) Less(i, j int) bool { return a[i] < a[j] } diff --git a/vendor/github.com/prometheus/procfs/stat_test.go b/vendor/github.com/prometheus/procfs/stat_test.go deleted file mode 100644 index 24b5d61f8e91..000000000000 --- a/vendor/github.com/prometheus/procfs/stat_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package procfs - -import "testing" - -func TestStat(t *testing.T) { - fs, err := NewFS("fixtures") - if err != nil { - t.Fatal(err) - } - - s, err := fs.NewStat() - if err != nil { - t.Fatal(err) - } - - if want, got := int64(1418183276), s.BootTime; want != got { - t.Errorf("want boot time %d, got %d", want, got) - } -} diff --git a/vendor/github.com/robfig/cron/BUILD b/vendor/github.com/robfig/cron/BUILD index da63d8157a8a..e33d33971502 100644 --- a/vendor/github.com/robfig/cron/BUILD +++ b/vendor/github.com/robfig/cron/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -13,18 +13,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = [ - "constantdelay_test.go", - "cron_test.go", - "parser_test.go", - "spec_test.go", - ], - importpath = "github.com/robfig/cron", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/robfig/cron/constantdelay_test.go b/vendor/github.com/robfig/cron/constantdelay_test.go deleted file mode 100644 index f43a58ad260e..000000000000 --- a/vendor/github.com/robfig/cron/constantdelay_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package cron - -import ( - "testing" - "time" -) - -func TestConstantDelayNext(t *testing.T) { - tests := []struct { - time string - delay time.Duration - expected string - }{ - // Simple cases - {"Mon Jul 9 14:45 2012", 15*time.Minute + 50*time.Nanosecond, "Mon Jul 9 15:00 2012"}, - {"Mon Jul 9 14:59 2012", 15 * time.Minute, "Mon Jul 9 15:14 2012"}, - {"Mon Jul 9 14:59:59 2012", 15 * time.Minute, "Mon Jul 9 15:14:59 2012"}, - - // Wrap around hours - {"Mon Jul 9 15:45 2012", 35 * time.Minute, "Mon Jul 9 16:20 2012"}, - - // Wrap around days - {"Mon Jul 9 23:46 2012", 14 * time.Minute, "Tue Jul 10 00:00 2012"}, - {"Mon Jul 9 23:45 2012", 35 * time.Minute, "Tue Jul 10 00:20 2012"}, - {"Mon Jul 9 23:35:51 2012", 44*time.Minute + 24*time.Second, "Tue Jul 10 00:20:15 2012"}, - {"Mon Jul 9 23:35:51 2012", 25*time.Hour + 44*time.Minute + 24*time.Second, "Thu Jul 11 01:20:15 2012"}, - - // Wrap around months - {"Mon Jul 9 23:35 2012", 91*24*time.Hour + 25*time.Minute, "Thu Oct 9 00:00 2012"}, - - // Wrap around minute, hour, day, month, and year - {"Mon Dec 31 23:59:45 2012", 15 * time.Second, "Tue Jan 1 00:00:00 2013"}, - - // Round to nearest second on the delay - {"Mon Jul 9 14:45 2012", 15*time.Minute + 50*time.Nanosecond, "Mon Jul 9 15:00 2012"}, - - // Round up to 1 second if the duration is less. - {"Mon Jul 9 14:45:00 2012", 15 * time.Millisecond, "Mon Jul 9 14:45:01 2012"}, - - // Round to nearest second when calculating the next time. - {"Mon Jul 9 14:45:00.005 2012", 15 * time.Minute, "Mon Jul 9 15:00 2012"}, - - // Round to nearest second for both. - {"Mon Jul 9 14:45:00.005 2012", 15*time.Minute + 50*time.Nanosecond, "Mon Jul 9 15:00 2012"}, - } - - for _, c := range tests { - actual := Every(c.delay).Next(getTime(c.time)) - expected := getTime(c.expected) - if actual != expected { - t.Errorf("%s, \"%s\": (expected) %v != %v (actual)", c.time, c.delay, expected, actual) - } - } -} diff --git a/vendor/github.com/robfig/cron/cron_test.go b/vendor/github.com/robfig/cron/cron_test.go deleted file mode 100644 index 06dfea3aa7ae..000000000000 --- a/vendor/github.com/robfig/cron/cron_test.go +++ /dev/null @@ -1,296 +0,0 @@ -package cron - -import ( - "fmt" - "sync" - "testing" - "time" -) - -// Many tests schedule a job for every second, and then wait at most a second -// for it to run. This amount is just slightly larger than 1 second to -// compensate for a few milliseconds of runtime. -const ONE_SECOND = 1*time.Second + 10*time.Millisecond - -// Start and stop cron with no entries. -func TestNoEntries(t *testing.T) { - cron := New() - cron.Start() - - select { - case <-time.After(ONE_SECOND): - t.FailNow() - case <-stop(cron): - } -} - -// Start, stop, then add an entry. Verify entry doesn't run. -func TestStopCausesJobsToNotRun(t *testing.T) { - wg := &sync.WaitGroup{} - wg.Add(1) - - cron := New() - cron.Start() - cron.Stop() - cron.AddFunc("* * * * * ?", func() { wg.Done() }) - - select { - case <-time.After(ONE_SECOND): - // No job ran! - case <-wait(wg): - t.FailNow() - } -} - -// Add a job, start cron, expect it runs. -func TestAddBeforeRunning(t *testing.T) { - wg := &sync.WaitGroup{} - wg.Add(1) - - cron := New() - cron.AddFunc("* * * * * ?", func() { wg.Done() }) - cron.Start() - defer cron.Stop() - - // Give cron 2 seconds to run our job (which is always activated). - select { - case <-time.After(ONE_SECOND): - t.FailNow() - case <-wait(wg): - } -} - -// Start cron, add a job, expect it runs. -func TestAddWhileRunning(t *testing.T) { - wg := &sync.WaitGroup{} - wg.Add(1) - - cron := New() - cron.Start() - defer cron.Stop() - cron.AddFunc("* * * * * ?", func() { wg.Done() }) - - select { - case <-time.After(ONE_SECOND): - t.FailNow() - case <-wait(wg): - } -} - -// Add a job, remove a job, start cron, expect nothing runs. -func TestRemoveBeforeRunning(t *testing.T) { - wg := &sync.WaitGroup{} - wg.Add(1) - - cron := New() - id, _ := cron.AddFunc("* * * * * ?", func() { wg.Done() }) - cron.Remove(id) - cron.Start() - defer cron.Stop() - - select { - case <-time.After(ONE_SECOND): - // Success, shouldn't run - case <-wait(wg): - t.FailNow() - } -} - -// Start cron, add a job, remove it, expect it doesn't run. -func TestRemoveWhileRunning(t *testing.T) { - wg := &sync.WaitGroup{} - wg.Add(1) - - cron := New() - cron.Start() - defer cron.Stop() - id, _ := cron.AddFunc("* * * * * ?", func() { wg.Done() }) - cron.Remove(id) - - select { - case <-time.After(ONE_SECOND): - case <-wait(wg): - t.FailNow() - } -} - -// Test timing with Entries. -func TestSnapshotEntries(t *testing.T) { - wg := &sync.WaitGroup{} - wg.Add(1) - - cron := New() - cron.AddFunc("@every 2s", func() { wg.Done() }) - cron.Start() - defer cron.Stop() - - // Cron should fire in 2 seconds. After 1 second, call Entries. - select { - case <-time.After(ONE_SECOND): - cron.Entries() - } - - // Even though Entries was called, the cron should fire at the 2 second mark. - select { - case <-time.After(ONE_SECOND): - t.FailNow() - case <-wait(wg): - } - -} - -// Test that the entries are correctly sorted. -// Add a bunch of long-in-the-future entries, and an immediate entry, and ensure -// that the immediate entry runs immediately. -// Also: Test that multiple jobs run in the same instant. -func TestMultipleEntries(t *testing.T) { - wg := &sync.WaitGroup{} - wg.Add(2) - - cron := New() - cron.AddFunc("0 0 0 1 1 ?", func() {}) - cron.AddFunc("* * * * * ?", func() { wg.Done() }) - id1, _ := cron.AddFunc("* * * * * ?", func() { t.Fatal() }) - id2, _ := cron.AddFunc("* * * * * ?", func() { t.Fatal() }) - cron.AddFunc("0 0 0 31 12 ?", func() {}) - cron.AddFunc("* * * * * ?", func() { wg.Done() }) - - cron.Remove(id1) - cron.Start() - cron.Remove(id2) - defer cron.Stop() - - select { - case <-time.After(ONE_SECOND): - t.FailNow() - case <-wait(wg): - } -} - -// Test running the same job twice. -func TestRunningJobTwice(t *testing.T) { - wg := &sync.WaitGroup{} - wg.Add(2) - - cron := New() - cron.AddFunc("0 0 0 1 1 ?", func() {}) - cron.AddFunc("0 0 0 31 12 ?", func() {}) - cron.AddFunc("* * * * * ?", func() { wg.Done() }) - - cron.Start() - defer cron.Stop() - - select { - case <-time.After(2 * ONE_SECOND): - t.FailNow() - case <-wait(wg): - } -} - -func TestRunningMultipleSchedules(t *testing.T) { - wg := &sync.WaitGroup{} - wg.Add(2) - - cron := New() - cron.AddFunc("0 0 0 1 1 ?", func() {}) - cron.AddFunc("0 0 0 31 12 ?", func() {}) - cron.AddFunc("* * * * * ?", func() { wg.Done() }) - cron.Schedule(Every(time.Minute), FuncJob(func() {})) - cron.Schedule(Every(time.Second), FuncJob(func() { wg.Done() })) - cron.Schedule(Every(time.Hour), FuncJob(func() {})) - - cron.Start() - defer cron.Stop() - - select { - case <-time.After(2 * ONE_SECOND): - t.FailNow() - case <-wait(wg): - } -} - -// Test that the cron is run in the local time zone (as opposed to UTC). -func TestLocalTimezone(t *testing.T) { - wg := &sync.WaitGroup{} - wg.Add(1) - - now := time.Now().Local() - spec := fmt.Sprintf("%d %d %d %d %d ?", - now.Second()+1, now.Minute(), now.Hour(), now.Day(), now.Month()) - - cron := New() - cron.AddFunc(spec, func() { wg.Done() }) - cron.Start() - defer cron.Stop() - - select { - case <-time.After(ONE_SECOND): - t.FailNow() - case <-wait(wg): - } -} - -type testJob struct { - wg *sync.WaitGroup - name string -} - -func (t testJob) Run() { - t.wg.Done() -} - -// Simple test using Runnables. -func TestJob(t *testing.T) { - wg := &sync.WaitGroup{} - wg.Add(1) - - cron := New() - cron.AddJob("0 0 0 30 Feb ?", testJob{wg, "job0"}) - cron.AddJob("0 0 0 1 1 ?", testJob{wg, "job1"}) - cron.AddJob("* * * * * ?", testJob{wg, "job2"}) - cron.AddJob("1 0 0 1 1 ?", testJob{wg, "job3"}) - cron.Schedule(Every(5*time.Second+5*time.Nanosecond), testJob{wg, "job4"}) - cron.Schedule(Every(5*time.Minute), testJob{wg, "job5"}) - - cron.Start() - defer cron.Stop() - - select { - case <-time.After(ONE_SECOND): - t.FailNow() - case <-wait(wg): - } - - // Ensure the entries are in the right order. - expecteds := []string{"job2", "job4", "job5", "job1", "job3", "job0"} - - var actuals []string - for _, entry := range cron.Entries() { - actuals = append(actuals, entry.Job.(testJob).name) - } - - for i, expected := range expecteds { - if actuals[i] != expected { - t.Errorf("Jobs not in the right order. (expected) %s != %s (actual)", expecteds, actuals) - t.FailNow() - } - } -} - -func wait(wg *sync.WaitGroup) chan bool { - ch := make(chan bool) - go func() { - wg.Wait() - ch <- true - }() - return ch -} - -func stop(cron *Cron) chan bool { - ch := make(chan bool) - go func() { - cron.Stop() - ch <- true - }() - return ch -} diff --git a/vendor/github.com/robfig/cron/parser_test.go b/vendor/github.com/robfig/cron/parser_test.go deleted file mode 100644 index a4a1c510f14b..000000000000 --- a/vendor/github.com/robfig/cron/parser_test.go +++ /dev/null @@ -1,133 +0,0 @@ -package cron - -import ( - "reflect" - "testing" - "time" -) - -func TestRange(t *testing.T) { - ranges := []struct { - expr string - min, max uint - expected uint64 - }{ - {"5", 0, 7, 1 << 5}, - {"0", 0, 7, 1 << 0}, - {"7", 0, 7, 1 << 7}, - - {"5-5", 0, 7, 1 << 5}, - {"5-6", 0, 7, 1<<5 | 1<<6}, - {"5-7", 0, 7, 1<<5 | 1<<6 | 1<<7}, - - {"5-6/2", 0, 7, 1 << 5}, - {"5-7/2", 0, 7, 1<<5 | 1<<7}, - {"5-7/1", 0, 7, 1<<5 | 1<<6 | 1<<7}, - - {"*", 1, 3, 1<<1 | 1<<2 | 1<<3 | starBit}, - {"*/2", 1, 3, 1<<1 | 1<<3 | starBit}, - } - - for _, c := range ranges { - actual := getRange(c.expr, bounds{c.min, c.max, nil}) - if actual != c.expected { - t.Errorf("%s => (expected) %d != %d (actual)", c.expr, c.expected, actual) - } - } -} - -func TestField(t *testing.T) { - fields := []struct { - expr string - min, max uint - expected uint64 - }{ - {"5", 1, 7, 1 << 5}, - {"5,6", 1, 7, 1<<5 | 1<<6}, - {"5,6,7", 1, 7, 1<<5 | 1<<6 | 1<<7}, - {"1,5-7/2,3", 1, 7, 1<<1 | 1<<5 | 1<<7 | 1<<3}, - } - - for _, c := range fields { - actual := getField(c.expr, bounds{c.min, c.max, nil}) - if actual != c.expected { - t.Errorf("%s => (expected) %d != %d (actual)", c.expr, c.expected, actual) - } - } -} - -func TestBits(t *testing.T) { - allBits := []struct { - r bounds - expected uint64 - }{ - {minutes, 0xfffffffffffffff}, // 0-59: 60 ones - {hours, 0xffffff}, // 0-23: 24 ones - {dom, 0xfffffffe}, // 1-31: 31 ones, 1 zero - {months, 0x1ffe}, // 1-12: 12 ones, 1 zero - {dow, 0x7f}, // 0-6: 7 ones - } - - for _, c := range allBits { - actual := all(c.r) // all() adds the starBit, so compensate for that.. - if c.expected|starBit != actual { - t.Errorf("%d-%d/%d => (expected) %b != %b (actual)", - c.r.min, c.r.max, 1, c.expected|starBit, actual) - } - } - - bits := []struct { - min, max, step uint - expected uint64 - }{ - - {0, 0, 1, 0x1}, - {1, 1, 1, 0x2}, - {1, 5, 2, 0x2a}, // 101010 - {1, 4, 2, 0xa}, // 1010 - } - - for _, c := range bits { - actual := getBits(c.min, c.max, c.step) - if c.expected != actual { - t.Errorf("%d-%d/%d => (expected) %b != %b (actual)", - c.min, c.max, c.step, c.expected, actual) - } - } -} - -func TestParseSchedule(t *testing.T) { - tokyo, _ := time.LoadLocation("Asia/Tokyo") - entries := []struct { - expr string - expected Schedule - }{ - {"0 5 * * * *", every5min(time.Local)}, - {"5 * * * *", every5min(time.Local)}, - {"TZ=UTC 0 5 * * * *", every5min(time.UTC)}, - {"TZ=UTC 5 * * * *", every5min(time.UTC)}, - {"TZ=Asia/Tokyo 0 5 * * * *", every5min(tokyo)}, - {"@every 5m", ConstantDelaySchedule{5 * time.Minute}}, - {"@midnight", midnight(time.Local)}, - {"TZ=UTC @midnight", midnight(time.UTC)}, - {"TZ=Asia/Tokyo @midnight", midnight(tokyo)}, - } - - for _, c := range entries { - actual, err := Parse(c.expr) - if err != nil { - t.Error(err) - } - if !reflect.DeepEqual(actual, c.expected) { - t.Errorf("%s => (expected) %v != %v (actual)", c.expr, c.expected, actual) - } - } -} - -func every5min(loc *time.Location) *SpecSchedule { - return &SpecSchedule{1 << 0, 1 << 5, all(hours), all(dom), all(months), all(dow), loc} -} - -func midnight(loc *time.Location) *SpecSchedule { - return &SpecSchedule{1, 1, 1, all(dom), all(months), all(dow), loc} -} diff --git a/vendor/github.com/robfig/cron/spec_test.go b/vendor/github.com/robfig/cron/spec_test.go deleted file mode 100644 index 5e5e5cd04388..000000000000 --- a/vendor/github.com/robfig/cron/spec_test.go +++ /dev/null @@ -1,202 +0,0 @@ -package cron - -import ( - "testing" - "time" -) - -func TestActivation(t *testing.T) { - tests := []struct { - time, spec string - expected bool - }{ - // Every fifteen minutes. - {"Mon Jul 9 15:00 2012", "0/15 * * * *", true}, - {"Mon Jul 9 15:45 2012", "0/15 * * * *", true}, - {"Mon Jul 9 15:40 2012", "0/15 * * * *", false}, - - // Every fifteen minutes, starting at 5 minutes. - {"Mon Jul 9 15:05 2012", "5/15 * * * *", true}, - {"Mon Jul 9 15:20 2012", "5/15 * * * *", true}, - {"Mon Jul 9 15:50 2012", "5/15 * * * *", true}, - - // Named months - {"Sun Jul 15 15:00 2012", "0/15 * * Jul *", true}, - {"Sun Jul 15 15:00 2012", "0/15 * * Jun *", false}, - - // Everything set. - {"Sun Jul 15 08:30 2012", "0 30 08 ? Jul Sun", true}, - {"Sun Jul 15 08:30 2012", "0 30 08 15 Jul ?", true}, - {"Mon Jul 16 08:30 2012", "0 30 08 ? Jul Sun", false}, - {"Mon Jul 16 08:30 2012", "0 30 08 15 Jul ?", false}, - - // Predefined schedules - {"Mon Jul 9 15:00 2012", "@hourly", true}, - {"Mon Jul 9 15:04 2012", "@hourly", false}, - {"Mon Jul 9 15:00 2012", "@daily", false}, - {"Mon Jul 9 00:00 2012", "@daily", true}, - {"Mon Jul 9 00:00 2012", "@weekly", false}, - {"Sun Jul 8 00:00 2012", "@weekly", true}, - {"Sun Jul 8 01:00 2012", "@weekly", false}, - {"Sun Jul 8 00:00 2012", "@monthly", false}, - {"Sun Jul 1 00:00 2012", "@monthly", true}, - - // Test interaction of DOW and DOM. - // If both are specified, then only one needs to match. - {"Sun Jul 15 00:00 2012", "0 * * 1,15 * Sun", true}, - {"Fri Jun 15 00:00 2012", "0 * * 1,15 * Sun", true}, - {"Wed Aug 1 00:00 2012", "0 * * 1,15 * Sun", true}, - - // However, if one has a star, then both need to match. - {"Sun Jul 15 00:00 2012", "0 * * * * Mon", false}, - {"Sun Jul 15 00:00 2012", "0 * * */10 * Sun", false}, - {"Mon Jul 9 00:00 2012", "0 * * 1,15 * *", false}, - {"Sun Jul 15 00:00 2012", "0 * * 1,15 * *", true}, - {"Sun Jul 15 00:00 2012", "0 * * */2 * Sun", true}, - } - - for _, test := range tests { - sched, err := Parse(test.spec) - if err != nil { - t.Error(err) - continue - } - actual := sched.Next(getTime(test.time).Add(-1 * time.Second)) - expected := getTime(test.time) - if test.expected && expected != actual || !test.expected && expected == actual { - t.Errorf("Fail evaluating %s on %s: (expected) %s != %s (actual)", - test.spec, test.time, expected, actual) - } - } -} - -func TestNext(t *testing.T) { - runs := []struct { - time, spec string - expected string - }{ - // Simple cases - {"Mon Jul 9 14:45 2012", "0/15 * * * *", "Mon Jul 9 15:00 2012"}, - {"Mon Jul 9 14:59 2012", "0/15 * * * *", "Mon Jul 9 15:00 2012"}, - {"Mon Jul 9 14:59:59 2012", "0/15 * * * *", "Mon Jul 9 15:00 2012"}, - - // Wrap around hours - {"Mon Jul 9 15:45 2012", "20-35/15 * * * *", "Mon Jul 9 16:20 2012"}, - - // Wrap around days - {"Mon Jul 9 23:46 2012", "*/15 * * * *", "Tue Jul 10 00:00 2012"}, - {"Mon Jul 9 23:45 2012", "20-35/15 * * * *", "Tue Jul 10 00:20 2012"}, - {"Mon Jul 9 23:35:51 2012", "15/35 20-35/15 * * * *", "Tue Jul 10 00:20:15 2012"}, - {"Mon Jul 9 23:35:51 2012", "15/35 20-35/15 1/2 * * *", "Tue Jul 10 01:20:15 2012"}, - {"Mon Jul 9 23:35:51 2012", "15/35 20-35/15 10-12 * * *", "Tue Jul 10 10:20:15 2012"}, - - {"Mon Jul 9 23:35:51 2012", "15/35 20-35/15 1/2 */2 * *", "Thu Jul 11 01:20:15 2012"}, - {"Mon Jul 9 23:35:51 2012", "15/35 20-35/15 * 9-20 * *", "Wed Jul 10 00:20:15 2012"}, - {"Mon Jul 9 23:35:51 2012", "15/35 20-35/15 * 9-20 Jul *", "Wed Jul 10 00:20:15 2012"}, - - // Wrap around months - {"Mon Jul 9 23:35 2012", "0 0 0 9 Apr-Oct ?", "Thu Aug 9 00:00 2012"}, - {"Mon Jul 9 23:35 2012", "0 0 0 */5 Apr,Aug,Oct Mon", "Mon Aug 6 00:00 2012"}, - {"Mon Jul 9 23:35 2012", "0 0 0 */5 Oct Mon", "Mon Oct 1 00:00 2012"}, - - // Wrap around years - {"Mon Jul 9 23:35 2012", "0 0 0 * Feb Mon", "Mon Feb 4 00:00 2013"}, - {"Mon Jul 9 23:35 2012", "0 0 0 * Feb Mon/2", "Fri Feb 1 00:00 2013"}, - - // Wrap around minute, hour, day, month, and year - {"Mon Dec 31 23:59:45 2012", "0 * * * * *", "Tue Jan 1 00:00:00 2013"}, - - // Leap year - {"Mon Jul 9 23:35 2012", "0 0 0 29 Feb ?", "Mon Feb 29 00:00 2016"}, - - // Daylight savings time 2am EST (-5) -> 3am EDT (-4) - {"2012-03-11T00:00:00-0500", "TZ=America/New_York 0 30 2 11 Mar ?", "2013-03-11T02:30:00-0400"}, - - // hourly job - {"2012-03-11T00:00:00-0500", "TZ=America/New_York 0 0 * * * ?", "2012-03-11T01:00:00-0500"}, - {"2012-03-11T01:00:00-0500", "TZ=America/New_York 0 0 * * * ?", "2012-03-11T03:00:00-0400"}, - {"2012-03-11T03:00:00-0400", "TZ=America/New_York 0 0 * * * ?", "2012-03-11T04:00:00-0400"}, - {"2012-03-11T04:00:00-0400", "TZ=America/New_York 0 0 * * * ?", "2012-03-11T05:00:00-0400"}, - - // 1am nightly job - {"2012-03-11T00:00:00-0500", "TZ=America/New_York 0 0 1 * * ?", "2012-03-11T01:00:00-0500"}, - {"2012-03-11T01:00:00-0500", "TZ=America/New_York 0 0 1 * * ?", "2012-03-12T01:00:00-0400"}, - - // 2am nightly job (skipped) - {"2012-03-11T00:00:00-0500", "TZ=America/New_York 0 0 2 * * ?", "2012-03-12T02:00:00-0400"}, - - // Daylight savings time 2am EDT (-4) => 1am EST (-5) - {"2012-11-04T00:00:00-0400", "TZ=America/New_York 0 30 2 04 Nov ?", "2012-11-04T02:30:00-0500"}, - {"2012-11-04T01:45:00-0400", "TZ=America/New_York 0 30 1 04 Nov ?", "2012-11-04T01:30:00-0500"}, - - // hourly job - {"2012-11-04T00:00:00-0400", "TZ=America/New_York 0 0 * * * ?", "2012-11-04T01:00:00-0400"}, - {"2012-11-04T01:00:00-0400", "TZ=America/New_York 0 0 * * * ?", "2012-11-04T01:00:00-0500"}, - {"2012-11-04T01:00:00-0500", "TZ=America/New_York 0 0 * * * ?", "2012-11-04T02:00:00-0500"}, - - // 1am nightly job (runs twice) - {"2012-11-04T00:00:00-0400", "TZ=America/New_York 0 0 1 * * ?", "2012-11-04T01:00:00-0400"}, - {"2012-11-04T01:00:00-0400", "TZ=America/New_York 0 0 1 * * ?", "2012-11-04T01:00:00-0500"}, - {"2012-11-04T01:00:00-0500", "TZ=America/New_York 0 0 1 * * ?", "2012-11-05T01:00:00-0500"}, - - // 2am nightly job - {"2012-11-04T00:00:00-0400", "TZ=America/New_York 0 0 2 * * ?", "2012-11-04T02:00:00-0500"}, - {"2012-11-04T02:00:00-0500", "TZ=America/New_York 0 0 2 * * ?", "2012-11-05T02:00:00-0500"}, - - // 3am nightly job - {"2012-11-04T00:00:00-0400", "TZ=America/New_York 0 0 3 * * ?", "2012-11-04T03:00:00-0500"}, - {"2012-11-04T03:00:00-0500", "TZ=America/New_York 0 0 3 * * ?", "2012-11-05T03:00:00-0500"}, - - // Unsatisfiable - {"Mon Jul 9 23:35 2012", "0 0 0 30 Feb ?", ""}, - {"Mon Jul 9 23:35 2012", "0 0 0 31 Apr ?", ""}, - } - - for _, c := range runs { - sched, err := Parse(c.spec) - if err != nil { - t.Error(err) - continue - } - actual := sched.Next(getTime(c.time)) - expected := getTime(c.expected) - if !actual.Equal(expected) { - t.Errorf("%s, \"%s\": (expected) %v != %v (actual)", c.time, c.spec, expected, actual) - } - } -} - -func TestErrors(t *testing.T) { - invalidSpecs := []string{ - "xyz", - "60 0 * * *", - "0 60 * * *", - "0 0 * * XYZ", - } - for _, spec := range invalidSpecs { - _, err := Parse(spec) - if err == nil { - t.Error("expected an error parsing: ", spec) - } - } -} - -func getTime(value string) time.Time { - if value == "" { - return time.Time{} - } - - var layouts = []string{ - "Mon Jan 2 15:04 2006", - "Mon Jan 2 15:04:05 2006", - } - for _, layout := range layouts { - if t, err := time.ParseInLocation(layout, value, time.Local); err == nil { - return t - } - } - if t, err := time.Parse("2006-01-02T15:04:05-0700", value); err == nil { - return t - } - panic("could not parse time value " + value) -} diff --git a/vendor/github.com/satori/go.uuid/BUILD b/vendor/github.com/satori/go.uuid/BUILD index d38ad2c76d34..98cc64153940 100644 --- a/vendor/github.com/satori/go.uuid/BUILD +++ b/vendor/github.com/satori/go.uuid/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -7,16 +7,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = [ - "benchmarks_test.go", - "uuid_test.go", - ], - importpath = "github.com/satori/go.uuid", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/satori/go.uuid/benchmarks_test.go b/vendor/github.com/satori/go.uuid/benchmarks_test.go deleted file mode 100644 index b4e567fc64f8..000000000000 --- a/vendor/github.com/satori/go.uuid/benchmarks_test.go +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (C) 2013-2015 by Maxim Bublis -// -// 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. - -package uuid - -import ( - "testing" -) - -func BenchmarkFromBytes(b *testing.B) { - bytes := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} - for i := 0; i < b.N; i++ { - FromBytes(bytes) - } -} - -func BenchmarkFromString(b *testing.B) { - s := "6ba7b810-9dad-11d1-80b4-00c04fd430c8" - for i := 0; i < b.N; i++ { - FromString(s) - } -} - -func BenchmarkFromStringUrn(b *testing.B) { - s := "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8" - for i := 0; i < b.N; i++ { - FromString(s) - } -} - -func BenchmarkFromStringWithBrackets(b *testing.B) { - s := "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}" - for i := 0; i < b.N; i++ { - FromString(s) - } -} - -func BenchmarkNewV1(b *testing.B) { - for i := 0; i < b.N; i++ { - NewV1() - } -} - -func BenchmarkNewV2(b *testing.B) { - for i := 0; i < b.N; i++ { - NewV2(DomainPerson) - } -} - -func BenchmarkNewV3(b *testing.B) { - for i := 0; i < b.N; i++ { - NewV3(NamespaceDNS, "www.example.com") - } -} - -func BenchmarkNewV4(b *testing.B) { - for i := 0; i < b.N; i++ { - NewV4() - } -} - -func BenchmarkNewV5(b *testing.B) { - for i := 0; i < b.N; i++ { - NewV5(NamespaceDNS, "www.example.com") - } -} - -func BenchmarkMarshalBinary(b *testing.B) { - u := NewV4() - for i := 0; i < b.N; i++ { - u.MarshalBinary() - } -} - -func BenchmarkMarshalText(b *testing.B) { - u := NewV4() - for i := 0; i < b.N; i++ { - u.MarshalText() - } -} - -func BenchmarkUnmarshalBinary(b *testing.B) { - bytes := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} - u := UUID{} - for i := 0; i < b.N; i++ { - u.UnmarshalBinary(bytes) - } -} - -func BenchmarkUnmarshalText(b *testing.B) { - bytes := []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c8") - u := UUID{} - for i := 0; i < b.N; i++ { - u.UnmarshalText(bytes) - } -} - -func BenchmarkMarshalToString(b *testing.B) { - u := NewV4() - for i := 0; i < b.N; i++ { - u.String() - } -} diff --git a/vendor/github.com/satori/go.uuid/uuid_test.go b/vendor/github.com/satori/go.uuid/uuid_test.go deleted file mode 100644 index aa68ac94f59c..000000000000 --- a/vendor/github.com/satori/go.uuid/uuid_test.go +++ /dev/null @@ -1,633 +0,0 @@ -// Copyright (C) 2013, 2015 by Maxim Bublis -// -// 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. - -package uuid - -import ( - "bytes" - "testing" -) - -func TestBytes(t *testing.T) { - u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} - - bytes1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} - - if !bytes.Equal(u.Bytes(), bytes1) { - t.Errorf("Incorrect bytes representation for UUID: %s", u) - } -} - -func TestString(t *testing.T) { - if NamespaceDNS.String() != "6ba7b810-9dad-11d1-80b4-00c04fd430c8" { - t.Errorf("Incorrect string representation for UUID: %s", NamespaceDNS.String()) - } -} - -func TestEqual(t *testing.T) { - if !Equal(NamespaceDNS, NamespaceDNS) { - t.Errorf("Incorrect comparison of %s and %s", NamespaceDNS, NamespaceDNS) - } - - if Equal(NamespaceDNS, NamespaceURL) { - t.Errorf("Incorrect comparison of %s and %s", NamespaceDNS, NamespaceURL) - } -} - -func TestOr(t *testing.T) { - u1 := UUID{0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff} - u2 := UUID{0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00} - - u := UUID{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff} - - if !Equal(u, Or(u1, u2)) { - t.Errorf("Incorrect bitwise OR result %s", Or(u1, u2)) - } -} - -func TestAnd(t *testing.T) { - u1 := UUID{0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff} - u2 := UUID{0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00} - - u := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} - - if !Equal(u, And(u1, u2)) { - t.Errorf("Incorrect bitwise AND result %s", And(u1, u2)) - } -} - -func TestVersion(t *testing.T) { - u := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} - - if u.Version() != 1 { - t.Errorf("Incorrect version for UUID: %d", u.Version()) - } -} - -func TestSetVersion(t *testing.T) { - u := UUID{} - u.SetVersion(4) - - if u.Version() != 4 { - t.Errorf("Incorrect version for UUID after u.setVersion(4): %d", u.Version()) - } -} - -func TestVariant(t *testing.T) { - u1 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} - - if u1.Variant() != VariantNCS { - t.Errorf("Incorrect variant for UUID variant %d: %d", VariantNCS, u1.Variant()) - } - - u2 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} - - if u2.Variant() != VariantRFC4122 { - t.Errorf("Incorrect variant for UUID variant %d: %d", VariantRFC4122, u2.Variant()) - } - - u3 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} - - if u3.Variant() != VariantMicrosoft { - t.Errorf("Incorrect variant for UUID variant %d: %d", VariantMicrosoft, u3.Variant()) - } - - u4 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} - - if u4.Variant() != VariantFuture { - t.Errorf("Incorrect variant for UUID variant %d: %d", VariantFuture, u4.Variant()) - } -} - -func TestSetVariant(t *testing.T) { - u := new(UUID) - u.SetVariant() - - if u.Variant() != VariantRFC4122 { - t.Errorf("Incorrect variant for UUID after u.setVariant(): %d", u.Variant()) - } -} - -func TestFromBytes(t *testing.T) { - u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} - b1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} - - u1, err := FromBytes(b1) - if err != nil { - t.Errorf("Error parsing UUID from bytes: %s", err) - } - - if !Equal(u, u1) { - t.Errorf("UUIDs should be equal: %s and %s", u, u1) - } - - b2 := []byte{} - - _, err = FromBytes(b2) - if err == nil { - t.Errorf("Should return error parsing from empty byte slice, got %s", err) - } -} - -func TestMarshalBinary(t *testing.T) { - u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} - b1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} - - b2, err := u.MarshalBinary() - if err != nil { - t.Errorf("Error marshaling UUID: %s", err) - } - - if !bytes.Equal(b1, b2) { - t.Errorf("Marshaled UUID should be %s, got %s", b1, b2) - } -} - -func TestUnmarshalBinary(t *testing.T) { - u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} - b1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} - - u1 := UUID{} - err := u1.UnmarshalBinary(b1) - if err != nil { - t.Errorf("Error unmarshaling UUID: %s", err) - } - - if !Equal(u, u1) { - t.Errorf("UUIDs should be equal: %s and %s", u, u1) - } - - b2 := []byte{} - u2 := UUID{} - - err = u2.UnmarshalBinary(b2) - if err == nil { - t.Errorf("Should return error unmarshalling from empty byte slice, got %s", err) - } -} - -func TestFromString(t *testing.T) { - u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} - - s1 := "6ba7b810-9dad-11d1-80b4-00c04fd430c8" - s2 := "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}" - s3 := "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8" - - _, err := FromString("") - if err == nil { - t.Errorf("Should return error trying to parse empty string, got %s", err) - } - - u1, err := FromString(s1) - if err != nil { - t.Errorf("Error parsing UUID from string: %s", err) - } - - if !Equal(u, u1) { - t.Errorf("UUIDs should be equal: %s and %s", u, u1) - } - - u2, err := FromString(s2) - if err != nil { - t.Errorf("Error parsing UUID from string: %s", err) - } - - if !Equal(u, u2) { - t.Errorf("UUIDs should be equal: %s and %s", u, u2) - } - - u3, err := FromString(s3) - if err != nil { - t.Errorf("Error parsing UUID from string: %s", err) - } - - if !Equal(u, u3) { - t.Errorf("UUIDs should be equal: %s and %s", u, u3) - } -} - -func TestFromStringShort(t *testing.T) { - // Invalid 35-character UUID string - s1 := "6ba7b810-9dad-11d1-80b4-00c04fd430c" - - for i := len(s1); i >= 0; i-- { - _, err := FromString(s1[:i]) - if err == nil { - t.Errorf("Should return error trying to parse too short string, got %s", err) - } - } -} - -func TestFromStringLong(t *testing.T) { - // Invalid 37+ character UUID string - s := []string{ - "6ba7b810-9dad-11d1-80b4-00c04fd430c8=", - "6ba7b810-9dad-11d1-80b4-00c04fd430c8}", - "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}f", - "6ba7b810-9dad-11d1-80b4-00c04fd430c800c04fd430c8", - } - - for _, str := range s { - _, err := FromString(str) - if err == nil { - t.Errorf("Should return error trying to parse too long string, passed %s", str) - } - } -} - -func TestFromStringInvalid(t *testing.T) { - // Invalid UUID string formats - s := []string{ - "6ba7b8109dad11d180b400c04fd430c8", - "6ba7b8109dad11d180b400c04fd430c86ba7b8109dad11d180b400c04fd430c8", - "urn:uuid:{6ba7b810-9dad-11d1-80b4-00c04fd430c8}", - "6ba7b8109-dad-11d1-80b4-00c04fd430c8", - "6ba7b810-9dad1-1d1-80b4-00c04fd430c8", - "6ba7b810-9dad-11d18-0b4-00c04fd430c8", - "6ba7b810-9dad-11d1-80b40-0c04fd430c8", - "6ba7b810+9dad+11d1+80b4+00c04fd430c8", - "6ba7b810-9dad11d180b400c04fd430c8", - "6ba7b8109dad-11d180b400c04fd430c8", - "6ba7b8109dad11d1-80b400c04fd430c8", - "6ba7b8109dad11d180b4-00c04fd430c8", - } - - for _, str := range s { - _, err := FromString(str) - if err == nil { - t.Errorf("Should return error trying to parse invalid string, passed %s", str) - } - } -} - -func TestFromStringOrNil(t *testing.T) { - u := FromStringOrNil("") - if u != Nil { - t.Errorf("Should return Nil UUID on parse failure, got %s", u) - } -} - -func TestFromBytesOrNil(t *testing.T) { - b := []byte{} - u := FromBytesOrNil(b) - if u != Nil { - t.Errorf("Should return Nil UUID on parse failure, got %s", u) - } -} - -func TestMarshalText(t *testing.T) { - u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} - b1 := []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c8") - - b2, err := u.MarshalText() - if err != nil { - t.Errorf("Error marshaling UUID: %s", err) - } - - if !bytes.Equal(b1, b2) { - t.Errorf("Marshaled UUID should be %s, got %s", b1, b2) - } -} - -func TestUnmarshalText(t *testing.T) { - u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} - b1 := []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c8") - - u1 := UUID{} - err := u1.UnmarshalText(b1) - if err != nil { - t.Errorf("Error unmarshaling UUID: %s", err) - } - - if !Equal(u, u1) { - t.Errorf("UUIDs should be equal: %s and %s", u, u1) - } - - b2 := []byte("") - u2 := UUID{} - - err = u2.UnmarshalText(b2) - if err == nil { - t.Errorf("Should return error trying to unmarshal from empty string") - } -} - -func TestValue(t *testing.T) { - u, err := FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8") - if err != nil { - t.Errorf("Error parsing UUID from string: %s", err) - } - - val, err := u.Value() - if err != nil { - t.Errorf("Error getting UUID value: %s", err) - } - - if val != u.String() { - t.Errorf("Wrong value returned, should be equal: %s and %s", val, u) - } -} - -func TestValueNil(t *testing.T) { - u := UUID{} - - val, err := u.Value() - if err != nil { - t.Errorf("Error getting UUID value: %s", err) - } - - if val != Nil.String() { - t.Errorf("Wrong value returned, should be equal to UUID.Nil: %s", val) - } -} - -func TestNullUUIDValueNil(t *testing.T) { - u := NullUUID{} - - val, err := u.Value() - if err != nil { - t.Errorf("Error getting UUID value: %s", err) - } - - if val != nil { - t.Errorf("Wrong value returned, should be nil: %s", val) - } -} - -func TestScanBinary(t *testing.T) { - u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} - b1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} - - u1 := UUID{} - err := u1.Scan(b1) - if err != nil { - t.Errorf("Error unmarshaling UUID: %s", err) - } - - if !Equal(u, u1) { - t.Errorf("UUIDs should be equal: %s and %s", u, u1) - } - - b2 := []byte{} - u2 := UUID{} - - err = u2.Scan(b2) - if err == nil { - t.Errorf("Should return error unmarshalling from empty byte slice, got %s", err) - } -} - -func TestScanString(t *testing.T) { - u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} - s1 := "6ba7b810-9dad-11d1-80b4-00c04fd430c8" - - u1 := UUID{} - err := u1.Scan(s1) - if err != nil { - t.Errorf("Error unmarshaling UUID: %s", err) - } - - if !Equal(u, u1) { - t.Errorf("UUIDs should be equal: %s and %s", u, u1) - } - - s2 := "" - u2 := UUID{} - - err = u2.Scan(s2) - if err == nil { - t.Errorf("Should return error trying to unmarshal from empty string") - } -} - -func TestScanText(t *testing.T) { - u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} - b1 := []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c8") - - u1 := UUID{} - err := u1.Scan(b1) - if err != nil { - t.Errorf("Error unmarshaling UUID: %s", err) - } - - if !Equal(u, u1) { - t.Errorf("UUIDs should be equal: %s and %s", u, u1) - } - - b2 := []byte("") - u2 := UUID{} - - err = u2.Scan(b2) - if err == nil { - t.Errorf("Should return error trying to unmarshal from empty string") - } -} - -func TestScanUnsupported(t *testing.T) { - u := UUID{} - - err := u.Scan(true) - if err == nil { - t.Errorf("Should return error trying to unmarshal from bool") - } -} - -func TestScanNil(t *testing.T) { - u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} - - err := u.Scan(nil) - if err == nil { - t.Errorf("Error UUID shouldn't allow unmarshalling from nil") - } -} - -func TestNullUUIDScanValid(t *testing.T) { - u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} - s1 := "6ba7b810-9dad-11d1-80b4-00c04fd430c8" - - u1 := NullUUID{} - err := u1.Scan(s1) - if err != nil { - t.Errorf("Error unmarshaling NullUUID: %s", err) - } - - if !u1.Valid { - t.Errorf("NullUUID should be valid") - } - - if !Equal(u, u1.UUID) { - t.Errorf("UUIDs should be equal: %s and %s", u, u1.UUID) - } -} - -func TestNullUUIDScanNil(t *testing.T) { - u := NullUUID{UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}, true} - - err := u.Scan(nil) - if err != nil { - t.Errorf("Error unmarshaling NullUUID: %s", err) - } - - if u.Valid { - t.Errorf("NullUUID should not be valid") - } - - if !Equal(u.UUID, Nil) { - t.Errorf("NullUUID value should be equal to Nil: %s", u) - } -} - -func TestNewV1(t *testing.T) { - u := NewV1() - - if u.Version() != 1 { - t.Errorf("UUIDv1 generated with incorrect version: %d", u.Version()) - } - - if u.Variant() != VariantRFC4122 { - t.Errorf("UUIDv1 generated with incorrect variant: %d", u.Variant()) - } - - u1 := NewV1() - u2 := NewV1() - - if Equal(u1, u2) { - t.Errorf("UUIDv1 generated two equal UUIDs: %s and %s", u1, u2) - } - - oldFunc := epochFunc - epochFunc = func() uint64 { return 0 } - - u3 := NewV1() - u4 := NewV1() - - if Equal(u3, u4) { - t.Errorf("UUIDv1 generated two equal UUIDs: %s and %s", u3, u4) - } - - epochFunc = oldFunc -} - -func TestNewV2(t *testing.T) { - u1 := NewV2(DomainPerson) - - if u1.Version() != 2 { - t.Errorf("UUIDv2 generated with incorrect version: %d", u1.Version()) - } - - if u1.Variant() != VariantRFC4122 { - t.Errorf("UUIDv2 generated with incorrect variant: %d", u1.Variant()) - } - - u2 := NewV2(DomainGroup) - - if u2.Version() != 2 { - t.Errorf("UUIDv2 generated with incorrect version: %d", u2.Version()) - } - - if u2.Variant() != VariantRFC4122 { - t.Errorf("UUIDv2 generated with incorrect variant: %d", u2.Variant()) - } -} - -func TestNewV3(t *testing.T) { - u := NewV3(NamespaceDNS, "www.example.com") - - if u.Version() != 3 { - t.Errorf("UUIDv3 generated with incorrect version: %d", u.Version()) - } - - if u.Variant() != VariantRFC4122 { - t.Errorf("UUIDv3 generated with incorrect variant: %d", u.Variant()) - } - - if u.String() != "5df41881-3aed-3515-88a7-2f4a814cf09e" { - t.Errorf("UUIDv3 generated incorrectly: %s", u.String()) - } - - u = NewV3(NamespaceDNS, "python.org") - - if u.String() != "6fa459ea-ee8a-3ca4-894e-db77e160355e" { - t.Errorf("UUIDv3 generated incorrectly: %s", u.String()) - } - - u1 := NewV3(NamespaceDNS, "golang.org") - u2 := NewV3(NamespaceDNS, "golang.org") - if !Equal(u1, u2) { - t.Errorf("UUIDv3 generated different UUIDs for same namespace and name: %s and %s", u1, u2) - } - - u3 := NewV3(NamespaceDNS, "example.com") - if Equal(u1, u3) { - t.Errorf("UUIDv3 generated same UUIDs for different names in same namespace: %s and %s", u1, u2) - } - - u4 := NewV3(NamespaceURL, "golang.org") - if Equal(u1, u4) { - t.Errorf("UUIDv3 generated same UUIDs for sane names in different namespaces: %s and %s", u1, u4) - } -} - -func TestNewV4(t *testing.T) { - u := NewV4() - - if u.Version() != 4 { - t.Errorf("UUIDv4 generated with incorrect version: %d", u.Version()) - } - - if u.Variant() != VariantRFC4122 { - t.Errorf("UUIDv4 generated with incorrect variant: %d", u.Variant()) - } -} - -func TestNewV5(t *testing.T) { - u := NewV5(NamespaceDNS, "www.example.com") - - if u.Version() != 5 { - t.Errorf("UUIDv5 generated with incorrect version: %d", u.Version()) - } - - if u.Variant() != VariantRFC4122 { - t.Errorf("UUIDv5 generated with incorrect variant: %d", u.Variant()) - } - - u = NewV5(NamespaceDNS, "python.org") - - if u.String() != "886313e1-3b8a-5372-9b90-0c9aee199e5d" { - t.Errorf("UUIDv5 generated incorrectly: %s", u.String()) - } - - u1 := NewV5(NamespaceDNS, "golang.org") - u2 := NewV5(NamespaceDNS, "golang.org") - if !Equal(u1, u2) { - t.Errorf("UUIDv5 generated different UUIDs for same namespace and name: %s and %s", u1, u2) - } - - u3 := NewV5(NamespaceDNS, "example.com") - if Equal(u1, u3) { - t.Errorf("UUIDv5 generated same UUIDs for different names in same namespace: %s and %s", u1, u2) - } - - u4 := NewV5(NamespaceURL, "golang.org") - if Equal(u1, u4) { - t.Errorf("UUIDv3 generated same UUIDs for sane names in different namespaces: %s and %s", u1, u4) - } -} diff --git a/vendor/github.com/shurcooL/githubql/BUILD b/vendor/github.com/shurcooL/githubql/BUILD index 7f27649303f0..da8b90055ee4 100644 --- a/vendor/github.com/shurcooL/githubql/BUILD +++ b/vendor/github.com/shurcooL/githubql/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -14,16 +14,6 @@ go_library( deps = ["//vendor/github.com/shurcooL/graphql:go_default_library"], ) -go_test( - name = "go_default_xtest", - srcs = [ - "githubql_test.go", - "scalar_test.go", - ], - importpath = "github.com/shurcooL/githubql_test", - deps = [":go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/shurcooL/githubql/githubql_test.go b/vendor/github.com/shurcooL/githubql/githubql_test.go deleted file mode 100644 index c0d624b2bf69..000000000000 --- a/vendor/github.com/shurcooL/githubql/githubql_test.go +++ /dev/null @@ -1,289 +0,0 @@ -package githubql_test - -import ( - "context" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "reflect" - "testing" - "time" - - "github.com/shurcooL/githubql" -) - -func TestNewClient_nil(t *testing.T) { - // Shouldn't panic with nil parameter. - client := githubql.NewClient(nil) - _ = client -} - -func TestClient_Query(t *testing.T) { - mux := http.NewServeMux() - mux.HandleFunc("/graphql", func(w http.ResponseWriter, req *http.Request) { - if got, want := req.Method, http.MethodPost; got != want { - t.Errorf("got request method: %v, want: %v", got, want) - } - body := mustRead(req.Body) - if got, want := body, `{"query":"{viewer{login,bio}}"}`+"\n"; got != want { - t.Errorf("got body: %v, want %v", got, want) - } - mustWrite(w, `{"data": {"viewer": {"login": "gopher", "bio": "The Go gopher."}}}`) - }) - client := githubql.NewClient(&http.Client{Transport: localRoundTripper{mux: mux}}) - - type query struct { - Viewer struct { - Login githubql.String - Biography githubql.String `graphql:"bio"` // GraphQL alias. - } - } - - var q query - err := client.Query(context.Background(), &q, nil) - if err != nil { - t.Fatal(err) - } - got := q - - var want query - want.Viewer.Login = "gopher" - want.Viewer.Biography = "The Go gopher." - if !reflect.DeepEqual(got, want) { - t.Errorf("client.Query got: %v, want: %v", got, want) - } -} - -func TestClient_Query_errorResponse(t *testing.T) { - mux := http.NewServeMux() - mux.HandleFunc("/graphql", func(w http.ResponseWriter, req *http.Request) { - mustWrite(w, `{ - "data": null, - "errors": [ - { - "message": "Field 'bad' doesn't exist on type 'Query'", - "locations": [ - { - "line": 7, - "column": 3 - } - ] - } - ] - }`) - }) - client := githubql.NewClient(&http.Client{Transport: localRoundTripper{mux: mux}}) - - var q struct { - Bad githubql.String - } - err := client.Query(context.Background(), &q, nil) - if err == nil { - t.Fatal("got error: nil, want: non-nil") - } - if got, want := err.Error(), "Field 'bad' doesn't exist on type 'Query'"; got != want { - t.Errorf("got error: %v, want: %v", got, want) - } -} - -func TestClient_Query_errorStatusCode(t *testing.T) { - mux := http.NewServeMux() - mux.HandleFunc("/graphql", func(w http.ResponseWriter, req *http.Request) { - http.Error(w, "404 Not Found", http.StatusNotFound) - }) - client := githubql.NewClient(&http.Client{Transport: localRoundTripper{mux: mux}}) - - var q struct { - Viewer struct { - Login githubql.String - } - } - err := client.Query(context.Background(), &q, nil) - if err == nil { - t.Fatal("got error: nil, want: non-nil") - } - if got, want := err.Error(), "unexpected status: 404 Not Found"; got != want { - t.Errorf("got error: %v, want: %v", got, want) - } -} - -func TestClient_Query_union(t *testing.T) { - mux := http.NewServeMux() - mux.HandleFunc("/graphql", func(w http.ResponseWriter, req *http.Request) { - if got, want := req.Method, http.MethodPost; got != want { - t.Errorf("got request method: %v, want: %v", got, want) - } - body := mustRead(req.Body) - if got, want := body, `{"query":"query($issueNumber:Int!$repositoryName:String!$repositoryOwner:String!){repository(owner: $repositoryOwner, name: $repositoryName){issue(number: $issueNumber){timeline(first: 10){nodes{__typename,...on ClosedEvent{actor{login},createdAt},...on ReopenedEvent{actor{login},createdAt},...on RenamedTitleEvent{actor{login},createdAt,currentTitle,previousTitle}}}}}}","variables":{"issueNumber":1,"repositoryName":"go","repositoryOwner":"golang"}}`+"\n"; got != want { - t.Errorf("got body: %v, want %v", got, want) - } - mustWrite(w, `{"data": { - "repository": { - "issue": { - "timeline": { - "nodes": [ - { - "__typename": "RenamedTitleEvent", - "createdAt": "2017-06-29T04:12:01Z", - "actor": { - "login": "gopher" - }, - "currentTitle": "new", - "previousTitle": "old" - } - ] - } - } - } - }}`) - }) - client := githubql.NewClient(&http.Client{Transport: localRoundTripper{mux: mux}}) - - type event struct { // Common fields for all events. - Actor struct{ Login githubql.String } - CreatedAt githubql.DateTime - } - type issueTimelineItem struct { - Typename string `graphql:"__typename"` - ClosedEvent struct { - event - } `graphql:"...on ClosedEvent"` - ReopenedEvent struct { - event - } `graphql:"...on ReopenedEvent"` - RenamedTitleEvent struct { - event - CurrentTitle string - PreviousTitle string - } `graphql:"...on RenamedTitleEvent"` - } - type query struct { - Repository struct { - Issue struct { - Timeline struct { - Nodes []issueTimelineItem - } `graphql:"timeline(first: 10)"` - } `graphql:"issue(number: $issueNumber)"` - } `graphql:"repository(owner: $repositoryOwner, name: $repositoryName)"` - } - - var q query - variables := map[string]interface{}{ - "repositoryOwner": githubql.String("golang"), - "repositoryName": githubql.String("go"), - "issueNumber": githubql.Int(1), - } - err := client.Query(context.Background(), &q, variables) - if err != nil { - t.Fatal(err) - } - got := q - - var want query - want.Repository.Issue.Timeline.Nodes = make([]issueTimelineItem, 1) - want.Repository.Issue.Timeline.Nodes[0].Typename = "RenamedTitleEvent" - want.Repository.Issue.Timeline.Nodes[0].RenamedTitleEvent.Actor.Login = "gopher" - want.Repository.Issue.Timeline.Nodes[0].RenamedTitleEvent.CreatedAt.Time = time.Unix(1498709521, 0).UTC() - want.Repository.Issue.Timeline.Nodes[0].RenamedTitleEvent.CurrentTitle = "new" - want.Repository.Issue.Timeline.Nodes[0].RenamedTitleEvent.PreviousTitle = "old" - want.Repository.Issue.Timeline.Nodes[0].ClosedEvent.event = want.Repository.Issue.Timeline.Nodes[0].RenamedTitleEvent.event - want.Repository.Issue.Timeline.Nodes[0].ReopenedEvent.event = want.Repository.Issue.Timeline.Nodes[0].RenamedTitleEvent.event - if !reflect.DeepEqual(got, want) { - t.Errorf("client.Query:\ngot: %+v\nwant: %+v", got, want) - } -} - -func TestClient_Mutate(t *testing.T) { - mux := http.NewServeMux() - mux.HandleFunc("/graphql", func(w http.ResponseWriter, req *http.Request) { - if got, want := req.Method, http.MethodPost; got != want { - t.Errorf("got request method: %v, want: %v", got, want) - } - body := mustRead(req.Body) - if got, want := body, `{"query":"mutation($input:AddReactionInput!){addReaction(input:$input){reaction{content},subject{id,reactionGroups{users{totalCount}}}}}","variables":{"input":{"subjectId":"MDU6SXNzdWUyMTc5NTQ0OTc=","content":"HOORAY"}}}`+"\n"; got != want { - t.Errorf("got body: %v, want %v", got, want) - } - mustWrite(w, `{"data": { - "addReaction": { - "reaction": { - "content": "HOORAY" - }, - "subject": { - "id": "MDU6SXNzdWUyMTc5NTQ0OTc=", - "reactionGroups": [ - { - "users": {"totalCount": 3} - } - ] - } - } - }}`) - }) - client := githubql.NewClient(&http.Client{Transport: localRoundTripper{mux: mux}}) - - type reactionGroup struct { - Users struct { - TotalCount githubql.Int - } - } - type mutation struct { - AddReaction struct { - Reaction struct { - Content githubql.ReactionContent - } - Subject struct { - ID githubql.ID - ReactionGroups []reactionGroup - } - } `graphql:"addReaction(input:$input)"` - } - - var m mutation - input := githubql.AddReactionInput{ - SubjectID: "MDU6SXNzdWUyMTc5NTQ0OTc=", - Content: githubql.ReactionContentHooray, - } - err := client.Mutate(context.Background(), &m, input, nil) - if err != nil { - t.Fatal(err) - } - got := m - - var want mutation - want.AddReaction.Reaction.Content = githubql.ReactionContentHooray - want.AddReaction.Subject.ID = "MDU6SXNzdWUyMTc5NTQ0OTc=" - var rg reactionGroup - rg.Users.TotalCount = 3 - want.AddReaction.Subject.ReactionGroups = []reactionGroup{rg} - if !reflect.DeepEqual(got, want) { - t.Errorf("client.Query got: %v, want: %v", got, want) - } -} - -// localRoundTripper is an http.RoundTripper that executes HTTP transactions -// by using mux directly, instead of going over an HTTP connection. -type localRoundTripper struct { - mux *http.ServeMux -} - -func (l localRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - w := httptest.NewRecorder() - l.mux.ServeHTTP(w, req) - return w.Result(), nil -} - -func mustRead(r io.Reader) string { - b, err := ioutil.ReadAll(r) - if err != nil { - panic(err) - } - return string(b) -} - -func mustWrite(w io.Writer, s string) { - _, err := io.WriteString(w, s) - if err != nil { - panic(err) - } -} diff --git a/vendor/github.com/shurcooL/githubql/scalar_test.go b/vendor/github.com/shurcooL/githubql/scalar_test.go deleted file mode 100644 index 12251a583563..000000000000 --- a/vendor/github.com/shurcooL/githubql/scalar_test.go +++ /dev/null @@ -1,117 +0,0 @@ -package githubql_test - -import ( - "encoding/json" - "errors" - "net/url" - "reflect" - "testing" - - "github.com/shurcooL/githubql" -) - -func TestURI_MarshalJSON(t *testing.T) { - tests := []struct { - name string - in githubql.URI - want string - }{ - { - in: githubql.URI{URL: &url.URL{Scheme: "https", Host: "example.org", Path: "/foo/bar"}}, - want: `"https://example.org/foo/bar"`, - }, - } - for _, tc := range tests { - got, err := json.Marshal(tc.in) - if err != nil { - t.Fatalf("%s: got error: %v", tc.name, err) - } - if string(got) != tc.want { - t.Errorf("%s: got: %q, want: %q", tc.name, string(got), tc.want) - } - } -} - -func TestURI_UnmarshalJSON(t *testing.T) { - tests := []struct { - name string - in string - want githubql.URI - wantError error - }{ - { - in: `"https://example.org/foo/bar"`, - want: githubql.URI{URL: &url.URL{Scheme: "https", Host: "example.org", Path: "/foo/bar"}}, - }, - { - name: "null", - in: `null`, - want: githubql.URI{}, - }, - { - name: "error JSON unmarshaling into string", - in: `86`, - wantError: errors.New("json: cannot unmarshal number into Go value of type string"), - }, - } - for _, tc := range tests { - var got githubql.URI - err := json.Unmarshal([]byte(tc.in), &got) - if got, want := err, tc.wantError; !equalError(got, want) { - t.Fatalf("%s: got error: %v, want: %v", tc.name, got, want) - } - if tc.wantError != nil { - continue - } - if !reflect.DeepEqual(got, tc.want) { - t.Errorf("%s: got: %v, want: %v", tc.name, got, tc.want) - } - } -} - -// equalError reports whether errors a and b are considered equal. -// They're equal if both are nil, or both are not nil and a.Error() == b.Error(). -func equalError(a, b error) bool { - return a == nil && b == nil || a != nil && b != nil && a.Error() == b.Error() -} - -func TestNewScalars(t *testing.T) { - if got := githubql.NewBoolean(false); got == nil { - t.Error("NewBoolean returned nil") - } - if got := githubql.NewDateTime(githubql.DateTime{}); got == nil { - t.Error("NewDateTime returned nil") - } - if got := githubql.NewFloat(0.0); got == nil { - t.Error("NewFloat returned nil") - } - if got := githubql.NewGitObjectID(""); got == nil { - t.Error("NewGitObjectID returned nil") - } - if got := githubql.NewGitTimestamp(githubql.GitTimestamp{}); got == nil { - t.Error("NewGitTimestamp returned nil") - } - if got := githubql.NewHTML(""); got == nil { - t.Error("NewHTML returned nil") - } - // ID with underlying type string. - if got := githubql.NewID(""); got == nil { - t.Error("NewID returned nil") - } - // ID with underlying type int. - if got := githubql.NewID(0); got == nil { - t.Error("NewID returned nil") - } - if got := githubql.NewInt(0); got == nil { - t.Error("NewInt returned nil") - } - if got := githubql.NewString(""); got == nil { - t.Error("NewString returned nil") - } - if got := githubql.NewURI(githubql.URI{}); got == nil { - t.Error("NewURI returned nil") - } - if got := githubql.NewX509Certificate(githubql.X509Certificate{}); got == nil { - t.Error("NewX509Certificate returned nil") - } -} diff --git a/vendor/github.com/shurcooL/go/ctxhttp/BUILD b/vendor/github.com/shurcooL/go/ctxhttp/BUILD index d197732f3cda..da1cd8201a85 100644 --- a/vendor/github.com/shurcooL/go/ctxhttp/BUILD +++ b/vendor/github.com/shurcooL/go/ctxhttp/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -7,13 +7,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = ["ctxhttp_test.go"], - importpath = "github.com/shurcooL/go/ctxhttp", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/shurcooL/go/ctxhttp/ctxhttp_test.go b/vendor/github.com/shurcooL/go/ctxhttp/ctxhttp_test.go deleted file mode 100644 index 812efeca8f1d..000000000000 --- a/vendor/github.com/shurcooL/go/ctxhttp/ctxhttp_test.go +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.7 -// +build !plan9 - -package ctxhttp - -import ( - "context" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - "time" -) - -func TestGo17Context(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, "ok") - })) - ctx := context.Background() - resp, err := Get(ctx, http.DefaultClient, ts.URL) - if resp == nil || err != nil { - t.Fatalf("error received from client: %v %v", err, resp) - } - resp.Body.Close() -} - -const ( - requestDuration = 100 * time.Millisecond - requestBody = "ok" -) - -func okHandler(w http.ResponseWriter, r *http.Request) { - time.Sleep(requestDuration) - io.WriteString(w, requestBody) -} - -func TestNoTimeout(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(okHandler)) - defer ts.Close() - - ctx := context.Background() - res, err := Get(ctx, nil, ts.URL) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Fatal(err) - } - if string(slurp) != requestBody { - t.Errorf("body = %q; want %q", slurp, requestBody) - } -} - -func TestCancelBeforeHeaders(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - - blockServer := make(chan struct{}) - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - cancel() - <-blockServer - io.WriteString(w, requestBody) - })) - defer ts.Close() - defer close(blockServer) - - res, err := Get(ctx, nil, ts.URL) - if err == nil { - res.Body.Close() - t.Fatal("Get returned unexpected nil error") - } - if err != context.Canceled { - t.Errorf("err = %v; want %v", err, context.Canceled) - } -} - -func TestCancelAfterHangingRequest(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - w.(http.Flusher).Flush() - <-w.(http.CloseNotifier).CloseNotify() - })) - defer ts.Close() - - ctx, cancel := context.WithCancel(context.Background()) - resp, err := Get(ctx, nil, ts.URL) - if err != nil { - t.Fatalf("unexpected error in Get: %v", err) - } - - // Cancel befer reading the body. - // Reading Request.Body should fail, since the request was - // canceled before anything was written. - cancel() - - done := make(chan struct{}) - - go func() { - b, err := ioutil.ReadAll(resp.Body) - if len(b) != 0 || err == nil { - t.Errorf(`Read got (%q, %v); want ("", error)`, b, err) - } - close(done) - }() - - select { - case <-time.After(1 * time.Second): - t.Errorf("Test timed out") - case <-done: - } -} diff --git a/vendor/github.com/shurcooL/graphql/BUILD b/vendor/github.com/shurcooL/graphql/BUILD index 399f64251388..e1ea36079f06 100644 --- a/vendor/github.com/shurcooL/graphql/BUILD +++ b/vendor/github.com/shurcooL/graphql/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -17,20 +17,6 @@ go_library( ], ) -go_test( - name = "go_default_test", - srcs = ["query_test.go"], - importpath = "github.com/shurcooL/graphql", - library = ":go_default_library", -) - -go_test( - name = "go_default_xtest", - srcs = ["scalar_test.go"], - importpath = "github.com/shurcooL/graphql_test", - deps = [":go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/shurcooL/graphql/ident/BUILD b/vendor/github.com/shurcooL/graphql/ident/BUILD index f5c3fdeeb3d8..2fa75e209fde 100644 --- a/vendor/github.com/shurcooL/graphql/ident/BUILD +++ b/vendor/github.com/shurcooL/graphql/ident/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -7,13 +7,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_xtest", - srcs = ["ident_test.go"], - importpath = "github.com/shurcooL/graphql/ident_test", - deps = [":go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/shurcooL/graphql/ident/ident_test.go b/vendor/github.com/shurcooL/graphql/ident/ident_test.go deleted file mode 100644 index 9a1562b737ef..000000000000 --- a/vendor/github.com/shurcooL/graphql/ident/ident_test.go +++ /dev/null @@ -1,164 +0,0 @@ -package ident_test - -import ( - "fmt" - "reflect" - "testing" - - "github.com/shurcooL/graphql/ident" -) - -func Example_lowerCamelCaseToMixedCaps() { - fmt.Println(ident.ParseLowerCamelCase("clientMutationId").ToMixedCaps()) - - // Output: ClientMutationID -} - -func Example_screamingSnakeCaseToMixedCaps() { - fmt.Println(ident.ParseScreamingSnakeCase("CLIENT_MUTATION_ID").ToMixedCaps()) - - // Output: ClientMutationID -} - -func Example_mixedCapsToLowerCamelCase() { - fmt.Println(ident.ParseMixedCaps("ClientMutationID").ToLowerCamelCase()) - - // Output: clientMutationId -} - -func TestParseMixedCaps(t *testing.T) { - tests := []struct { - in string - want ident.Name - }{ - {in: "ClientMutationID", want: ident.Name{"Client", "Mutation", "ID"}}, - {in: "StringURLAppend", want: ident.Name{"String", "URL", "Append"}}, - {in: "URLFrom", want: ident.Name{"URL", "From"}}, - {in: "SetURL", want: ident.Name{"Set", "URL"}}, - {in: "UIIP", want: ident.Name{"UI", "IP"}}, - {in: "URLHTMLFrom", want: ident.Name{"URL", "HTML", "From"}}, - {in: "SetURLHTML", want: ident.Name{"Set", "URL", "HTML"}}, - {in: "HTTPSQL", want: ident.Name{"HTTP", "SQL"}}, - {in: "HTTPSSQL", want: ident.Name{"HTTPS", "SQL"}}, - {in: "UserIDs", want: ident.Name{"User", "IDs"}}, - {in: "TeamIDsSorted", want: ident.Name{"Team", "IDs", "Sorted"}}, - } - for _, tc := range tests { - got := ident.ParseMixedCaps(tc.in) - if !reflect.DeepEqual(got, tc.want) { - t.Errorf("got: %q, want: %q", got, tc.want) - } - } -} - -func TestParseLowerCamelCase(t *testing.T) { - tests := []struct { - in string - want ident.Name - }{ - {in: "clientMutationId", want: ident.Name{"client", "Mutation", "Id"}}, - } - for _, tc := range tests { - got := ident.ParseLowerCamelCase(tc.in) - if !reflect.DeepEqual(got, tc.want) { - t.Errorf("got: %q, want: %q", got, tc.want) - } - } -} - -func TestParseScreamingSnakeCase(t *testing.T) { - tests := []struct { - in string - want ident.Name - }{ - {in: "CLIENT_MUTATION_ID", want: ident.Name{"CLIENT", "MUTATION", "ID"}}, - } - for _, tc := range tests { - got := ident.ParseScreamingSnakeCase(tc.in) - if !reflect.DeepEqual(got, tc.want) { - t.Errorf("got: %q, want: %q", got, tc.want) - } - } -} - -func TestWords_ToMixedCaps(t *testing.T) { - tests := []struct { - in ident.Name - want string - }{ - {in: ident.Name{"client", "Mutation", "Id"}, want: "ClientMutationID"}, - {in: ident.Name{"CLIENT", "MUTATION", "ID"}, want: "ClientMutationID"}, - } - for _, tc := range tests { - got := tc.in.ToMixedCaps() - if got != tc.want { - t.Errorf("got: %q, want: %q", got, tc.want) - } - } -} - -func TestWords_ToLowerCamelCase(t *testing.T) { - tests := []struct { - in ident.Name - want string - }{ - {in: ident.Name{"client", "Mutation", "Id"}, want: "clientMutationId"}, - {in: ident.Name{"CLIENT", "MUTATION", "ID"}, want: "clientMutationId"}, - } - for _, tc := range tests { - got := tc.in.ToLowerCamelCase() - if got != tc.want { - t.Errorf("got: %q, want: %q", got, tc.want) - } - } -} - -func TestMixedCapsToLowerCamelCase(t *testing.T) { - tests := []struct { - in string - want string - }{ - {in: "DatabaseID", want: "databaseId"}, - {in: "URL", want: "url"}, - {in: "ID", want: "id"}, - {in: "CreatedAt", want: "createdAt"}, - {in: "Login", want: "login"}, - {in: "ResetAt", want: "resetAt"}, - {in: "ID", want: "id"}, - {in: "IDs", want: "ids"}, - {in: "IDsAndNames", want: "idsAndNames"}, - {in: "UserIDs", want: "userIds"}, - {in: "TeamIDsSorted", want: "teamIdsSorted"}, - } - for _, tc := range tests { - got := ident.ParseMixedCaps(tc.in).ToLowerCamelCase() - if got != tc.want { - t.Errorf("got: %q, want: %q", got, tc.want) - } - } -} - -func TestLowerCamelCaseToMixedCaps(t *testing.T) { - tests := []struct { - in string - want string - }{ - {in: "databaseId", want: "DatabaseID"}, - {in: "url", want: "URL"}, - {in: "id", want: "ID"}, - {in: "createdAt", want: "CreatedAt"}, - {in: "login", want: "Login"}, - {in: "resetAt", want: "ResetAt"}, - {in: "id", want: "ID"}, - {in: "ids", want: "IDs"}, - {in: "idsAndNames", want: "IDsAndNames"}, - {in: "userIds", want: "UserIDs"}, - {in: "teamIdsSorted", want: "TeamIDsSorted"}, - } - for _, tc := range tests { - got := ident.ParseLowerCamelCase(tc.in).ToMixedCaps() - if got != tc.want { - t.Errorf("got: %q, want: %q", got, tc.want) - } - } -} diff --git a/vendor/github.com/shurcooL/graphql/internal/jsonutil/BUILD b/vendor/github.com/shurcooL/graphql/internal/jsonutil/BUILD index cd29c18e03e2..fb8c83e2d3b6 100644 --- a/vendor/github.com/shurcooL/graphql/internal/jsonutil/BUILD +++ b/vendor/github.com/shurcooL/graphql/internal/jsonutil/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -7,19 +7,6 @@ go_library( visibility = ["//vendor/github.com/shurcooL/graphql:__subpackages__"], ) -go_test( - name = "go_default_xtest", - srcs = [ - "benchmark_test.go", - "graphql_test.go", - ], - importpath = "github.com/shurcooL/graphql/internal/jsonutil_test", - deps = [ - ":go_default_library", - "//vendor/github.com/shurcooL/graphql:go_default_library", - ], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/shurcooL/graphql/internal/jsonutil/benchmark_test.go b/vendor/github.com/shurcooL/graphql/internal/jsonutil/benchmark_test.go deleted file mode 100644 index f8788b169d98..000000000000 --- a/vendor/github.com/shurcooL/graphql/internal/jsonutil/benchmark_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package jsonutil_test - -import ( - "encoding/json" - "io" - "reflect" - "strings" - "testing" - "time" - - "github.com/shurcooL/graphql" - "github.com/shurcooL/graphql/internal/jsonutil" -) - -func TestUnmarshalGraphQL_benchmark(t *testing.T) { - /* - query { - viewer { - login - createdAt - } - } - */ - type query struct { - Viewer struct { - Login graphql.String - CreatedAt time.Time - } - } - var got query - err := jsonutil.UnmarshalGraphQL([]byte(`{ - "viewer": { - "login": "shurcooL-test", - "createdAt": "2017-06-29T04:12:01Z" - } - }`), &got) - if err != nil { - t.Fatal(err) - } - var want query - want.Viewer.Login = "shurcooL-test" - want.Viewer.CreatedAt = time.Unix(1498709521, 0).UTC() - if !reflect.DeepEqual(got, want) { - t.Error("not equal") - } -} - -func BenchmarkUnmarshalGraphQL(b *testing.B) { - type query struct { - Viewer struct { - Login graphql.String - CreatedAt time.Time - } - } - for i := 0; i < b.N; i++ { - now := time.Now().UTC() - var got query - err := jsonutil.UnmarshalGraphQL([]byte(`{ - "viewer": { - "login": "shurcooL-test", - "createdAt": "`+now.Format(time.RFC3339Nano)+`" - } - }`), &got) - if err != nil { - b.Fatal(err) - } - var want query - want.Viewer.Login = "shurcooL-test" - want.Viewer.CreatedAt = now - if !reflect.DeepEqual(got, want) { - b.Error("not equal") - } - } -} - -func BenchmarkJSONUnmarshal(b *testing.B) { - type query struct { - Viewer struct { - Login graphql.String - CreatedAt time.Time - } - } - for i := 0; i < b.N; i++ { - now := time.Now().UTC() - var got query - err := json.Unmarshal([]byte(`{ - "viewer": { - "login": "shurcooL-test", - "createdAt": "`+now.Format(time.RFC3339Nano)+`" - } - }`), &got) - if err != nil { - b.Fatal(err) - } - var want query - want.Viewer.Login = "shurcooL-test" - want.Viewer.CreatedAt = now - if !reflect.DeepEqual(got, want) { - b.Error("not equal") - } - } -} - -func BenchmarkJSONTokenize(b *testing.B) { - for i := 0; i < b.N; i++ { - now := time.Now().UTC() - dec := json.NewDecoder(strings.NewReader(`{ - "viewer": { - "login": "shurcooL-test", - "createdAt": "` + now.Format(time.RFC3339Nano) + `" - } - }`)) - var tokens int - for { - _, err := dec.Token() - if err == io.EOF { - break - } else if err != nil { - b.Error(err) - } - tokens++ - } - if tokens != 9 { - b.Error("not 9 tokens") - } - } -} diff --git a/vendor/github.com/shurcooL/graphql/internal/jsonutil/graphql_test.go b/vendor/github.com/shurcooL/graphql/internal/jsonutil/graphql_test.go deleted file mode 100644 index 63b0650b3a91..000000000000 --- a/vendor/github.com/shurcooL/graphql/internal/jsonutil/graphql_test.go +++ /dev/null @@ -1,336 +0,0 @@ -package jsonutil_test - -import ( - "reflect" - "testing" - "time" - - "github.com/shurcooL/graphql" - "github.com/shurcooL/graphql/internal/jsonutil" -) - -func TestUnmarshalGraphQL(t *testing.T) { - /* - query { - me { - name - height - } - } - */ - type query struct { - Me struct { - Name graphql.String - Height graphql.Float - } - } - var got query - err := jsonutil.UnmarshalGraphQL([]byte(`{ - "me": { - "name": "Luke Skywalker", - "height": 1.72 - } - }`), &got) - if err != nil { - t.Fatal(err) - } - var want query - want.Me.Name = "Luke Skywalker" - want.Me.Height = 1.72 - if !reflect.DeepEqual(got, want) { - t.Error("not equal") - } -} - -func TestUnmarshalGraphQL_graphqlTag(t *testing.T) { - type query struct { - Foo graphql.String `graphql:"baz"` - } - var got query - err := jsonutil.UnmarshalGraphQL([]byte(`{ - "baz": "bar" - }`), &got) - if err != nil { - t.Fatal(err) - } - want := query{ - Foo: "bar", - } - if !reflect.DeepEqual(got, want) { - t.Error("not equal") - } -} - -func TestUnmarshalGraphQL_jsonTag(t *testing.T) { - type query struct { - Foo graphql.String `json:"baz"` - } - var got query - err := jsonutil.UnmarshalGraphQL([]byte(`{ - "foo": "bar" - }`), &got) - if err != nil { - t.Fatal(err) - } - want := query{ - Foo: "bar", - } - if !reflect.DeepEqual(got, want) { - t.Error("not equal") - } -} - -func TestUnmarshalGraphQL_array(t *testing.T) { - type query struct { - Foo []graphql.String - } - var got query - err := jsonutil.UnmarshalGraphQL([]byte(`{ - "foo": [ - "bar", - "baz" - ] - }`), &got) - if err != nil { - t.Fatal(err) - } - want := query{ - Foo: []graphql.String{"bar", "baz"}, - } - if !reflect.DeepEqual(got, want) { - t.Error("not equal") - } -} - -// When unmarshaling into an array, its initial value should be overwritten -// (rather than appended to). -func TestUnmarshalGraphQL_arrayReset(t *testing.T) { - var got = []string{"initial"} - err := jsonutil.UnmarshalGraphQL([]byte(`["bar", "baz"]`), &got) - if err != nil { - t.Fatal(err) - } - want := []string{"bar", "baz"} - if !reflect.DeepEqual(got, want) { - t.Error("not equal") - } -} - -func TestUnmarshalGraphQL_objectArray(t *testing.T) { - type query struct { - Foo []struct { - Name graphql.String - } - } - var got query - err := jsonutil.UnmarshalGraphQL([]byte(`{ - "foo": [ - {"name": "bar"}, - {"name": "baz"} - ] - }`), &got) - if err != nil { - t.Fatal(err) - } - want := query{ - Foo: []struct{ Name graphql.String }{ - {"bar"}, - {"baz"}, - }, - } - if !reflect.DeepEqual(got, want) { - t.Error("not equal") - } -} - -func TestUnmarshalGraphQL_pointer(t *testing.T) { - type query struct { - Foo *graphql.String - Bar *graphql.String - } - var got query - got.Bar = new(graphql.String) // Test that got.Bar gets set to nil. - err := jsonutil.UnmarshalGraphQL([]byte(`{ - "foo": "foo", - "bar": null - }`), &got) - if err != nil { - t.Fatal(err) - } - want := query{ - Foo: graphql.NewString("foo"), - Bar: nil, - } - if !reflect.DeepEqual(got, want) { - t.Error("not equal") - } -} - -func TestUnmarshalGraphQL_objectPointerArray(t *testing.T) { - type query struct { - Foo []*struct { - Name graphql.String - } - } - var got query - err := jsonutil.UnmarshalGraphQL([]byte(`{ - "foo": [ - {"name": "bar"}, - null, - {"name": "baz"} - ] - }`), &got) - if err != nil { - t.Fatal(err) - } - want := query{ - Foo: []*struct{ Name graphql.String }{ - {"bar"}, - nil, - {"baz"}, - }, - } - if !reflect.DeepEqual(got, want) { - t.Error("not equal") - } -} - -func TestUnmarshalGraphQL_multipleValues(t *testing.T) { - type query struct { - Foo graphql.String - } - err := jsonutil.UnmarshalGraphQL([]byte(`{"foo": "bar"}{"foo": "baz"}`), new(query)) - if err == nil { - t.Fatal("got error: nil, want: non-nil") - } - if got, want := err.Error(), "invalid token '{' after top-level value"; got != want { - t.Errorf("got error: %v, want: %v", got, want) - } -} - -func TestUnmarshalGraphQL_union(t *testing.T) { - /* - { - __typename - ... on ClosedEvent { - createdAt - actor {login} - } - ... on ReopenedEvent { - createdAt - actor {login} - } - } - */ - type actor struct{ Login graphql.String } - type closedEvent struct { - Actor actor - CreatedAt time.Time - } - type reopenedEvent struct { - Actor actor - CreatedAt time.Time - } - type issueTimelineItem struct { - Typename string `graphql:"__typename"` - ClosedEvent closedEvent `graphql:"... on ClosedEvent"` - ReopenedEvent reopenedEvent `graphql:"... on ReopenedEvent"` - } - var got issueTimelineItem - err := jsonutil.UnmarshalGraphQL([]byte(`{ - "__typename": "ClosedEvent", - "createdAt": "2017-06-29T04:12:01Z", - "actor": { - "login": "shurcooL-test" - } - }`), &got) - if err != nil { - t.Fatal(err) - } - want := issueTimelineItem{ - Typename: "ClosedEvent", - ClosedEvent: closedEvent{ - Actor: actor{ - Login: "shurcooL-test", - }, - CreatedAt: time.Unix(1498709521, 0).UTC(), - }, - ReopenedEvent: reopenedEvent{ - Actor: actor{ - Login: "shurcooL-test", - }, - CreatedAt: time.Unix(1498709521, 0).UTC(), - }, - } - if !reflect.DeepEqual(got, want) { - t.Error("not equal") - } -} - -// Issue https://github.com/shurcooL/githubql/issues/18. -func TestUnmarshalGraphQL_arrayInsideInlineFragment(t *testing.T) { - /* - query { - search(type: ISSUE, first: 1, query: "type:pr repo:owner/name") { - nodes { - ... on PullRequest { - commits(last: 1) { - nodes { - url - } - } - } - } - } - } - */ - type query struct { - Search struct { - Nodes []struct { - PullRequest struct { - Commits struct { - Nodes []struct { - URL string `graphql:"url"` - } - } `graphql:"commits(last: 1)"` - } `graphql:"... on PullRequest"` - } - } `graphql:"search(type: ISSUE, first: 1, query: \"type:pr repo:owner/name\")"` - } - var got query - err := jsonutil.UnmarshalGraphQL([]byte(`{ - "search": { - "nodes": [ - { - "commits": { - "nodes": [ - { - "url": "https://example.org/commit/49e1" - } - ] - } - } - ] - } - }`), &got) - if err != nil { - t.Fatal(err) - } - var want query - want.Search.Nodes = make([]struct { - PullRequest struct { - Commits struct { - Nodes []struct { - URL string `graphql:"url"` - } - } `graphql:"commits(last: 1)"` - } `graphql:"... on PullRequest"` - }, 1) - want.Search.Nodes[0].PullRequest.Commits.Nodes = make([]struct { - URL string `graphql:"url"` - }, 1) - want.Search.Nodes[0].PullRequest.Commits.Nodes[0].URL = "https://example.org/commit/49e1" - if !reflect.DeepEqual(got, want) { - t.Error("not equal") - } -} diff --git a/vendor/github.com/shurcooL/graphql/query_test.go b/vendor/github.com/shurcooL/graphql/query_test.go deleted file mode 100644 index 536b3008504e..000000000000 --- a/vendor/github.com/shurcooL/graphql/query_test.go +++ /dev/null @@ -1,345 +0,0 @@ -package graphql - -import ( - "net/url" - "reflect" - "testing" - "time" -) - -func TestConstructQuery(t *testing.T) { - tests := []struct { - inV interface{} - inVariables map[string]interface{} - want string - }{ - { - inV: struct { - Viewer struct { - Login String - CreatedAt DateTime - ID ID - DatabaseID Int - } - RateLimit struct { - Cost Int - Limit Int - Remaining Int - ResetAt DateTime - } - }{}, - want: `{viewer{login,createdAt,id,databaseId},rateLimit{cost,limit,remaining,resetAt}}`, - }, - { - inV: struct { - Repository struct { - DatabaseID Int - URL URI - - Issue struct { - Comments struct { - Edges []struct { - Node struct { - Body String - Author struct { - Login String - } - Editor struct { - Login String - } - } - Cursor String - } - } `graphql:"comments(first:1after:\"Y3Vyc29yOjE5NTE4NDI1Ng==\")"` - } `graphql:"issue(number:1)"` - } `graphql:"repository(owner:\"shurcooL-test\"name:\"test-repo\")"` - }{}, - want: `{repository(owner:"shurcooL-test"name:"test-repo"){databaseId,url,issue(number:1){comments(first:1after:"Y3Vyc29yOjE5NTE4NDI1Ng=="){edges{node{body,author{login},editor{login}},cursor}}}}}`, - }, - { - inV: func() interface{} { - type actor struct { - Login String - AvatarURL URI - URL URI - } - - return struct { - Repository struct { - DatabaseID Int - URL URI - - Issue struct { - Comments struct { - Edges []struct { - Node struct { - DatabaseID Int - Author actor - PublishedAt DateTime - LastEditedAt *DateTime - Editor *actor - Body String - ViewerCanUpdate Boolean - } - Cursor String - } - } `graphql:"comments(first:1)"` - } `graphql:"issue(number:1)"` - } `graphql:"repository(owner:\"shurcooL-test\"name:\"test-repo\")"` - }{} - }(), - want: `{repository(owner:"shurcooL-test"name:"test-repo"){databaseId,url,issue(number:1){comments(first:1){edges{node{databaseId,author{login,avatarUrl,url},publishedAt,lastEditedAt,editor{login,avatarUrl,url},body,viewerCanUpdate},cursor}}}}}`, - }, - { - inV: func() interface{} { - type actor struct { - Login String - AvatarURL URI `graphql:"avatarUrl(size:72)"` - URL URI - } - - return struct { - Repository struct { - Issue struct { - Author actor - PublishedAt DateTime - LastEditedAt *DateTime - Editor *actor - Body String - ReactionGroups []struct { - Content ReactionContent - Users struct { - TotalCount Int - } - ViewerHasReacted Boolean - } - ViewerCanUpdate Boolean - - Comments struct { - Nodes []struct { - DatabaseID Int - Author actor - PublishedAt DateTime - LastEditedAt *DateTime - Editor *actor - Body String - ReactionGroups []struct { - Content ReactionContent - Users struct { - TotalCount Int - } - ViewerHasReacted Boolean - } - ViewerCanUpdate Boolean - } - PageInfo struct { - EndCursor String - HasNextPage Boolean - } - } `graphql:"comments(first:1)"` - } `graphql:"issue(number:1)"` - } `graphql:"repository(owner:\"shurcooL-test\"name:\"test-repo\")"` - }{} - }(), - want: `{repository(owner:"shurcooL-test"name:"test-repo"){issue(number:1){author{login,avatarUrl(size:72),url},publishedAt,lastEditedAt,editor{login,avatarUrl(size:72),url},body,reactionGroups{content,users{totalCount},viewerHasReacted},viewerCanUpdate,comments(first:1){nodes{databaseId,author{login,avatarUrl(size:72),url},publishedAt,lastEditedAt,editor{login,avatarUrl(size:72),url},body,reactionGroups{content,users{totalCount},viewerHasReacted},viewerCanUpdate},pageInfo{endCursor,hasNextPage}}}}}`, - }, - { - inV: struct { - Repository struct { - Issue struct { - Body String - } `graphql:"issue(number: 1)"` - } `graphql:"repository(owner:\"shurcooL-test\"name:\"test-repo\")"` - }{}, - want: `{repository(owner:"shurcooL-test"name:"test-repo"){issue(number: 1){body}}}`, - }, - { - inV: struct { - Repository struct { - Issue struct { - Body String - } `graphql:"issue(number: $issueNumber)"` - } `graphql:"repository(owner: $repositoryOwner, name: $repositoryName)"` - }{}, - inVariables: map[string]interface{}{ - "repositoryOwner": String("shurcooL-test"), - "repositoryName": String("test-repo"), - "issueNumber": Int(1), - }, - want: `query($issueNumber:Int!$repositoryName:String!$repositoryOwner:String!){repository(owner: $repositoryOwner, name: $repositoryName){issue(number: $issueNumber){body}}}`, - }, - { - inV: struct { - Repository struct { - Issue struct { - ReactionGroups []struct { - Users struct { - Nodes []struct { - Login String - } - } `graphql:"users(first:10)"` - } - } `graphql:"issue(number: $issueNumber)"` - } `graphql:"repository(owner: $repositoryOwner, name: $repositoryName)"` - }{}, - inVariables: map[string]interface{}{ - "repositoryOwner": String("shurcooL-test"), - "repositoryName": String("test-repo"), - "issueNumber": Int(1), - }, - want: `query($issueNumber:Int!$repositoryName:String!$repositoryOwner:String!){repository(owner: $repositoryOwner, name: $repositoryName){issue(number: $issueNumber){reactionGroups{users(first:10){nodes{login}}}}}}`, - }, - // Embedded structs without graphql tag should be inlined in query. - { - inV: func() interface{} { - type actor struct { - Login String - AvatarURL URI - URL URI - } - type event struct { // Common fields for all events. - Actor actor - CreatedAt DateTime - } - type IssueComment struct { - Body String - } - return struct { - event // Should be inlined. - IssueComment `graphql:"... on IssueComment"` // Should not be, because of graphql tag. - CurrentTitle String - PreviousTitle String - Label struct { - Name String - Color String - } - }{} - }(), - want: `{actor{login,avatarUrl,url},createdAt,... on IssueComment{body},currentTitle,previousTitle,label{name,color}}`, - }, - } - for _, tc := range tests { - qctx := &queryContext{ - Scalars: []reflect.Type{ - reflect.TypeOf(DateTime{}), - reflect.TypeOf(URI{}), - }, - } - got := constructQuery(qctx, tc.inV, tc.inVariables) - if got != tc.want { - t.Errorf("\ngot: %q\nwant: %q\n", got, tc.want) - } - } -} - -func TestConstructMutation(t *testing.T) { - tests := []struct { - inV interface{} - inVariables map[string]interface{} - want string - }{ - { - inV: struct { - AddReaction struct { - Subject struct { - ReactionGroups []struct { - Users struct { - TotalCount Int - } - } - } - } `graphql:"addReaction(input:$input)"` - }{}, - inVariables: map[string]interface{}{ - "input": AddReactionInput{ - SubjectID: "MDU6SXNzdWUyMzE1MjcyNzk=", - Content: ReactionContentThumbsUp, - }, - }, - want: `mutation($input:AddReactionInput!){addReaction(input:$input){subject{reactionGroups{users{totalCount}}}}}`, - }, - } - for _, tc := range tests { - got := constructMutation(&queryContext{}, tc.inV, tc.inVariables) - if got != tc.want { - t.Errorf("\ngot: %q\nwant: %q\n", got, tc.want) - } - } -} - -func TestQueryArguments(t *testing.T) { - tests := []struct { - name string - in map[string]interface{} - want string - }{ - { - in: map[string]interface{}{"a": Int(123), "b": NewBoolean(true)}, - want: "$a:Int!$b:Boolean", - }, - { - in: map[string]interface{}{"states": []IssueState{IssueStateOpen, IssueStateClosed}}, - want: "$states:[IssueState!]", - }, - { - in: map[string]interface{}{"states": []IssueState(nil)}, - want: "$states:[IssueState!]", - }, - { - in: map[string]interface{}{"states": [...]IssueState{IssueStateOpen, IssueStateClosed}}, - want: "$states:[IssueState!]", - }, - { - in: map[string]interface{}{"id": ID("someid")}, - want: "$id:ID!", - }, - } - for _, tc := range tests { - got := queryArguments(tc.in) - if got != tc.want { - t.Errorf("%s: got: %q, want: %q", tc.name, got, tc.want) - } - } -} - -// Custom GraphQL types for testing. -type ( - // DateTime is an ISO-8601 encoded UTC date. - DateTime struct{ time.Time } - - // URI is an RFC 3986, RFC 3987, and RFC 6570 (level 4) compliant URI. - URI struct{ *url.URL } -) - -// IssueState represents the possible states of an issue. -type IssueState string - -// The possible states of an issue. -const ( - IssueStateOpen IssueState = "OPEN" // An issue that is still open. - IssueStateClosed IssueState = "CLOSED" // An issue that has been closed. -) - -// ReactionContent represents emojis that can be attached to Issues, Pull Requests and Comments. -type ReactionContent string - -// Emojis that can be attached to Issues, Pull Requests and Comments. -const ( - ReactionContentThumbsUp ReactionContent = "THUMBS_UP" // Represents the 👍 emoji. - ReactionContentThumbsDown ReactionContent = "THUMBS_DOWN" // Represents the 👎 emoji. - ReactionContentLaugh ReactionContent = "LAUGH" // Represents the 😄 emoji. - ReactionContentHooray ReactionContent = "HOORAY" // Represents the 🎉 emoji. - ReactionContentConfused ReactionContent = "CONFUSED" // Represents the 😕 emoji. - ReactionContentHeart ReactionContent = "HEART" // Represents the ❤️ emoji. -) - -// AddReactionInput is an autogenerated input type of AddReaction. -type AddReactionInput struct { - // The Node ID of the subject to modify. (Required.) - SubjectID ID `json:"subjectId"` - // The name of the emoji to react with. (Required.) - Content ReactionContent `json:"content"` - - // A unique identifier for the client performing the mutation. (Optional.) - ClientMutationID *String `json:"clientMutationId,omitempty"` -} diff --git a/vendor/github.com/shurcooL/graphql/scalar_test.go b/vendor/github.com/shurcooL/graphql/scalar_test.go deleted file mode 100644 index 8334b960167f..000000000000 --- a/vendor/github.com/shurcooL/graphql/scalar_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package graphql_test - -import ( - "testing" - - "github.com/shurcooL/graphql" -) - -func TestNewScalars(t *testing.T) { - if got := graphql.NewBoolean(false); got == nil { - t.Error("NewBoolean returned nil") - } - if got := graphql.NewFloat(0.0); got == nil { - t.Error("NewFloat returned nil") - } - // ID with underlying type string. - if got := graphql.NewID(""); got == nil { - t.Error("NewID returned nil") - } - // ID with underlying type int. - if got := graphql.NewID(0); got == nil { - t.Error("NewID returned nil") - } - if got := graphql.NewInt(0); got == nil { - t.Error("NewInt returned nil") - } - if got := graphql.NewString(""); got == nil { - t.Error("NewString returned nil") - } -} diff --git a/vendor/github.com/sirupsen/logrus/BUILD b/vendor/github.com/sirupsen/logrus/BUILD index 83e0e4e53fab..a2fef26adb15 100644 --- a/vendor/github.com/sirupsen/logrus/BUILD +++ b/vendor/github.com/sirupsen/logrus/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -32,22 +32,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = [ - "alt_exit_test.go", - "entry_test.go", - "formatter_bench_test.go", - "hook_test.go", - "json_formatter_test.go", - "logrus_test.go", - "text_formatter_test.go", - ], - importpath = "github.com/sirupsen/logrus", - library = ":go_default_library", - deps = ["//vendor/github.com/stretchr/testify/assert:go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/sirupsen/logrus/alt_exit_test.go b/vendor/github.com/sirupsen/logrus/alt_exit_test.go deleted file mode 100644 index 022b778303b7..000000000000 --- a/vendor/github.com/sirupsen/logrus/alt_exit_test.go +++ /dev/null @@ -1,74 +0,0 @@ -package logrus - -import ( - "io/ioutil" - "os/exec" - "testing" - "time" -) - -func TestRegister(t *testing.T) { - current := len(handlers) - RegisterExitHandler(func() {}) - if len(handlers) != current+1 { - t.Fatalf("can't add handler") - } -} - -func TestHandler(t *testing.T) { - gofile := "/tmp/testprog.go" - if err := ioutil.WriteFile(gofile, testprog, 0666); err != nil { - t.Fatalf("can't create go file") - } - - outfile := "/tmp/testprog.out" - arg := time.Now().UTC().String() - err := exec.Command("go", "run", gofile, outfile, arg).Run() - if err == nil { - t.Fatalf("completed normally, should have failed") - } - - data, err := ioutil.ReadFile(outfile) - if err != nil { - t.Fatalf("can't read output file %s", outfile) - } - - if string(data) != arg { - t.Fatalf("bad data") - } -} - -var testprog = []byte(` -// Test program for atexit, gets output file and data as arguments and writes -// data to output file in atexit handler. -package main - -import ( - "github.com/Sirupsen/logrus" - "flag" - "fmt" - "io/ioutil" -) - -var outfile = "" -var data = "" - -func handler() { - ioutil.WriteFile(outfile, []byte(data), 0666) -} - -func badHandler() { - n := 0 - fmt.Println(1/n) -} - -func main() { - flag.Parse() - outfile = flag.Arg(0) - data = flag.Arg(1) - - logrus.RegisterExitHandler(handler) - logrus.RegisterExitHandler(badHandler) - logrus.Fatal("Bye bye") -} -`) diff --git a/vendor/github.com/sirupsen/logrus/entry_test.go b/vendor/github.com/sirupsen/logrus/entry_test.go deleted file mode 100644 index 99c3b41d5f57..000000000000 --- a/vendor/github.com/sirupsen/logrus/entry_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package logrus - -import ( - "bytes" - "fmt" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestEntryWithError(t *testing.T) { - - assert := assert.New(t) - - defer func() { - ErrorKey = "error" - }() - - err := fmt.Errorf("kaboom at layer %d", 4711) - - assert.Equal(err, WithError(err).Data["error"]) - - logger := New() - logger.Out = &bytes.Buffer{} - entry := NewEntry(logger) - - assert.Equal(err, entry.WithError(err).Data["error"]) - - ErrorKey = "err" - - assert.Equal(err, entry.WithError(err).Data["err"]) - -} - -func TestEntryPanicln(t *testing.T) { - errBoom := fmt.Errorf("boom time") - - defer func() { - p := recover() - assert.NotNil(t, p) - - switch pVal := p.(type) { - case *Entry: - assert.Equal(t, "kaboom", pVal.Message) - assert.Equal(t, errBoom, pVal.Data["err"]) - default: - t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal) - } - }() - - logger := New() - logger.Out = &bytes.Buffer{} - entry := NewEntry(logger) - entry.WithField("err", errBoom).Panicln("kaboom") -} - -func TestEntryPanicf(t *testing.T) { - errBoom := fmt.Errorf("boom again") - - defer func() { - p := recover() - assert.NotNil(t, p) - - switch pVal := p.(type) { - case *Entry: - assert.Equal(t, "kaboom true", pVal.Message) - assert.Equal(t, errBoom, pVal.Data["err"]) - default: - t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal) - } - }() - - logger := New() - logger.Out = &bytes.Buffer{} - entry := NewEntry(logger) - entry.WithField("err", errBoom).Panicf("kaboom %v", true) -} diff --git a/vendor/github.com/sirupsen/logrus/formatter_bench_test.go b/vendor/github.com/sirupsen/logrus/formatter_bench_test.go deleted file mode 100644 index c6d290c77f09..000000000000 --- a/vendor/github.com/sirupsen/logrus/formatter_bench_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package logrus - -import ( - "fmt" - "testing" - "time" -) - -// smallFields is a small size data set for benchmarking -var smallFields = Fields{ - "foo": "bar", - "baz": "qux", - "one": "two", - "three": "four", -} - -// largeFields is a large size data set for benchmarking -var largeFields = Fields{ - "foo": "bar", - "baz": "qux", - "one": "two", - "three": "four", - "five": "six", - "seven": "eight", - "nine": "ten", - "eleven": "twelve", - "thirteen": "fourteen", - "fifteen": "sixteen", - "seventeen": "eighteen", - "nineteen": "twenty", - "a": "b", - "c": "d", - "e": "f", - "g": "h", - "i": "j", - "k": "l", - "m": "n", - "o": "p", - "q": "r", - "s": "t", - "u": "v", - "w": "x", - "y": "z", - "this": "will", - "make": "thirty", - "entries": "yeah", -} - -var errorFields = Fields{ - "foo": fmt.Errorf("bar"), - "baz": fmt.Errorf("qux"), -} - -func BenchmarkErrorTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{DisableColors: true}, errorFields) -} - -func BenchmarkSmallTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{DisableColors: true}, smallFields) -} - -func BenchmarkLargeTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{DisableColors: true}, largeFields) -} - -func BenchmarkSmallColoredTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{ForceColors: true}, smallFields) -} - -func BenchmarkLargeColoredTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{ForceColors: true}, largeFields) -} - -func BenchmarkSmallJSONFormatter(b *testing.B) { - doBenchmark(b, &JSONFormatter{}, smallFields) -} - -func BenchmarkLargeJSONFormatter(b *testing.B) { - doBenchmark(b, &JSONFormatter{}, largeFields) -} - -func doBenchmark(b *testing.B, formatter Formatter, fields Fields) { - entry := &Entry{ - Time: time.Time{}, - Level: InfoLevel, - Message: "message", - Data: fields, - } - var d []byte - var err error - for i := 0; i < b.N; i++ { - d, err = formatter.Format(entry) - if err != nil { - b.Fatal(err) - } - b.SetBytes(int64(len(d))) - } -} diff --git a/vendor/github.com/sirupsen/logrus/hook_test.go b/vendor/github.com/sirupsen/logrus/hook_test.go deleted file mode 100644 index 13f34cb6f815..000000000000 --- a/vendor/github.com/sirupsen/logrus/hook_test.go +++ /dev/null @@ -1,122 +0,0 @@ -package logrus - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -type TestHook struct { - Fired bool -} - -func (hook *TestHook) Fire(entry *Entry) error { - hook.Fired = true - return nil -} - -func (hook *TestHook) Levels() []Level { - return []Level{ - DebugLevel, - InfoLevel, - WarnLevel, - ErrorLevel, - FatalLevel, - PanicLevel, - } -} - -func TestHookFires(t *testing.T) { - hook := new(TestHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - assert.Equal(t, hook.Fired, false) - - log.Print("test") - }, func(fields Fields) { - assert.Equal(t, hook.Fired, true) - }) -} - -type ModifyHook struct { -} - -func (hook *ModifyHook) Fire(entry *Entry) error { - entry.Data["wow"] = "whale" - return nil -} - -func (hook *ModifyHook) Levels() []Level { - return []Level{ - DebugLevel, - InfoLevel, - WarnLevel, - ErrorLevel, - FatalLevel, - PanicLevel, - } -} - -func TestHookCanModifyEntry(t *testing.T) { - hook := new(ModifyHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - log.WithField("wow", "elephant").Print("test") - }, func(fields Fields) { - assert.Equal(t, fields["wow"], "whale") - }) -} - -func TestCanFireMultipleHooks(t *testing.T) { - hook1 := new(ModifyHook) - hook2 := new(TestHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook1) - log.Hooks.Add(hook2) - - log.WithField("wow", "elephant").Print("test") - }, func(fields Fields) { - assert.Equal(t, fields["wow"], "whale") - assert.Equal(t, hook2.Fired, true) - }) -} - -type ErrorHook struct { - Fired bool -} - -func (hook *ErrorHook) Fire(entry *Entry) error { - hook.Fired = true - return nil -} - -func (hook *ErrorHook) Levels() []Level { - return []Level{ - ErrorLevel, - } -} - -func TestErrorHookShouldntFireOnInfo(t *testing.T) { - hook := new(ErrorHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - log.Info("test") - }, func(fields Fields) { - assert.Equal(t, hook.Fired, false) - }) -} - -func TestErrorHookShouldFireOnError(t *testing.T) { - hook := new(ErrorHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - log.Error("test") - }, func(fields Fields) { - assert.Equal(t, hook.Fired, true) - }) -} diff --git a/vendor/github.com/sirupsen/logrus/json_formatter_test.go b/vendor/github.com/sirupsen/logrus/json_formatter_test.go deleted file mode 100644 index 1d70873254d7..000000000000 --- a/vendor/github.com/sirupsen/logrus/json_formatter_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package logrus - -import ( - "encoding/json" - "errors" - - "testing" -) - -func TestErrorNotLost(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("error", errors.New("wild walrus"))) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["error"] != "wild walrus" { - t.Fatal("Error field not set") - } -} - -func TestErrorNotLostOnFieldNotNamedError(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("omg", errors.New("wild walrus"))) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["omg"] != "wild walrus" { - t.Fatal("Error field not set") - } -} - -func TestFieldClashWithTime(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("time", "right now!")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["fields.time"] != "right now!" { - t.Fatal("fields.time not set to original time field") - } - - if entry["time"] != "0001-01-01T00:00:00Z" { - t.Fatal("time field not set to current time, was: ", entry["time"]) - } -} - -func TestFieldClashWithMsg(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("msg", "something")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["fields.msg"] != "something" { - t.Fatal("fields.msg not set to original msg field") - } -} - -func TestFieldClashWithLevel(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("level", "something")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["fields.level"] != "something" { - t.Fatal("fields.level not set to original level field") - } -} - -func TestJSONEntryEndsWithNewline(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("level", "something")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - if b[len(b)-1] != '\n' { - t.Fatal("Expected JSON log entry to end with a newline") - } -} diff --git a/vendor/github.com/sirupsen/logrus/logrus_test.go b/vendor/github.com/sirupsen/logrus/logrus_test.go deleted file mode 100644 index bfc478055ea7..000000000000 --- a/vendor/github.com/sirupsen/logrus/logrus_test.go +++ /dev/null @@ -1,361 +0,0 @@ -package logrus - -import ( - "bytes" - "encoding/json" - "strconv" - "strings" - "sync" - "testing" - - "github.com/stretchr/testify/assert" -) - -func LogAndAssertJSON(t *testing.T, log func(*Logger), assertions func(fields Fields)) { - var buffer bytes.Buffer - var fields Fields - - logger := New() - logger.Out = &buffer - logger.Formatter = new(JSONFormatter) - - log(logger) - - err := json.Unmarshal(buffer.Bytes(), &fields) - assert.Nil(t, err) - - assertions(fields) -} - -func LogAndAssertText(t *testing.T, log func(*Logger), assertions func(fields map[string]string)) { - var buffer bytes.Buffer - - logger := New() - logger.Out = &buffer - logger.Formatter = &TextFormatter{ - DisableColors: true, - } - - log(logger) - - fields := make(map[string]string) - for _, kv := range strings.Split(buffer.String(), " ") { - if !strings.Contains(kv, "=") { - continue - } - kvArr := strings.Split(kv, "=") - key := strings.TrimSpace(kvArr[0]) - val := kvArr[1] - if kvArr[1][0] == '"' { - var err error - val, err = strconv.Unquote(val) - assert.NoError(t, err) - } - fields[key] = val - } - assertions(fields) -} - -func TestPrint(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Print("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["level"], "info") - }) -} - -func TestInfo(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["level"], "info") - }) -} - -func TestWarn(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Warn("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["level"], "warning") - }) -} - -func TestInfolnShouldAddSpacesBetweenStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln("test", "test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test test") - }) -} - -func TestInfolnShouldAddSpacesBetweenStringAndNonstring(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln("test", 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test 10") - }) -} - -func TestInfolnShouldAddSpacesBetweenTwoNonStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln(10, 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "10 10") - }) -} - -func TestInfoShouldAddSpacesBetweenTwoNonStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln(10, 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "10 10") - }) -} - -func TestInfoShouldNotAddSpacesBetweenStringAndNonstring(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Info("test", 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test10") - }) -} - -func TestInfoShouldNotAddSpacesBetweenStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Info("test", "test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "testtest") - }) -} - -func TestWithFieldsShouldAllowAssignments(t *testing.T) { - var buffer bytes.Buffer - var fields Fields - - logger := New() - logger.Out = &buffer - logger.Formatter = new(JSONFormatter) - - localLog := logger.WithFields(Fields{ - "key1": "value1", - }) - - localLog.WithField("key2", "value2").Info("test") - err := json.Unmarshal(buffer.Bytes(), &fields) - assert.Nil(t, err) - - assert.Equal(t, "value2", fields["key2"]) - assert.Equal(t, "value1", fields["key1"]) - - buffer = bytes.Buffer{} - fields = Fields{} - localLog.Info("test") - err = json.Unmarshal(buffer.Bytes(), &fields) - assert.Nil(t, err) - - _, ok := fields["key2"] - assert.Equal(t, false, ok) - assert.Equal(t, "value1", fields["key1"]) -} - -func TestUserSuppliedFieldDoesNotOverwriteDefaults(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("msg", "hello").Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - }) -} - -func TestUserSuppliedMsgFieldHasPrefix(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("msg", "hello").Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["fields.msg"], "hello") - }) -} - -func TestUserSuppliedTimeFieldHasPrefix(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("time", "hello").Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["fields.time"], "hello") - }) -} - -func TestUserSuppliedLevelFieldHasPrefix(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("level", 1).Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["level"], "info") - assert.Equal(t, fields["fields.level"], 1.0) // JSON has floats only - }) -} - -func TestDefaultFieldsAreNotPrefixed(t *testing.T) { - LogAndAssertText(t, func(log *Logger) { - ll := log.WithField("herp", "derp") - ll.Info("hello") - ll.Info("bye") - }, func(fields map[string]string) { - for _, fieldName := range []string{"fields.level", "fields.time", "fields.msg"} { - if _, ok := fields[fieldName]; ok { - t.Fatalf("should not have prefixed %q: %v", fieldName, fields) - } - } - }) -} - -func TestDoubleLoggingDoesntPrefixPreviousFields(t *testing.T) { - - var buffer bytes.Buffer - var fields Fields - - logger := New() - logger.Out = &buffer - logger.Formatter = new(JSONFormatter) - - llog := logger.WithField("context", "eating raw fish") - - llog.Info("looks delicious") - - err := json.Unmarshal(buffer.Bytes(), &fields) - assert.NoError(t, err, "should have decoded first message") - assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields") - assert.Equal(t, fields["msg"], "looks delicious") - assert.Equal(t, fields["context"], "eating raw fish") - - buffer.Reset() - - llog.Warn("omg it is!") - - err = json.Unmarshal(buffer.Bytes(), &fields) - assert.NoError(t, err, "should have decoded second message") - assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields") - assert.Equal(t, fields["msg"], "omg it is!") - assert.Equal(t, fields["context"], "eating raw fish") - assert.Nil(t, fields["fields.msg"], "should not have prefixed previous `msg` entry") - -} - -func TestConvertLevelToString(t *testing.T) { - assert.Equal(t, "debug", DebugLevel.String()) - assert.Equal(t, "info", InfoLevel.String()) - assert.Equal(t, "warning", WarnLevel.String()) - assert.Equal(t, "error", ErrorLevel.String()) - assert.Equal(t, "fatal", FatalLevel.String()) - assert.Equal(t, "panic", PanicLevel.String()) -} - -func TestParseLevel(t *testing.T) { - l, err := ParseLevel("panic") - assert.Nil(t, err) - assert.Equal(t, PanicLevel, l) - - l, err = ParseLevel("PANIC") - assert.Nil(t, err) - assert.Equal(t, PanicLevel, l) - - l, err = ParseLevel("fatal") - assert.Nil(t, err) - assert.Equal(t, FatalLevel, l) - - l, err = ParseLevel("FATAL") - assert.Nil(t, err) - assert.Equal(t, FatalLevel, l) - - l, err = ParseLevel("error") - assert.Nil(t, err) - assert.Equal(t, ErrorLevel, l) - - l, err = ParseLevel("ERROR") - assert.Nil(t, err) - assert.Equal(t, ErrorLevel, l) - - l, err = ParseLevel("warn") - assert.Nil(t, err) - assert.Equal(t, WarnLevel, l) - - l, err = ParseLevel("WARN") - assert.Nil(t, err) - assert.Equal(t, WarnLevel, l) - - l, err = ParseLevel("warning") - assert.Nil(t, err) - assert.Equal(t, WarnLevel, l) - - l, err = ParseLevel("WARNING") - assert.Nil(t, err) - assert.Equal(t, WarnLevel, l) - - l, err = ParseLevel("info") - assert.Nil(t, err) - assert.Equal(t, InfoLevel, l) - - l, err = ParseLevel("INFO") - assert.Nil(t, err) - assert.Equal(t, InfoLevel, l) - - l, err = ParseLevel("debug") - assert.Nil(t, err) - assert.Equal(t, DebugLevel, l) - - l, err = ParseLevel("DEBUG") - assert.Nil(t, err) - assert.Equal(t, DebugLevel, l) - - l, err = ParseLevel("invalid") - assert.Equal(t, "not a valid logrus Level: \"invalid\"", err.Error()) -} - -func TestGetSetLevelRace(t *testing.T) { - wg := sync.WaitGroup{} - for i := 0; i < 100; i++ { - wg.Add(1) - go func(i int) { - defer wg.Done() - if i%2 == 0 { - SetLevel(InfoLevel) - } else { - GetLevel() - } - }(i) - - } - wg.Wait() -} - -func TestLoggingRace(t *testing.T) { - logger := New() - - var wg sync.WaitGroup - wg.Add(100) - - for i := 0; i < 100; i++ { - go func() { - logger.Info("info") - wg.Done() - }() - } - wg.Wait() -} - -// Compile test -func TestLogrusInterface(t *testing.T) { - var buffer bytes.Buffer - fn := func(l FieldLogger) { - b := l.WithField("key", "value") - b.Debug("Test") - } - // test logger - logger := New() - logger.Out = &buffer - fn(logger) - - // test Entry - e := logger.WithField("another", "value") - fn(e) -} diff --git a/vendor/github.com/sirupsen/logrus/text_formatter_test.go b/vendor/github.com/sirupsen/logrus/text_formatter_test.go deleted file mode 100644 index e25a44f67bfe..000000000000 --- a/vendor/github.com/sirupsen/logrus/text_formatter_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package logrus - -import ( - "bytes" - "errors" - "testing" - "time" -) - -func TestQuoting(t *testing.T) { - tf := &TextFormatter{DisableColors: true} - - checkQuoting := func(q bool, value interface{}) { - b, _ := tf.Format(WithField("test", value)) - idx := bytes.Index(b, ([]byte)("test=")) - cont := bytes.Contains(b[idx+5:], []byte{'"'}) - if cont != q { - if q { - t.Errorf("quoting expected for: %#v", value) - } else { - t.Errorf("quoting not expected for: %#v", value) - } - } - } - - checkQuoting(false, "abcd") - checkQuoting(false, "v1.0") - checkQuoting(false, "1234567890") - checkQuoting(true, "/foobar") - checkQuoting(true, "x y") - checkQuoting(true, "x,y") - checkQuoting(false, errors.New("invalid")) - checkQuoting(true, errors.New("invalid argument")) -} - -func TestTimestampFormat(t *testing.T) { - checkTimeStr := func(format string) { - customFormatter := &TextFormatter{DisableColors: true, TimestampFormat: format} - customStr, _ := customFormatter.Format(WithField("test", "test")) - timeStart := bytes.Index(customStr, ([]byte)("time=")) - timeEnd := bytes.Index(customStr, ([]byte)("level=")) - timeStr := customStr[timeStart+5 : timeEnd-1] - if timeStr[0] == '"' && timeStr[len(timeStr)-1] == '"' { - timeStr = timeStr[1 : len(timeStr)-1] - } - if format == "" { - format = time.RFC3339 - } - _, e := time.Parse(format, (string)(timeStr)) - if e != nil { - t.Errorf("time string \"%s\" did not match provided time format \"%s\": %s", timeStr, format, e) - } - } - - checkTimeStr("2006-01-02T15:04:05.000000000Z07:00") - checkTimeStr("Mon Jan _2 15:04:05 2006") - checkTimeStr("") -} - -// TODO add tests for sorting etc., this requires a parser for the text -// formatter output. diff --git a/vendor/github.com/spf13/cobra/BUILD b/vendor/github.com/spf13/cobra/BUILD index bbd3bb8e294b..28bb423cd852 100644 --- a/vendor/github.com/spf13/cobra/BUILD +++ b/vendor/github.com/spf13/cobra/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -25,18 +25,6 @@ go_library( }), ) -go_test( - name = "go_default_test", - srcs = [ - "bash_completions_test.go", - "cobra_test.go", - "command_test.go", - ], - importpath = "github.com/spf13/cobra", - library = ":go_default_library", - deps = ["//vendor/github.com/spf13/pflag:go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/spf13/cobra/bash_completions_test.go b/vendor/github.com/spf13/cobra/bash_completions_test.go deleted file mode 100644 index 6957f8bd8be3..000000000000 --- a/vendor/github.com/spf13/cobra/bash_completions_test.go +++ /dev/null @@ -1,140 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "os" - "os/exec" - "strings" - "testing" -) - -var _ = fmt.Println -var _ = os.Stderr - -func checkOmit(t *testing.T, found, unexpected string) { - if strings.Contains(found, unexpected) { - t.Errorf("Unexpected response.\nGot: %q\nBut should not have!\n", unexpected) - } -} - -func check(t *testing.T, found, expected string) { - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } -} - -func runShellCheck(s string) error { - excluded := []string{ - "SC2034", // PREFIX appears unused. Verify it or export it. - } - cmd := exec.Command("shellcheck", "-s", "bash", "-", "-e", strings.Join(excluded, ",")) - cmd.Stderr = os.Stderr - cmd.Stdout = os.Stdout - - stdin, err := cmd.StdinPipe() - if err != nil { - return err - } - go func() { - defer stdin.Close() - stdin.Write([]byte(s)) - }() - - return cmd.Run() -} - -// World worst custom function, just keep telling you to enter hello! -const ( - bashCompletionFunc = `__custom_func() { -COMPREPLY=( "hello" ) -} -` -) - -func TestBashCompletions(t *testing.T) { - c := initializeWithRootCmd() - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdEcho, cmdPrint, cmdDeprecated, cmdColon) - - // custom completion function - c.BashCompletionFunction = bashCompletionFunc - - // required flag - c.MarkFlagRequired("introot") - - // valid nouns - validArgs := []string{"pod", "node", "service", "replicationcontroller"} - c.ValidArgs = validArgs - - // noun aliases - argAliases := []string{"pods", "nodes", "services", "replicationcontrollers", "po", "no", "svc", "rc"} - c.ArgAliases = argAliases - - // filename - var flagval string - c.Flags().StringVar(&flagval, "filename", "", "Enter a filename") - c.MarkFlagFilename("filename", "json", "yaml", "yml") - - // persistent filename - var flagvalPersistent string - c.PersistentFlags().StringVar(&flagvalPersistent, "persistent-filename", "", "Enter a filename") - c.MarkPersistentFlagFilename("persistent-filename") - c.MarkPersistentFlagRequired("persistent-filename") - - // filename extensions - var flagvalExt string - c.Flags().StringVar(&flagvalExt, "filename-ext", "", "Enter a filename (extension limited)") - c.MarkFlagFilename("filename-ext") - - // filename extensions - var flagvalCustom string - c.Flags().StringVar(&flagvalCustom, "custom", "", "Enter a filename (extension limited)") - c.MarkFlagCustom("custom", "__complete_custom") - - // subdirectories in a given directory - var flagvalTheme string - c.Flags().StringVar(&flagvalTheme, "theme", "", "theme to use (located in /themes/THEMENAME/)") - c.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"}) - - out := new(bytes.Buffer) - c.GenBashCompletion(out) - str := out.String() - - check(t, str, "_cobra-test") - check(t, str, "_cobra-test_echo") - check(t, str, "_cobra-test_echo_times") - check(t, str, "_cobra-test_print") - check(t, str, "_cobra-test_cmd__colon") - - // check for required flags - check(t, str, `must_have_one_flag+=("--introot=")`) - check(t, str, `must_have_one_flag+=("--persistent-filename=")`) - // check for custom completion function - check(t, str, `COMPREPLY=( "hello" )`) - // check for required nouns - check(t, str, `must_have_one_noun+=("pod")`) - // check for noun aliases - check(t, str, `noun_aliases+=("pods")`) - check(t, str, `noun_aliases+=("rc")`) - checkOmit(t, str, `must_have_one_noun+=("pods")`) - // check for filename extension flags - check(t, str, `flags_completion+=("_filedir")`) - // check for filename extension flags - check(t, str, `flags_completion+=("__handle_filename_extension_flag json|yaml|yml")`) - // check for custom flags - check(t, str, `flags_completion+=("__complete_custom")`) - // check for subdirs_in_dir flags - check(t, str, `flags_completion+=("__handle_subdirs_in_dir_flag themes")`) - - checkOmit(t, str, cmdDeprecated.Name()) - - // if available, run shellcheck against the script - if err := exec.Command("which", "shellcheck").Run(); err != nil { - return - } - err := runShellCheck(str) - if err != nil { - t.Fatalf("shellcheck failed: %v", err) - } -} diff --git a/vendor/github.com/spf13/cobra/cobra_test.go b/vendor/github.com/spf13/cobra/cobra_test.go deleted file mode 100644 index 97090b107c13..000000000000 --- a/vendor/github.com/spf13/cobra/cobra_test.go +++ /dev/null @@ -1,1188 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "os" - "reflect" - "runtime" - "strings" - "testing" - "text/template" - - "github.com/spf13/pflag" -) - -var _ = fmt.Println -var _ = os.Stderr - -var tp, te, tt, t1, tr []string -var rootPersPre, echoPre, echoPersPre, timesPersPre []string -var flagb1, flagb2, flagb3, flagbr, flagbp bool -var flags1, flags2a, flags2b, flags3, outs string -var flagi1, flagi2, flagi3, flagi4, flagir int -var globalFlag1 bool -var flagEcho, rootcalled bool -var versionUsed int - -const strtwoParentHelp = "help message for parent flag strtwo" -const strtwoChildHelp = "help message for child flag strtwo" - -var cmdHidden = &Command{ - Use: "hide [secret string to print]", - Short: "Print anything to screen (if command is known)", - Long: `an absolutely utterly useless command for testing.`, - Run: func(cmd *Command, args []string) { - outs = "hidden" - }, - Hidden: true, -} - -var cmdPrint = &Command{ - Use: "print [string to print]", - Short: "Print anything to the screen", - Long: `an absolutely utterly useless command for testing.`, - Run: func(cmd *Command, args []string) { - tp = args - }, -} - -var cmdEcho = &Command{ - Use: "echo [string to echo]", - Aliases: []string{"say"}, - Short: "Echo anything to the screen", - Long: `an utterly useless command for testing.`, - Example: "Just run cobra-test echo", - PersistentPreRun: func(cmd *Command, args []string) { - echoPersPre = args - }, - PreRun: func(cmd *Command, args []string) { - echoPre = args - }, - Run: func(cmd *Command, args []string) { - te = args - }, -} - -var cmdEchoSub = &Command{ - Use: "echosub [string to print]", - Short: "second sub command for echo", - Long: `an absolutely utterly useless command for testing gendocs!.`, - Run: func(cmd *Command, args []string) { - }, -} - -var cmdDeprecated = &Command{ - Use: "deprecated [can't do anything here]", - Short: "A command which is deprecated", - Long: `an absolutely utterly useless command for testing deprecation!.`, - Deprecated: "Please use echo instead", - Run: func(cmd *Command, args []string) { - }, -} - -var cmdTimes = &Command{ - Use: "times [# times] [string to echo]", - SuggestFor: []string{"counts"}, - Short: "Echo anything to the screen more times", - Long: `a slightly useless command for testing.`, - PersistentPreRun: func(cmd *Command, args []string) { - timesPersPre = args - }, - Run: func(cmd *Command, args []string) { - tt = args - }, -} - -var cmdRootNoRun = &Command{ - Use: "cobra-test", - Short: "The root can run its own function", - Long: "The root description for help", - PersistentPreRun: func(cmd *Command, args []string) { - rootPersPre = args - }, -} - -var cmdRootSameName = &Command{ - Use: "print", - Short: "Root with the same name as a subcommand", - Long: "The root description for help", -} - -var cmdRootWithRun = &Command{ - Use: "cobra-test", - Short: "The root can run its own function", - Long: "The root description for help", - Run: func(cmd *Command, args []string) { - tr = args - rootcalled = true - }, -} - -var cmdSubNoRun = &Command{ - Use: "subnorun", - Short: "A subcommand without a Run function", - Long: "A long output about a subcommand without a Run function", -} - -var cmdCustomFlags = &Command{ - Use: "customflags [flags] -- REMOTE_COMMAND", - Short: "A command that expects flags in a custom location", - Long: "A long output about a command that expects flags in a custom location", - Run: func(cmd *Command, args []string) { - }, -} - -var cmdVersion1 = &Command{ - Use: "version", - Short: "Print the version number", - Long: `First version of the version command`, - Run: func(cmd *Command, args []string) { - versionUsed = 1 - }, -} - -var cmdVersion2 = &Command{ - Use: "version", - Short: "Print the version number", - Long: `Second version of the version command`, - Run: func(cmd *Command, args []string) { - versionUsed = 2 - }, -} - -var cmdColon = &Command{ - Use: "cmd:colon", - Run: func(cmd *Command, args []string) { - }, -} - -func flagInit() { - cmdEcho.ResetFlags() - cmdPrint.ResetFlags() - cmdTimes.ResetFlags() - cmdRootNoRun.ResetFlags() - cmdRootSameName.ResetFlags() - cmdRootWithRun.ResetFlags() - cmdSubNoRun.ResetFlags() - cmdCustomFlags.ResetFlags() - cmdRootNoRun.PersistentFlags().StringVarP(&flags2a, "strtwo", "t", "two", strtwoParentHelp) - cmdEcho.Flags().IntVarP(&flagi1, "intone", "i", 123, "help message for flag intone") - cmdTimes.Flags().IntVarP(&flagi2, "inttwo", "j", 234, "help message for flag inttwo") - cmdPrint.Flags().IntVarP(&flagi3, "intthree", "i", 345, "help message for flag intthree") - cmdCustomFlags.Flags().IntVar(&flagi4, "intfour", 456, "help message for flag intfour") - cmdEcho.PersistentFlags().StringVarP(&flags1, "strone", "s", "one", "help message for flag strone") - cmdEcho.PersistentFlags().BoolVarP(&flagbp, "persistentbool", "p", false, "help message for flag persistentbool") - cmdTimes.PersistentFlags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp) - cmdPrint.PersistentFlags().StringVarP(&flags3, "strthree", "s", "three", "help message for flag strthree") - cmdEcho.Flags().BoolVarP(&flagb1, "boolone", "b", true, "help message for flag boolone") - cmdTimes.Flags().BoolVarP(&flagb2, "booltwo", "c", false, "help message for flag booltwo") - cmdPrint.Flags().BoolVarP(&flagb3, "boolthree", "b", true, "help message for flag boolthree") - cmdVersion1.ResetFlags() - cmdVersion2.ResetFlags() -} - -func commandInit() { - cmdEcho.ResetCommands() - cmdPrint.ResetCommands() - cmdTimes.ResetCommands() - cmdRootNoRun.ResetCommands() - cmdRootSameName.ResetCommands() - cmdRootWithRun.ResetCommands() - cmdSubNoRun.ResetCommands() - cmdCustomFlags.ResetCommands() -} - -func initialize() *Command { - tt, tp, te = nil, nil, nil - rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil - - var c = cmdRootNoRun - flagInit() - commandInit() - return c -} - -func initializeWithSameName() *Command { - tt, tp, te = nil, nil, nil - rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil - var c = cmdRootSameName - flagInit() - commandInit() - return c -} - -func initializeWithRootCmd() *Command { - cmdRootWithRun.ResetCommands() - tt, tp, te, tr, rootcalled = nil, nil, nil, nil, false - flagInit() - cmdRootWithRun.Flags().BoolVarP(&flagbr, "boolroot", "b", false, "help message for flag boolroot") - cmdRootWithRun.Flags().IntVarP(&flagir, "introot", "i", 321, "help message for flag introot") - commandInit() - return cmdRootWithRun -} - -type resulter struct { - Error error - Output string - Command *Command -} - -func fullSetupTest(input string) resulter { - c := initializeWithRootCmd() - - return fullTester(c, input) -} - -func noRRSetupTestSilenced(input string) resulter { - c := initialize() - c.SilenceErrors = true - c.SilenceUsage = true - return fullTester(c, input) -} - -func noRRSetupTest(input string) resulter { - c := initialize() - - return fullTester(c, input) -} - -func rootOnlySetupTest(input string) resulter { - c := initializeWithRootCmd() - - return simpleTester(c, input) -} - -func simpleTester(c *Command, input string) resulter { - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - c.SetArgs(strings.Split(input, " ")) - - err := c.Execute() - output := buf.String() - - return resulter{err, output, c} -} - -func simpleTesterC(c *Command, input string) resulter { - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - c.SetArgs(strings.Split(input, " ")) - - cmd, err := c.ExecuteC() - output := buf.String() - - return resulter{err, output, cmd} -} - -func fullTester(c *Command, input string) resulter { - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdPrint, cmdEcho, cmdSubNoRun, cmdCustomFlags, cmdDeprecated) - c.SetArgs(strings.Split(input, " ")) - - err := c.Execute() - output := buf.String() - - return resulter{err, output, c} -} - -func logErr(t *testing.T, found, expected string) { - out := new(bytes.Buffer) - - _, _, line, ok := runtime.Caller(2) - if ok { - fmt.Fprintf(out, "Line: %d ", line) - } - fmt.Fprintf(out, "Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - t.Errorf(out.String()) -} - -func checkStringContains(t *testing.T, found, expected string) { - if !strings.Contains(found, expected) { - logErr(t, found, expected) - } -} - -func checkResultContains(t *testing.T, x resulter, check string) { - checkStringContains(t, x.Output, check) -} - -func checkStringOmits(t *testing.T, found, expected string) { - if strings.Contains(found, expected) { - logErr(t, found, expected) - } -} - -func checkResultOmits(t *testing.T, x resulter, check string) { - checkStringOmits(t, x.Output, check) -} - -func checkOutputContains(t *testing.T, c *Command, check string) { - buf := new(bytes.Buffer) - c.SetOutput(buf) - c.Execute() - - if !strings.Contains(buf.String(), check) { - logErr(t, buf.String(), check) - } -} - -func TestSingleCommand(t *testing.T) { - noRRSetupTest("print one two") - - if te != nil || tt != nil { - t.Error("Wrong command called") - } - if tp == nil { - t.Error("Wrong command called") - } - if strings.Join(tp, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestChildCommand(t *testing.T) { - noRRSetupTest("echo times one two") - - if te != nil || tp != nil { - t.Error("Wrong command called") - } - if tt == nil { - t.Error("Wrong command called") - } - if strings.Join(tt, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestCommandAlias(t *testing.T) { - noRRSetupTest("say times one two") - - if te != nil || tp != nil { - t.Error("Wrong command called") - } - if tt == nil { - t.Error("Wrong command called") - } - if strings.Join(tt, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestPrefixMatching(t *testing.T) { - EnablePrefixMatching = true - noRRSetupTest("ech times one two") - - if te != nil || tp != nil { - t.Error("Wrong command called") - } - if tt == nil { - t.Error("Wrong command called") - } - if strings.Join(tt, " ") != "one two" { - t.Error("Command didn't parse correctly") - } - - EnablePrefixMatching = false -} - -func TestNoPrefixMatching(t *testing.T) { - EnablePrefixMatching = false - - noRRSetupTest("ech times one two") - - if !(tt == nil && te == nil && tp == nil) { - t.Error("Wrong command called") - } -} - -func TestAliasPrefixMatching(t *testing.T) { - EnablePrefixMatching = true - noRRSetupTest("sa times one two") - - if te != nil || tp != nil { - t.Error("Wrong command called") - } - if tt == nil { - t.Error("Wrong command called") - } - if strings.Join(tt, " ") != "one two" { - t.Error("Command didn't parse correctly") - } - EnablePrefixMatching = false -} - -func TestChildSameName(t *testing.T) { - c := initializeWithSameName() - c.AddCommand(cmdPrint, cmdEcho) - c.SetArgs(strings.Split("print one two", " ")) - c.Execute() - - if te != nil || tt != nil { - t.Error("Wrong command called") - } - if tp == nil { - t.Error("Wrong command called") - } - if strings.Join(tp, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestGrandChildSameName(t *testing.T) { - c := initializeWithSameName() - cmdTimes.AddCommand(cmdPrint) - c.AddCommand(cmdTimes) - c.SetArgs(strings.Split("times print one two", " ")) - c.Execute() - - if te != nil || tt != nil { - t.Error("Wrong command called") - } - if tp == nil { - t.Error("Wrong command called") - } - if strings.Join(tp, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestUsage(t *testing.T) { - x := fullSetupTest("help") - checkResultContains(t, x, cmdRootWithRun.Use+" [flags]") - x = fullSetupTest("help customflags") - checkResultContains(t, x, cmdCustomFlags.Use) - checkResultOmits(t, x, cmdCustomFlags.Use+" [flags]") -} - -func TestFlagLong(t *testing.T) { - noRRSetupTest("echo --intone=13 something -- here") - - if cmdEcho.ArgsLenAtDash() != 1 { - t.Errorf("expected argsLenAtDash: %d but got %d", 1, cmdRootNoRun.ArgsLenAtDash()) - } - if strings.Join(te, " ") != "something here" { - t.Errorf("flags didn't leave proper args remaining..%s given", te) - } - if flagi1 != 13 { - t.Errorf("int flag didn't get correct value, had %d", flagi1) - } - if flagi2 != 234 { - t.Errorf("default flag value changed, 234 expected, %d given", flagi2) - } -} - -func TestFlagShort(t *testing.T) { - noRRSetupTest("echo -i13 -- something here") - - if cmdEcho.ArgsLenAtDash() != 0 { - t.Errorf("expected argsLenAtDash: %d but got %d", 0, cmdRootNoRun.ArgsLenAtDash()) - } - if strings.Join(te, " ") != "something here" { - t.Errorf("flags didn't leave proper args remaining..%s given", te) - } - if flagi1 != 13 { - t.Errorf("int flag didn't get correct value, had %d", flagi1) - } - if flagi2 != 234 { - t.Errorf("default flag value changed, 234 expected, %d given", flagi2) - } - - noRRSetupTest("echo -i 13 something here") - - if strings.Join(te, " ") != "something here" { - t.Errorf("flags didn't leave proper args remaining..%s given", te) - } - if flagi1 != 13 { - t.Errorf("int flag didn't get correct value, had %d", flagi1) - } - if flagi2 != 234 { - t.Errorf("default flag value changed, 234 expected, %d given", flagi2) - } - - noRRSetupTest("print -i99 one two") - - if strings.Join(tp, " ") != "one two" { - t.Errorf("flags didn't leave proper args remaining..%s given", tp) - } - if flagi3 != 99 { - t.Errorf("int flag didn't get correct value, had %d", flagi3) - } - if flagi1 != 123 { - t.Errorf("default flag value changed on different command with same shortname, 234 expected, %d given", flagi2) - } -} - -func TestChildCommandFlags(t *testing.T) { - noRRSetupTest("echo times -j 99 one two") - - if strings.Join(tt, " ") != "one two" { - t.Errorf("flags didn't leave proper args remaining..%s given", tt) - } - - // Testing with flag that shouldn't be persistent - r := noRRSetupTest("echo times -j 99 -i77 one two") - - if r.Error == nil { - t.Errorf("invalid flag should generate error") - } - - if !strings.Contains(r.Error.Error(), "unknown shorthand") { - t.Errorf("Wrong error message displayed, \n %s", r.Error) - } - - if flagi2 != 99 { - t.Errorf("flag value should be 99, %d given", flagi2) - } - - if flagi1 != 123 { - t.Errorf("unset flag should have default value, expecting 123, given %d", flagi1) - } - - // Testing with flag only existing on child - r = noRRSetupTest("echo -j 99 -i77 one two") - - if r.Error == nil { - t.Errorf("invalid flag should generate error") - } - if !strings.Contains(r.Error.Error(), "unknown shorthand flag") { - t.Errorf("Wrong error message displayed, \n %s", r.Error) - } - - // Testing with persistent flag overwritten by child - noRRSetupTest("echo times --strtwo=child one two") - - if flags2b != "child" { - t.Errorf("flag value should be child, %s given", flags2b) - } - - if flags2a != "two" { - t.Errorf("unset flag should have default value, expecting two, given %s", flags2a) - } - - // Testing flag with invalid input - r = noRRSetupTest("echo -i10E") - - if r.Error == nil { - t.Errorf("invalid input should generate error") - } - if !strings.Contains(r.Error.Error(), "invalid argument \"10E\" for i10E") { - t.Errorf("Wrong error message displayed, \n %s", r.Error) - } -} - -func TestTrailingCommandFlags(t *testing.T) { - x := fullSetupTest("echo two -x") - - if x.Error == nil { - t.Errorf("invalid flag should generate error") - } -} - -func TestInvalidSubcommandFlags(t *testing.T) { - cmd := initializeWithRootCmd() - cmd.AddCommand(cmdTimes) - - result := simpleTester(cmd, "times --inttwo=2 --badflag=bar") - // given that we are not checking here result.Error we check for - // stock usage message - checkResultContains(t, result, "cobra-test times [# times]") - if strings.Contains(result.Error.Error(), "unknown flag: --inttwo") { - t.Errorf("invalid --badflag flag shouldn't fail on 'unknown' --inttwo flag") - } - -} - -func TestSubcommandExecuteC(t *testing.T) { - cmd := initializeWithRootCmd() - double := &Command{ - Use: "double message", - Run: func(c *Command, args []string) { - msg := strings.Join(args, " ") - c.Println(msg, msg) - }, - } - - echo := &Command{ - Use: "echo message", - Run: func(c *Command, args []string) { - msg := strings.Join(args, " ") - c.Println(msg, msg) - }, - } - - cmd.AddCommand(double, echo) - - result := simpleTesterC(cmd, "double hello world") - checkResultContains(t, result, "hello world hello world") - - if result.Command.Name() != "double" { - t.Errorf("invalid cmd returned from ExecuteC: should be 'double' but got %s", result.Command.Name()) - } - - result = simpleTesterC(cmd, "echo msg to be echoed") - checkResultContains(t, result, "msg to be echoed") - - if result.Command.Name() != "echo" { - t.Errorf("invalid cmd returned from ExecuteC: should be 'echo' but got %s", result.Command.Name()) - } -} - -func TestSubcommandArgEvaluation(t *testing.T) { - cmd := initializeWithRootCmd() - - first := &Command{ - Use: "first", - Run: func(cmd *Command, args []string) { - }, - } - cmd.AddCommand(first) - - second := &Command{ - Use: "second", - Run: func(cmd *Command, args []string) { - fmt.Fprintf(cmd.Out(), "%v", args) - }, - } - first.AddCommand(second) - - result := simpleTester(cmd, "first second first third") - - expectedOutput := fmt.Sprintf("%v", []string{"first third"}) - if result.Output != expectedOutput { - t.Errorf("exptected %v, got %v", expectedOutput, result.Output) - } -} - -func TestPersistentFlags(t *testing.T) { - fullSetupTest("echo -s something -p more here") - - // persistentFlag should act like normal flag on its own command - if strings.Join(te, " ") != "more here" { - t.Errorf("flags didn't leave proper args remaining..%s given", te) - } - if flags1 != "something" { - t.Errorf("string flag didn't get correct value, had %v", flags1) - } - if !flagbp { - t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp) - } - - // persistentFlag should act like normal flag on its own command - fullSetupTest("echo times -s again -c -p test here") - - if strings.Join(tt, " ") != "test here" { - t.Errorf("flags didn't leave proper args remaining..%s given", tt) - } - - if flags1 != "again" { - t.Errorf("string flag didn't get correct value, had %v", flags1) - } - - if !flagb2 { - t.Errorf("local flag not parsed correctly. Expected true, had %v", flagb2) - } - if !flagbp { - t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp) - } -} - -func TestHelpCommand(t *testing.T) { - x := fullSetupTest("help") - checkResultContains(t, x, cmdRootWithRun.Long) - - x = fullSetupTest("help echo") - checkResultContains(t, x, cmdEcho.Long) - - x = fullSetupTest("help echo times") - checkResultContains(t, x, cmdTimes.Long) -} - -func TestChildCommandHelp(t *testing.T) { - c := noRRSetupTest("print --help") - checkResultContains(t, c, strtwoParentHelp) - r := noRRSetupTest("echo times --help") - checkResultContains(t, r, strtwoChildHelp) -} - -func TestNonRunChildHelp(t *testing.T) { - x := noRRSetupTest("subnorun") - checkResultContains(t, x, cmdSubNoRun.Long) -} - -func TestRunnableRootCommand(t *testing.T) { - x := fullSetupTest("") - - if rootcalled != true { - t.Errorf("Root Function was not called\n out:%v", x.Error) - } -} - -func TestVisitParents(t *testing.T) { - c := &Command{Use: "app"} - sub := &Command{Use: "sub"} - dsub := &Command{Use: "dsub"} - sub.AddCommand(dsub) - c.AddCommand(sub) - total := 0 - add := func(x *Command) { - total++ - } - sub.VisitParents(add) - if total != 1 { - t.Errorf("Should have visited 1 parent but visited %d", total) - } - - total = 0 - dsub.VisitParents(add) - if total != 2 { - t.Errorf("Should have visited 2 parent but visited %d", total) - } - - total = 0 - c.VisitParents(add) - if total != 0 { - t.Errorf("Should have not visited any parent but visited %d", total) - } -} - -func TestRunnableRootCommandNilInput(t *testing.T) { - var emptyArg []string - c := initializeWithRootCmd() - - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdPrint, cmdEcho) - c.SetArgs(emptyArg) - - err := c.Execute() - if err != nil { - t.Errorf("Execute() failed with %v", err) - } - - if rootcalled != true { - t.Errorf("Root Function was not called") - } -} - -func TestRunnableRootCommandEmptyInput(t *testing.T) { - args := make([]string, 3) - args[0] = "" - args[1] = "--introot=12" - args[2] = "" - c := initializeWithRootCmd() - - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdPrint, cmdEcho) - c.SetArgs(args) - - c.Execute() - - if rootcalled != true { - t.Errorf("Root Function was not called.\n\nOutput was:\n\n%s\n", buf) - } -} - -func TestInvalidSubcommandWhenArgsAllowed(t *testing.T) { - fullSetupTest("echo invalid-sub") - - if te[0] != "invalid-sub" { - t.Errorf("Subcommand didn't work...") - } -} - -func TestRootFlags(t *testing.T) { - fullSetupTest("-i 17 -b") - - if flagbr != true { - t.Errorf("flag value should be true, %v given", flagbr) - } - - if flagir != 17 { - t.Errorf("flag value should be 17, %d given", flagir) - } -} - -func TestRootHelp(t *testing.T) { - x := fullSetupTest("--help") - - checkResultContains(t, x, "Available Commands:") - checkResultContains(t, x, "for more information about a command") - - if strings.Contains(x.Output, "unknown flag: --help") { - t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) - } - - if strings.Contains(x.Output, cmdEcho.Use) { - t.Errorf("--help shouldn't display subcommand's usage, Got: \n %s", x.Output) - } - - x = fullSetupTest("echo --help") - - if strings.Contains(x.Output, cmdTimes.Use) { - t.Errorf("--help shouldn't display subsubcommand's usage, Got: \n %s", x.Output) - } - - checkResultContains(t, x, "Available Commands:") - checkResultContains(t, x, "for more information about a command") - - if strings.Contains(x.Output, "unknown flag: --help") { - t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) - } - -} - -func TestFlagAccess(t *testing.T) { - initialize() - - local := cmdTimes.LocalFlags() - inherited := cmdTimes.InheritedFlags() - - for _, f := range []string{"inttwo", "strtwo", "booltwo"} { - if local.Lookup(f) == nil { - t.Errorf("LocalFlags expected to contain %s, Got: nil", f) - } - } - if inherited.Lookup("strone") == nil { - t.Errorf("InheritedFlags expected to contain strone, Got: nil") - } - if inherited.Lookup("strtwo") != nil { - t.Errorf("InheritedFlags shouldn not contain overwritten flag strtwo") - - } -} - -func TestNoNRunnableRootCommandNilInput(t *testing.T) { - var args []string - c := initialize() - - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdPrint, cmdEcho) - c.SetArgs(args) - - c.Execute() - - if !strings.Contains(buf.String(), cmdRootNoRun.Long) { - t.Errorf("Expected to get help output, Got: \n %s", buf) - } -} - -func TestRootNoCommandHelp(t *testing.T) { - x := rootOnlySetupTest("--help") - - checkResultOmits(t, x, "Available Commands:") - checkResultOmits(t, x, "for more information about a command") - - if strings.Contains(x.Output, "unknown flag: --help") { - t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) - } - - x = rootOnlySetupTest("echo --help") - - checkResultOmits(t, x, "Available Commands:") - checkResultOmits(t, x, "for more information about a command") - - if strings.Contains(x.Output, "unknown flag: --help") { - t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) - } -} - -func TestRootUnknownCommand(t *testing.T) { - r := noRRSetupTest("bogus") - s := "Error: unknown command \"bogus\" for \"cobra-test\"\nRun 'cobra-test --help' for usage.\n" - - if r.Output != s { - t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output) - } - - r = noRRSetupTest("--strtwo=a bogus") - if r.Output != s { - t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output) - } -} - -func TestRootUnknownCommandSilenced(t *testing.T) { - r := noRRSetupTestSilenced("bogus") - s := "Run 'cobra-test --help' for usage.\n" - - if r.Output != "" { - t.Errorf("Unexpected response.\nExpecting to be: \n\"\"\n Got:\n %q\n", s, r.Output) - } - - r = noRRSetupTestSilenced("--strtwo=a bogus") - if r.Output != "" { - t.Errorf("Unexpected response.\nExpecting to be:\n\"\"\nGot:\n %q\n", s, r.Output) - } -} - -func TestRootSuggestions(t *testing.T) { - outputWithSuggestions := "Error: unknown command \"%s\" for \"cobra-test\"\n\nDid you mean this?\n\t%s\n\nRun 'cobra-test --help' for usage.\n" - outputWithoutSuggestions := "Error: unknown command \"%s\" for \"cobra-test\"\nRun 'cobra-test --help' for usage.\n" - - cmd := initializeWithRootCmd() - cmd.AddCommand(cmdTimes) - - tests := map[string]string{ - "time": "times", - "tiems": "times", - "tims": "times", - "timeS": "times", - "rimes": "times", - "ti": "times", - "t": "times", - "timely": "times", - "ri": "", - "timezone": "", - "foo": "", - "counts": "times", - } - - for typo, suggestion := range tests { - for _, suggestionsDisabled := range []bool{false, true} { - cmd.DisableSuggestions = suggestionsDisabled - result := simpleTester(cmd, typo) - expected := "" - if len(suggestion) == 0 || suggestionsDisabled { - expected = fmt.Sprintf(outputWithoutSuggestions, typo) - } else { - expected = fmt.Sprintf(outputWithSuggestions, typo, suggestion) - } - if result.Output != expected { - t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", expected, result.Output) - } - } - } -} - -func TestFlagsBeforeCommand(t *testing.T) { - // short without space - x := fullSetupTest("-i10 echo") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) - } - - // short (int) with equals - // It appears that pflags doesn't support this... - // Commenting out until support can be added - - //x = noRRSetupTest("echo -i=10") - //if x.Error != nil { - //t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error) - //} - - // long with equals - x = noRRSetupTest("--intone=123 echo one two") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error) - } - - // With parsing error properly reported - x = fullSetupTest("-i10E echo") - if !strings.Contains(x.Error.Error(), "invalid argument \"10E\" for i10E") { - t.Errorf("Wrong error message displayed, \n %s", x.Error) - } - - //With quotes - x = fullSetupTest("-s=\"walking\" echo") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) - } - - //With quotes and space - x = fullSetupTest("-s=\"walking fast\" echo") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) - } - - //With inner quote - x = fullSetupTest("-s=\"walking \\\"Inner Quote\\\" fast\" echo") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) - } - - //With quotes and space - x = fullSetupTest("-s=\"walking \\\"Inner Quote\\\" fast\" echo") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) - } - -} - -func TestRemoveCommand(t *testing.T) { - versionUsed = 0 - c := initializeWithRootCmd() - c.AddCommand(cmdVersion1) - c.RemoveCommand(cmdVersion1) - x := fullTester(c, "version") - if x.Error == nil { - t.Errorf("Removed command should not have been called\n") - return - } -} - -func TestCommandWithoutSubcommands(t *testing.T) { - c := initializeWithRootCmd() - - x := simpleTester(c, "") - if x.Error != nil { - t.Errorf("Calling command without subcommands should not have error: %v", x.Error) - return - } -} - -func TestCommandWithoutSubcommandsWithArg(t *testing.T) { - c := initializeWithRootCmd() - expectedArgs := []string{"arg"} - - x := simpleTester(c, "arg") - if x.Error != nil { - t.Errorf("Calling command without subcommands but with arg should not have error: %v", x.Error) - return - } - if !reflect.DeepEqual(expectedArgs, tr) { - t.Errorf("Calling command without subcommands but with arg has wrong args: expected: %v, actual: %v", expectedArgs, tr) - return - } -} - -func TestReplaceCommandWithRemove(t *testing.T) { - versionUsed = 0 - c := initializeWithRootCmd() - c.AddCommand(cmdVersion1) - c.RemoveCommand(cmdVersion1) - c.AddCommand(cmdVersion2) - x := fullTester(c, "version") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) - return - } - if versionUsed == 1 { - t.Errorf("Removed command shouldn't be called\n") - } - if versionUsed != 2 { - t.Errorf("Replacing command should have been called but didn't\n") - } -} - -func TestDeprecatedSub(t *testing.T) { - c := fullSetupTest("deprecated") - - checkResultContains(t, c, cmdDeprecated.Deprecated) -} - -func TestPreRun(t *testing.T) { - noRRSetupTest("echo one two") - if echoPre == nil || echoPersPre == nil { - t.Error("PreRun or PersistentPreRun not called") - } - if rootPersPre != nil || timesPersPre != nil { - t.Error("Wrong *Pre functions called!") - } - - noRRSetupTest("echo times one two") - if timesPersPre == nil { - t.Error("PreRun or PersistentPreRun not called") - } - if echoPre != nil || echoPersPre != nil || rootPersPre != nil { - t.Error("Wrong *Pre functions called!") - } - - noRRSetupTest("print one two") - if rootPersPre == nil { - t.Error("Parent PersistentPreRun not called but should not have been") - } - if echoPre != nil || echoPersPre != nil || timesPersPre != nil { - t.Error("Wrong *Pre functions called!") - } -} - -// Check if cmdEchoSub gets PersistentPreRun from rootCmd even if is added last -func TestPeristentPreRunPropagation(t *testing.T) { - rootCmd := initialize() - - // First add the cmdEchoSub to cmdPrint - cmdPrint.AddCommand(cmdEchoSub) - // Now add cmdPrint to rootCmd - rootCmd.AddCommand(cmdPrint) - - rootCmd.SetArgs(strings.Split("print echosub lala", " ")) - rootCmd.Execute() - - if rootPersPre == nil || len(rootPersPre) == 0 || rootPersPre[0] != "lala" { - t.Error("RootCmd PersistentPreRun not called but should have been") - } -} - -func TestGlobalNormFuncPropagation(t *testing.T) { - normFunc := func(f *pflag.FlagSet, name string) pflag.NormalizedName { - return pflag.NormalizedName(name) - } - - rootCmd := initialize() - rootCmd.SetGlobalNormalizationFunc(normFunc) - if reflect.ValueOf(normFunc) != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()) { - t.Error("rootCmd seems to have a wrong normalization function") - } - - // First add the cmdEchoSub to cmdPrint - cmdPrint.AddCommand(cmdEchoSub) - if cmdPrint.GlobalNormalizationFunc() != nil && cmdEchoSub.GlobalNormalizationFunc() != nil { - t.Error("cmdPrint and cmdEchoSub should had no normalization functions") - } - - // Now add cmdPrint to rootCmd - rootCmd.AddCommand(cmdPrint) - if reflect.ValueOf(cmdPrint.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() || - reflect.ValueOf(cmdEchoSub.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() { - t.Error("cmdPrint and cmdEchoSub should had the normalization function of rootCmd") - } -} - -func TestFlagOnPflagCommandLine(t *testing.T) { - flagName := "flagOnCommandLine" - pflag.CommandLine.String(flagName, "", "about my flag") - r := fullSetupTest("--help") - - checkResultContains(t, r, flagName) -} - -func TestAddTemplateFunctions(t *testing.T) { - AddTemplateFunc("t", func() bool { return true }) - AddTemplateFuncs(template.FuncMap{ - "f": func() bool { return false }, - "h": func() string { return "Hello," }, - "w": func() string { return "world." }}) - - const usage = "Hello, world." - - c := &Command{} - c.SetUsageTemplate(`{{if t}}{{h}}{{end}}{{if f}}{{h}}{{end}} {{w}}`) - - if us := c.UsageString(); us != usage { - t.Errorf("c.UsageString() != \"%s\", is \"%s\"", usage, us) - } -} - -func TestUsageIsNotPrintedTwice(t *testing.T) { - var cmd = &Command{Use: "root"} - var sub = &Command{Use: "sub"} - cmd.AddCommand(sub) - - r := simpleTester(cmd, "") - if strings.Count(r.Output, "Usage:") != 1 { - t.Error("Usage output is not printed exactly once") - } -} diff --git a/vendor/github.com/spf13/cobra/command_test.go b/vendor/github.com/spf13/cobra/command_test.go deleted file mode 100644 index 43ed7a34fcc0..000000000000 --- a/vendor/github.com/spf13/cobra/command_test.go +++ /dev/null @@ -1,114 +0,0 @@ -package cobra - -import ( - "reflect" - "testing" -) - -// test to ensure hidden commands run as intended -func TestHiddenCommandExecutes(t *testing.T) { - - // ensure that outs does not already equal what the command will be setting it - // to, if it did this test would not actually be testing anything... - if outs == "hidden" { - t.Errorf("outs should NOT EQUAL hidden") - } - - cmdHidden.Execute() - - // upon running the command, the value of outs should now be 'hidden' - if outs != "hidden" { - t.Errorf("Hidden command failed to run!") - } -} - -// test to ensure hidden commands do not show up in usage/help text -func TestHiddenCommandIsHidden(t *testing.T) { - if cmdHidden.IsAvailableCommand() { - t.Errorf("Hidden command found!") - } -} - -func TestStripFlags(t *testing.T) { - tests := []struct { - input []string - output []string - }{ - { - []string{"foo", "bar"}, - []string{"foo", "bar"}, - }, - { - []string{"foo", "--bar", "-b"}, - []string{"foo"}, - }, - { - []string{"-b", "foo", "--bar", "bar"}, - []string{}, - }, - { - []string{"-i10", "echo"}, - []string{"echo"}, - }, - { - []string{"-i=10", "echo"}, - []string{"echo"}, - }, - { - []string{"--int=100", "echo"}, - []string{"echo"}, - }, - { - []string{"-ib", "echo", "-bfoo", "baz"}, - []string{"echo", "baz"}, - }, - { - []string{"-i=baz", "bar", "-i", "foo", "blah"}, - []string{"bar", "blah"}, - }, - { - []string{"--int=baz", "-bbar", "-i", "foo", "blah"}, - []string{"blah"}, - }, - { - []string{"--cat", "bar", "-i", "foo", "blah"}, - []string{"bar", "blah"}, - }, - { - []string{"-c", "bar", "-i", "foo", "blah"}, - []string{"bar", "blah"}, - }, - { - []string{"--persist", "bar"}, - []string{"bar"}, - }, - { - []string{"-p", "bar"}, - []string{"bar"}, - }, - } - - cmdPrint := &Command{ - Use: "print [string to print]", - Short: "Print anything to the screen", - Long: `an utterly useless command for testing.`, - Run: func(cmd *Command, args []string) { - tp = args - }, - } - - var flagi int - var flagstr string - var flagbool bool - cmdPrint.PersistentFlags().BoolVarP(&flagbool, "persist", "p", false, "help for persistent one") - cmdPrint.Flags().IntVarP(&flagi, "int", "i", 345, "help message for flag int") - cmdPrint.Flags().StringVarP(&flagstr, "bar", "b", "bar", "help message for flag string") - cmdPrint.Flags().BoolVarP(&flagbool, "cat", "c", false, "help message for flag bool") - - for _, test := range tests { - output := stripFlags(test.input, cmdPrint) - if !reflect.DeepEqual(test.output, output) { - t.Errorf("expected: %v, got: %v", test.output, output) - } - } -} diff --git a/vendor/github.com/spf13/pflag/BUILD b/vendor/github.com/spf13/pflag/BUILD index 724ed915245b..e48a6b288896 100644 --- a/vendor/github.com/spf13/pflag/BUILD +++ b/vendor/github.com/spf13/pflag/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -34,34 +34,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = [ - "bool_slice_test.go", - "bool_test.go", - "count_test.go", - "export_test.go", - "flag_test.go", - "golangflag_test.go", - "int_slice_test.go", - "ip_slice_test.go", - "ip_test.go", - "ipnet_test.go", - "string_array_test.go", - "string_slice_test.go", - "uint_slice_test.go", - ], - importpath = "github.com/spf13/pflag", - library = ":go_default_library", -) - -go_test( - name = "go_default_xtest", - srcs = ["example_test.go"], - importpath = "github.com/spf13/pflag_test", - deps = [":go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/github.com/spf13/pflag/bool_slice_test.go b/vendor/github.com/spf13/pflag/bool_slice_test.go deleted file mode 100644 index b617dd237f3b..000000000000 --- a/vendor/github.com/spf13/pflag/bool_slice_test.go +++ /dev/null @@ -1,215 +0,0 @@ -package pflag - -import ( - "fmt" - "strconv" - "strings" - "testing" -) - -func setUpBSFlagSet(bsp *[]bool) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.BoolSliceVar(bsp, "bs", []bool{}, "Command separated list!") - return f -} - -func setUpBSFlagSetWithDefault(bsp *[]bool) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.BoolSliceVar(bsp, "bs", []bool{false, true}, "Command separated list!") - return f -} - -func TestEmptyBS(t *testing.T) { - var bs []bool - f := setUpBSFlagSet(&bs) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getBS, err := f.GetBoolSlice("bs") - if err != nil { - t.Fatal("got an error from GetBoolSlice():", err) - } - if len(getBS) != 0 { - t.Fatalf("got bs %v with len=%d but expected length=0", getBS, len(getBS)) - } -} - -func TestBS(t *testing.T) { - var bs []bool - f := setUpBSFlagSet(&bs) - - vals := []string{"1", "F", "TRUE", "0"} - arg := fmt.Sprintf("--bs=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range bs { - b, err := strconv.ParseBool(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if b != v { - t.Fatalf("expected is[%d] to be %s but got: %t", i, vals[i], v) - } - } - getBS, err := f.GetBoolSlice("bs") - if err != nil { - t.Fatalf("got error: %v", err) - } - for i, v := range getBS { - b, err := strconv.ParseBool(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if b != v { - t.Fatalf("expected bs[%d] to be %s but got: %t from GetBoolSlice", i, vals[i], v) - } - } -} - -func TestBSDefault(t *testing.T) { - var bs []bool - f := setUpBSFlagSetWithDefault(&bs) - - vals := []string{"false", "T"} - - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range bs { - b, err := strconv.ParseBool(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if b != v { - t.Fatalf("expected bs[%d] to be %t from GetBoolSlice but got: %t", i, b, v) - } - } - - getBS, err := f.GetBoolSlice("bs") - if err != nil { - t.Fatal("got an error from GetBoolSlice():", err) - } - for i, v := range getBS { - b, err := strconv.ParseBool(vals[i]) - if err != nil { - t.Fatal("got an error from GetBoolSlice():", err) - } - if b != v { - t.Fatalf("expected bs[%d] to be %t from GetBoolSlice but got: %t", i, b, v) - } - } -} - -func TestBSWithDefault(t *testing.T) { - var bs []bool - f := setUpBSFlagSetWithDefault(&bs) - - vals := []string{"FALSE", "1"} - arg := fmt.Sprintf("--bs=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range bs { - b, err := strconv.ParseBool(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if b != v { - t.Fatalf("expected bs[%d] to be %t but got: %t", i, b, v) - } - } - - getBS, err := f.GetBoolSlice("bs") - if err != nil { - t.Fatal("got an error from GetBoolSlice():", err) - } - for i, v := range getBS { - b, err := strconv.ParseBool(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if b != v { - t.Fatalf("expected bs[%d] to be %t from GetBoolSlice but got: %t", i, b, v) - } - } -} - -func TestBSCalledTwice(t *testing.T) { - var bs []bool - f := setUpBSFlagSet(&bs) - - in := []string{"T,F", "T"} - expected := []bool{true, false, true} - argfmt := "--bs=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range bs { - if expected[i] != v { - t.Fatalf("expected bs[%d] to be %t but got %t", i, expected[i], v) - } - } -} - -func TestBSBadQuoting(t *testing.T) { - - tests := []struct { - Want []bool - FlagArg []string - }{ - { - Want: []bool{true, false, true}, - FlagArg: []string{"1", "0", "true"}, - }, - { - Want: []bool{true, false}, - FlagArg: []string{"True", "F"}, - }, - { - Want: []bool{true, false}, - FlagArg: []string{"T", "0"}, - }, - { - Want: []bool{true, false}, - FlagArg: []string{"1", "0"}, - }, - { - Want: []bool{true, false, false}, - FlagArg: []string{"true,false", "false"}, - }, - { - Want: []bool{true, false, false, true, false, true, false}, - FlagArg: []string{`"true,false,false,1,0, T"`, " false "}, - }, - { - Want: []bool{false, false, true, false, true, false, true}, - FlagArg: []string{`"0, False, T,false , true,F"`, "true"}, - }, - } - - for i, test := range tests { - - var bs []bool - f := setUpBSFlagSet(&bs) - - if err := f.Parse([]string{fmt.Sprintf("--bs=%s", strings.Join(test.FlagArg, ","))}); err != nil { - t.Fatalf("flag parsing failed with error: %s\nparsing:\t%#v\nwant:\t\t%#v", - err, test.FlagArg, test.Want[i]) - } - - for j, b := range bs { - if b != test.Want[j] { - t.Fatalf("bad value parsed for test %d on bool %d:\nwant:\t%t\ngot:\t%t", i, j, test.Want[j], b) - } - } - } -} diff --git a/vendor/github.com/spf13/pflag/bool_test.go b/vendor/github.com/spf13/pflag/bool_test.go deleted file mode 100644 index a4319e79fcda..000000000000 --- a/vendor/github.com/spf13/pflag/bool_test.go +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pflag - -import ( - "bytes" - "strconv" - "testing" -) - -// This value can be a boolean ("true", "false") or "maybe" -type triStateValue int - -const ( - triStateFalse triStateValue = 0 - triStateTrue triStateValue = 1 - triStateMaybe triStateValue = 2 -) - -const strTriStateMaybe = "maybe" - -func (v *triStateValue) IsBoolFlag() bool { - return true -} - -func (v *triStateValue) Get() interface{} { - return triStateValue(*v) -} - -func (v *triStateValue) Set(s string) error { - if s == strTriStateMaybe { - *v = triStateMaybe - return nil - } - boolVal, err := strconv.ParseBool(s) - if boolVal { - *v = triStateTrue - } else { - *v = triStateFalse - } - return err -} - -func (v *triStateValue) String() string { - if *v == triStateMaybe { - return strTriStateMaybe - } - return strconv.FormatBool(*v == triStateTrue) -} - -// The type of the flag as required by the pflag.Value interface -func (v *triStateValue) Type() string { - return "version" -} - -func setUpFlagSet(tristate *triStateValue) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - *tristate = triStateFalse - flag := f.VarPF(tristate, "tristate", "t", "tristate value (true, maybe or false)") - flag.NoOptDefVal = "true" - return f -} - -func TestExplicitTrue(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"--tristate=true"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateTrue { - t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead") - } -} - -func TestImplicitTrue(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"--tristate"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateTrue { - t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead") - } -} - -func TestShortFlag(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"-t"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateTrue { - t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead") - } -} - -func TestShortFlagExtraArgument(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - // The"maybe"turns into an arg, since short boolean options will only do true/false - err := f.Parse([]string{"-t", "maybe"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateTrue { - t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead") - } - args := f.Args() - if len(args) != 1 || args[0] != "maybe" { - t.Fatal("expected an extra 'maybe' argument to stick around") - } -} - -func TestExplicitMaybe(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"--tristate=maybe"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateMaybe { - t.Fatal("expected", triStateMaybe, "(triStateMaybe) but got", tristate, "instead") - } -} - -func TestExplicitFalse(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"--tristate=false"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateFalse { - t.Fatal("expected", triStateFalse, "(triStateFalse) but got", tristate, "instead") - } -} - -func TestImplicitFalse(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateFalse { - t.Fatal("expected", triStateFalse, "(triStateFalse) but got", tristate, "instead") - } -} - -func TestInvalidValue(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - var buf bytes.Buffer - f.SetOutput(&buf) - err := f.Parse([]string{"--tristate=invalid"}) - if err == nil { - t.Fatal("expected an error but did not get any, tristate has value", tristate) - } -} - -func TestBoolP(t *testing.T) { - b := BoolP("bool", "b", false, "bool value in CommandLine") - c := BoolP("c", "c", false, "other bool value") - args := []string{"--bool"} - if err := CommandLine.Parse(args); err != nil { - t.Error("expected no error, got ", err) - } - if *b != true { - t.Errorf("expected b=true got b=%v", *b) - } - if *c != false { - t.Errorf("expect c=false got c=%v", *c) - } -} diff --git a/vendor/github.com/spf13/pflag/count_test.go b/vendor/github.com/spf13/pflag/count_test.go deleted file mode 100644 index 460d96a6f173..000000000000 --- a/vendor/github.com/spf13/pflag/count_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package pflag - -import ( - "os" - "testing" -) - -func setUpCount(c *int) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.CountVarP(c, "verbose", "v", "a counter") - return f -} - -func TestCount(t *testing.T) { - testCases := []struct { - input []string - success bool - expected int - }{ - {[]string{"-vvv"}, true, 3}, - {[]string{"-v", "-v", "-v"}, true, 3}, - {[]string{"-v", "--verbose", "-v"}, true, 3}, - {[]string{"-v=3", "-v"}, true, 4}, - {[]string{"-v=a"}, false, 0}, - } - - devnull, _ := os.Open(os.DevNull) - os.Stderr = devnull - for i := range testCases { - var count int - f := setUpCount(&count) - - tc := &testCases[i] - - err := f.Parse(tc.input) - if err != nil && tc.success == true { - t.Errorf("expected success, got %q", err) - continue - } else if err == nil && tc.success == false { - t.Errorf("expected failure, got success") - continue - } else if tc.success { - c, err := f.GetCount("verbose") - if err != nil { - t.Errorf("Got error trying to fetch the counter flag") - } - if c != tc.expected { - t.Errorf("expected %q, got %q", tc.expected, c) - } - } - } -} diff --git a/vendor/github.com/spf13/pflag/example_test.go b/vendor/github.com/spf13/pflag/example_test.go deleted file mode 100644 index abd7806fad55..000000000000 --- a/vendor/github.com/spf13/pflag/example_test.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pflag_test - -import ( - "fmt" - - "github.com/spf13/pflag" -) - -func ExampleShorthandLookup() { - name := "verbose" - short := name[:1] - - pflag.BoolP(name, short, false, "verbose output") - - // len(short) must be == 1 - flag := pflag.ShorthandLookup(short) - - fmt.Println(flag.Name) -} - -func ExampleFlagSet_ShorthandLookup() { - name := "verbose" - short := name[:1] - - fs := pflag.NewFlagSet("Example", pflag.ContinueOnError) - fs.BoolP(name, short, false, "verbose output") - - // len(short) must be == 1 - flag := fs.ShorthandLookup(short) - - fmt.Println(flag.Name) -} diff --git a/vendor/github.com/spf13/pflag/export_test.go b/vendor/github.com/spf13/pflag/export_test.go deleted file mode 100644 index 9318fee00e17..000000000000 --- a/vendor/github.com/spf13/pflag/export_test.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pflag - -import ( - "io/ioutil" - "os" -) - -// Additional routines compiled into the package only during testing. - -// ResetForTesting clears all flag state and sets the usage function as directed. -// After calling ResetForTesting, parse errors in flag handling will not -// exit the program. -func ResetForTesting(usage func()) { - CommandLine = &FlagSet{ - name: os.Args[0], - errorHandling: ContinueOnError, - output: ioutil.Discard, - } - Usage = usage -} - -// GetCommandLine returns the default FlagSet. -func GetCommandLine() *FlagSet { - return CommandLine -} diff --git a/vendor/github.com/spf13/pflag/flag_test.go b/vendor/github.com/spf13/pflag/flag_test.go deleted file mode 100644 index 29fec8671cf9..000000000000 --- a/vendor/github.com/spf13/pflag/flag_test.go +++ /dev/null @@ -1,1085 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pflag - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net" - "os" - "reflect" - "sort" - "strconv" - "strings" - "testing" - "time" -) - -var ( - testBool = Bool("test_bool", false, "bool value") - testInt = Int("test_int", 0, "int value") - testInt64 = Int64("test_int64", 0, "int64 value") - testUint = Uint("test_uint", 0, "uint value") - testUint64 = Uint64("test_uint64", 0, "uint64 value") - testString = String("test_string", "0", "string value") - testFloat = Float64("test_float64", 0, "float64 value") - testDuration = Duration("test_duration", 0, "time.Duration value") - testOptionalInt = Int("test_optional_int", 0, "optional int value") - normalizeFlagNameInvocations = 0 -) - -func boolString(s string) string { - if s == "0" { - return "false" - } - return "true" -} - -func TestEverything(t *testing.T) { - m := make(map[string]*Flag) - desired := "0" - visitor := func(f *Flag) { - if len(f.Name) > 5 && f.Name[0:5] == "test_" { - m[f.Name] = f - ok := false - switch { - case f.Value.String() == desired: - ok = true - case f.Name == "test_bool" && f.Value.String() == boolString(desired): - ok = true - case f.Name == "test_duration" && f.Value.String() == desired+"s": - ok = true - } - if !ok { - t.Error("Visit: bad value", f.Value.String(), "for", f.Name) - } - } - } - VisitAll(visitor) - if len(m) != 9 { - t.Error("VisitAll misses some flags") - for k, v := range m { - t.Log(k, *v) - } - } - m = make(map[string]*Flag) - Visit(visitor) - if len(m) != 0 { - t.Errorf("Visit sees unset flags") - for k, v := range m { - t.Log(k, *v) - } - } - // Now set all flags - Set("test_bool", "true") - Set("test_int", "1") - Set("test_int64", "1") - Set("test_uint", "1") - Set("test_uint64", "1") - Set("test_string", "1") - Set("test_float64", "1") - Set("test_duration", "1s") - Set("test_optional_int", "1") - desired = "1" - Visit(visitor) - if len(m) != 9 { - t.Error("Visit fails after set") - for k, v := range m { - t.Log(k, *v) - } - } - // Now test they're visited in sort order. - var flagNames []string - Visit(func(f *Flag) { flagNames = append(flagNames, f.Name) }) - if !sort.StringsAreSorted(flagNames) { - t.Errorf("flag names not sorted: %v", flagNames) - } -} - -func TestUsage(t *testing.T) { - called := false - ResetForTesting(func() { called = true }) - if GetCommandLine().Parse([]string{"--x"}) == nil { - t.Error("parse did not fail for unknown flag") - } - if !called { - t.Error("did not call Usage for unknown flag") - } -} - -func TestAddFlagSet(t *testing.T) { - oldSet := NewFlagSet("old", ContinueOnError) - newSet := NewFlagSet("new", ContinueOnError) - - oldSet.String("flag1", "flag1", "flag1") - oldSet.String("flag2", "flag2", "flag2") - - newSet.String("flag2", "flag2", "flag2") - newSet.String("flag3", "flag3", "flag3") - - oldSet.AddFlagSet(newSet) - - if len(oldSet.formal) != 3 { - t.Errorf("Unexpected result adding a FlagSet to a FlagSet %v", oldSet) - } -} - -func TestAnnotation(t *testing.T) { - f := NewFlagSet("shorthand", ContinueOnError) - - if err := f.SetAnnotation("missing-flag", "key", nil); err == nil { - t.Errorf("Expected error setting annotation on non-existent flag") - } - - f.StringP("stringa", "a", "", "string value") - if err := f.SetAnnotation("stringa", "key", nil); err != nil { - t.Errorf("Unexpected error setting new nil annotation: %v", err) - } - if annotation := f.Lookup("stringa").Annotations["key"]; annotation != nil { - t.Errorf("Unexpected annotation: %v", annotation) - } - - f.StringP("stringb", "b", "", "string2 value") - if err := f.SetAnnotation("stringb", "key", []string{"value1"}); err != nil { - t.Errorf("Unexpected error setting new annotation: %v", err) - } - if annotation := f.Lookup("stringb").Annotations["key"]; !reflect.DeepEqual(annotation, []string{"value1"}) { - t.Errorf("Unexpected annotation: %v", annotation) - } - - if err := f.SetAnnotation("stringb", "key", []string{"value2"}); err != nil { - t.Errorf("Unexpected error updating annotation: %v", err) - } - if annotation := f.Lookup("stringb").Annotations["key"]; !reflect.DeepEqual(annotation, []string{"value2"}) { - t.Errorf("Unexpected annotation: %v", annotation) - } -} - -func testParse(f *FlagSet, t *testing.T) { - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - boolFlag := f.Bool("bool", false, "bool value") - bool2Flag := f.Bool("bool2", false, "bool2 value") - bool3Flag := f.Bool("bool3", false, "bool3 value") - intFlag := f.Int("int", 0, "int value") - int8Flag := f.Int8("int8", 0, "int value") - int32Flag := f.Int32("int32", 0, "int value") - int64Flag := f.Int64("int64", 0, "int64 value") - uintFlag := f.Uint("uint", 0, "uint value") - uint8Flag := f.Uint8("uint8", 0, "uint value") - uint16Flag := f.Uint16("uint16", 0, "uint value") - uint32Flag := f.Uint32("uint32", 0, "uint value") - uint64Flag := f.Uint64("uint64", 0, "uint64 value") - stringFlag := f.String("string", "0", "string value") - float32Flag := f.Float32("float32", 0, "float32 value") - float64Flag := f.Float64("float64", 0, "float64 value") - ipFlag := f.IP("ip", net.ParseIP("127.0.0.1"), "ip value") - maskFlag := f.IPMask("mask", ParseIPv4Mask("0.0.0.0"), "mask value") - durationFlag := f.Duration("duration", 5*time.Second, "time.Duration value") - optionalIntNoValueFlag := f.Int("optional-int-no-value", 0, "int value") - f.Lookup("optional-int-no-value").NoOptDefVal = "9" - optionalIntWithValueFlag := f.Int("optional-int-with-value", 0, "int value") - f.Lookup("optional-int-no-value").NoOptDefVal = "9" - extra := "one-extra-argument" - args := []string{ - "--bool", - "--bool2=true", - "--bool3=false", - "--int=22", - "--int8=-8", - "--int32=-32", - "--int64=0x23", - "--uint", "24", - "--uint8=8", - "--uint16=16", - "--uint32=32", - "--uint64=25", - "--string=hello", - "--float32=-172e12", - "--float64=2718e28", - "--ip=10.11.12.13", - "--mask=255.255.255.0", - "--duration=2m", - "--optional-int-no-value", - "--optional-int-with-value=42", - extra, - } - if err := f.Parse(args); err != nil { - t.Fatal(err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - if *boolFlag != true { - t.Error("bool flag should be true, is ", *boolFlag) - } - if v, err := f.GetBool("bool"); err != nil || v != *boolFlag { - t.Error("GetBool does not work.") - } - if *bool2Flag != true { - t.Error("bool2 flag should be true, is ", *bool2Flag) - } - if *bool3Flag != false { - t.Error("bool3 flag should be false, is ", *bool2Flag) - } - if *intFlag != 22 { - t.Error("int flag should be 22, is ", *intFlag) - } - if v, err := f.GetInt("int"); err != nil || v != *intFlag { - t.Error("GetInt does not work.") - } - if *int8Flag != -8 { - t.Error("int8 flag should be 0x23, is ", *int8Flag) - } - if v, err := f.GetInt8("int8"); err != nil || v != *int8Flag { - t.Error("GetInt8 does not work.") - } - if *int32Flag != -32 { - t.Error("int32 flag should be 0x23, is ", *int32Flag) - } - if v, err := f.GetInt32("int32"); err != nil || v != *int32Flag { - t.Error("GetInt32 does not work.") - } - if *int64Flag != 0x23 { - t.Error("int64 flag should be 0x23, is ", *int64Flag) - } - if v, err := f.GetInt64("int64"); err != nil || v != *int64Flag { - t.Error("GetInt64 does not work.") - } - if *uintFlag != 24 { - t.Error("uint flag should be 24, is ", *uintFlag) - } - if v, err := f.GetUint("uint"); err != nil || v != *uintFlag { - t.Error("GetUint does not work.") - } - if *uint8Flag != 8 { - t.Error("uint8 flag should be 8, is ", *uint8Flag) - } - if v, err := f.GetUint8("uint8"); err != nil || v != *uint8Flag { - t.Error("GetUint8 does not work.") - } - if *uint16Flag != 16 { - t.Error("uint16 flag should be 16, is ", *uint16Flag) - } - if v, err := f.GetUint16("uint16"); err != nil || v != *uint16Flag { - t.Error("GetUint16 does not work.") - } - if *uint32Flag != 32 { - t.Error("uint32 flag should be 32, is ", *uint32Flag) - } - if v, err := f.GetUint32("uint32"); err != nil || v != *uint32Flag { - t.Error("GetUint32 does not work.") - } - if *uint64Flag != 25 { - t.Error("uint64 flag should be 25, is ", *uint64Flag) - } - if v, err := f.GetUint64("uint64"); err != nil || v != *uint64Flag { - t.Error("GetUint64 does not work.") - } - if *stringFlag != "hello" { - t.Error("string flag should be `hello`, is ", *stringFlag) - } - if v, err := f.GetString("string"); err != nil || v != *stringFlag { - t.Error("GetString does not work.") - } - if *float32Flag != -172e12 { - t.Error("float32 flag should be -172e12, is ", *float32Flag) - } - if v, err := f.GetFloat32("float32"); err != nil || v != *float32Flag { - t.Errorf("GetFloat32 returned %v but float32Flag was %v", v, *float32Flag) - } - if *float64Flag != 2718e28 { - t.Error("float64 flag should be 2718e28, is ", *float64Flag) - } - if v, err := f.GetFloat64("float64"); err != nil || v != *float64Flag { - t.Errorf("GetFloat64 returned %v but float64Flag was %v", v, *float64Flag) - } - if !(*ipFlag).Equal(net.ParseIP("10.11.12.13")) { - t.Error("ip flag should be 10.11.12.13, is ", *ipFlag) - } - if v, err := f.GetIP("ip"); err != nil || !v.Equal(*ipFlag) { - t.Errorf("GetIP returned %v but ipFlag was %v", v, *ipFlag) - } - if (*maskFlag).String() != ParseIPv4Mask("255.255.255.0").String() { - t.Error("mask flag should be 255.255.255.0, is ", (*maskFlag).String()) - } - if v, err := f.GetIPv4Mask("mask"); err != nil || v.String() != (*maskFlag).String() { - t.Errorf("GetIP returned %v maskFlag was %v error was %v", v, *maskFlag, err) - } - if *durationFlag != 2*time.Minute { - t.Error("duration flag should be 2m, is ", *durationFlag) - } - if v, err := f.GetDuration("duration"); err != nil || v != *durationFlag { - t.Error("GetDuration does not work.") - } - if _, err := f.GetInt("duration"); err == nil { - t.Error("GetInt parsed a time.Duration?!?!") - } - if *optionalIntNoValueFlag != 9 { - t.Error("optional int flag should be the default value, is ", *optionalIntNoValueFlag) - } - if *optionalIntWithValueFlag != 42 { - t.Error("optional int flag should be 42, is ", *optionalIntWithValueFlag) - } - if len(f.Args()) != 1 { - t.Error("expected one argument, got", len(f.Args())) - } else if f.Args()[0] != extra { - t.Errorf("expected argument %q got %q", extra, f.Args()[0]) - } -} - -func testParseAll(f *FlagSet, t *testing.T) { - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - f.BoolP("boola", "a", false, "bool value") - f.BoolP("boolb", "b", false, "bool2 value") - f.BoolP("boolc", "c", false, "bool3 value") - f.BoolP("boold", "d", false, "bool4 value") - f.StringP("stringa", "s", "0", "string value") - f.StringP("stringz", "z", "0", "string value") - f.StringP("stringx", "x", "0", "string value") - f.StringP("stringy", "y", "0", "string value") - f.Lookup("stringx").NoOptDefVal = "1" - args := []string{ - "-ab", - "-cs=xx", - "--stringz=something", - "-d=true", - "-x", - "-y", - "ee", - } - want := []string{ - "boola", "true", - "boolb", "true", - "boolc", "true", - "stringa", "xx", - "stringz", "something", - "boold", "true", - "stringx", "1", - "stringy", "ee", - } - got := []string{} - store := func(flag *Flag, value string) error { - got = append(got, flag.Name) - if len(value) > 0 { - got = append(got, value) - } - return nil - } - if err := f.ParseAll(args, store); err != nil { - t.Errorf("expected no error, got %s", err) - } - if !f.Parsed() { - t.Errorf("f.Parse() = false after Parse") - } - if !reflect.DeepEqual(got, want) { - t.Errorf("f.ParseAll() fail to restore the args") - t.Errorf("Got: %v", got) - t.Errorf("Want: %v", want) - } -} - -func TestShorthand(t *testing.T) { - f := NewFlagSet("shorthand", ContinueOnError) - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - boolaFlag := f.BoolP("boola", "a", false, "bool value") - boolbFlag := f.BoolP("boolb", "b", false, "bool2 value") - boolcFlag := f.BoolP("boolc", "c", false, "bool3 value") - booldFlag := f.BoolP("boold", "d", false, "bool4 value") - stringaFlag := f.StringP("stringa", "s", "0", "string value") - stringzFlag := f.StringP("stringz", "z", "0", "string value") - extra := "interspersed-argument" - notaflag := "--i-look-like-a-flag" - args := []string{ - "-ab", - extra, - "-cs", - "hello", - "-z=something", - "-d=true", - "--", - notaflag, - } - f.SetOutput(ioutil.Discard) - if err := f.Parse(args); err != nil { - t.Error("expected no error, got ", err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - if *boolaFlag != true { - t.Error("boola flag should be true, is ", *boolaFlag) - } - if *boolbFlag != true { - t.Error("boolb flag should be true, is ", *boolbFlag) - } - if *boolcFlag != true { - t.Error("boolc flag should be true, is ", *boolcFlag) - } - if *booldFlag != true { - t.Error("boold flag should be true, is ", *booldFlag) - } - if *stringaFlag != "hello" { - t.Error("stringa flag should be `hello`, is ", *stringaFlag) - } - if *stringzFlag != "something" { - t.Error("stringz flag should be `something`, is ", *stringzFlag) - } - if len(f.Args()) != 2 { - t.Error("expected one argument, got", len(f.Args())) - } else if f.Args()[0] != extra { - t.Errorf("expected argument %q got %q", extra, f.Args()[0]) - } else if f.Args()[1] != notaflag { - t.Errorf("expected argument %q got %q", notaflag, f.Args()[1]) - } - if f.ArgsLenAtDash() != 1 { - t.Errorf("expected argsLenAtDash %d got %d", f.ArgsLenAtDash(), 1) - } -} - -func TestShorthandLookup(t *testing.T) { - f := NewFlagSet("shorthand", ContinueOnError) - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - f.BoolP("boola", "a", false, "bool value") - f.BoolP("boolb", "b", false, "bool2 value") - args := []string{ - "-ab", - } - f.SetOutput(ioutil.Discard) - if err := f.Parse(args); err != nil { - t.Error("expected no error, got ", err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - flag := f.ShorthandLookup("a") - if flag == nil { - t.Errorf("f.ShorthandLookup(\"a\") returned nil") - } - if flag.Name != "boola" { - t.Errorf("f.ShorthandLookup(\"a\") found %q instead of \"boola\"", flag.Name) - } - flag = f.ShorthandLookup("") - if flag != nil { - t.Errorf("f.ShorthandLookup(\"\") did not return nil") - } - defer func() { - recover() - }() - flag = f.ShorthandLookup("ab") - // should NEVER get here. lookup should panic. defer'd func should recover it. - t.Errorf("f.ShorthandLookup(\"ab\") did not panic") -} - -func TestParse(t *testing.T) { - ResetForTesting(func() { t.Error("bad parse") }) - testParse(GetCommandLine(), t) -} - -func TestParseAll(t *testing.T) { - ResetForTesting(func() { t.Error("bad parse") }) - testParseAll(GetCommandLine(), t) -} - -func TestFlagSetParse(t *testing.T) { - testParse(NewFlagSet("test", ContinueOnError), t) -} - -func TestChangedHelper(t *testing.T) { - f := NewFlagSet("changedtest", ContinueOnError) - f.Bool("changed", false, "changed bool") - f.Bool("settrue", true, "true to true") - f.Bool("setfalse", false, "false to false") - f.Bool("unchanged", false, "unchanged bool") - - args := []string{"--changed", "--settrue", "--setfalse=false"} - if err := f.Parse(args); err != nil { - t.Error("f.Parse() = false after Parse") - } - if !f.Changed("changed") { - t.Errorf("--changed wasn't changed!") - } - if !f.Changed("settrue") { - t.Errorf("--settrue wasn't changed!") - } - if !f.Changed("setfalse") { - t.Errorf("--setfalse wasn't changed!") - } - if f.Changed("unchanged") { - t.Errorf("--unchanged was changed!") - } - if f.Changed("invalid") { - t.Errorf("--invalid was changed!") - } - if f.ArgsLenAtDash() != -1 { - t.Errorf("Expected argsLenAtDash: %d but got %d", -1, f.ArgsLenAtDash()) - } -} - -func replaceSeparators(name string, from []string, to string) string { - result := name - for _, sep := range from { - result = strings.Replace(result, sep, to, -1) - } - // Type convert to indicate normalization has been done. - return result -} - -func wordSepNormalizeFunc(f *FlagSet, name string) NormalizedName { - seps := []string{"-", "_"} - name = replaceSeparators(name, seps, ".") - normalizeFlagNameInvocations++ - - return NormalizedName(name) -} - -func testWordSepNormalizedNames(args []string, t *testing.T) { - f := NewFlagSet("normalized", ContinueOnError) - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - withDashFlag := f.Bool("with-dash-flag", false, "bool value") - // Set this after some flags have been added and before others. - f.SetNormalizeFunc(wordSepNormalizeFunc) - withUnderFlag := f.Bool("with_under_flag", false, "bool value") - withBothFlag := f.Bool("with-both_flag", false, "bool value") - if err := f.Parse(args); err != nil { - t.Fatal(err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - if *withDashFlag != true { - t.Error("withDashFlag flag should be true, is ", *withDashFlag) - } - if *withUnderFlag != true { - t.Error("withUnderFlag flag should be true, is ", *withUnderFlag) - } - if *withBothFlag != true { - t.Error("withBothFlag flag should be true, is ", *withBothFlag) - } -} - -func TestWordSepNormalizedNames(t *testing.T) { - args := []string{ - "--with-dash-flag", - "--with-under-flag", - "--with-both-flag", - } - testWordSepNormalizedNames(args, t) - - args = []string{ - "--with_dash_flag", - "--with_under_flag", - "--with_both_flag", - } - testWordSepNormalizedNames(args, t) - - args = []string{ - "--with-dash_flag", - "--with-under_flag", - "--with-both_flag", - } - testWordSepNormalizedNames(args, t) -} - -func aliasAndWordSepFlagNames(f *FlagSet, name string) NormalizedName { - seps := []string{"-", "_"} - - oldName := replaceSeparators("old-valid_flag", seps, ".") - newName := replaceSeparators("valid-flag", seps, ".") - - name = replaceSeparators(name, seps, ".") - switch name { - case oldName: - name = newName - break - } - - return NormalizedName(name) -} - -func TestCustomNormalizedNames(t *testing.T) { - f := NewFlagSet("normalized", ContinueOnError) - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - - validFlag := f.Bool("valid-flag", false, "bool value") - f.SetNormalizeFunc(aliasAndWordSepFlagNames) - someOtherFlag := f.Bool("some-other-flag", false, "bool value") - - args := []string{"--old_valid_flag", "--some-other_flag"} - if err := f.Parse(args); err != nil { - t.Fatal(err) - } - - if *validFlag != true { - t.Errorf("validFlag is %v even though we set the alias --old_valid_falg", *validFlag) - } - if *someOtherFlag != true { - t.Error("someOtherFlag should be true, is ", *someOtherFlag) - } -} - -// Every flag we add, the name (displayed also in usage) should normalized -func TestNormalizationFuncShouldChangeFlagName(t *testing.T) { - // Test normalization after addition - f := NewFlagSet("normalized", ContinueOnError) - - f.Bool("valid_flag", false, "bool value") - if f.Lookup("valid_flag").Name != "valid_flag" { - t.Error("The new flag should have the name 'valid_flag' instead of ", f.Lookup("valid_flag").Name) - } - - f.SetNormalizeFunc(wordSepNormalizeFunc) - if f.Lookup("valid_flag").Name != "valid.flag" { - t.Error("The new flag should have the name 'valid.flag' instead of ", f.Lookup("valid_flag").Name) - } - - // Test normalization before addition - f = NewFlagSet("normalized", ContinueOnError) - f.SetNormalizeFunc(wordSepNormalizeFunc) - - f.Bool("valid_flag", false, "bool value") - if f.Lookup("valid_flag").Name != "valid.flag" { - t.Error("The new flag should have the name 'valid.flag' instead of ", f.Lookup("valid_flag").Name) - } -} - -// Declare a user-defined flag type. -type flagVar []string - -func (f *flagVar) String() string { - return fmt.Sprint([]string(*f)) -} - -func (f *flagVar) Set(value string) error { - *f = append(*f, value) - return nil -} - -func (f *flagVar) Type() string { - return "flagVar" -} - -func TestUserDefined(t *testing.T) { - var flags FlagSet - flags.Init("test", ContinueOnError) - var v flagVar - flags.VarP(&v, "v", "v", "usage") - if err := flags.Parse([]string{"--v=1", "-v2", "-v", "3"}); err != nil { - t.Error(err) - } - if len(v) != 3 { - t.Fatal("expected 3 args; got ", len(v)) - } - expect := "[1 2 3]" - if v.String() != expect { - t.Errorf("expected value %q got %q", expect, v.String()) - } -} - -func TestSetOutput(t *testing.T) { - var flags FlagSet - var buf bytes.Buffer - flags.SetOutput(&buf) - flags.Init("test", ContinueOnError) - flags.Parse([]string{"--unknown"}) - if out := buf.String(); !strings.Contains(out, "--unknown") { - t.Logf("expected output mentioning unknown; got %q", out) - } -} - -// This tests that one can reset the flags. This still works but not well, and is -// superseded by FlagSet. -func TestChangingArgs(t *testing.T) { - ResetForTesting(func() { t.Fatal("bad parse") }) - oldArgs := os.Args - defer func() { os.Args = oldArgs }() - os.Args = []string{"cmd", "--before", "subcmd"} - before := Bool("before", false, "") - if err := GetCommandLine().Parse(os.Args[1:]); err != nil { - t.Fatal(err) - } - cmd := Arg(0) - os.Args = []string{"subcmd", "--after", "args"} - after := Bool("after", false, "") - Parse() - args := Args() - - if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" { - t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args) - } -} - -// Test that -help invokes the usage message and returns ErrHelp. -func TestHelp(t *testing.T) { - var helpCalled = false - fs := NewFlagSet("help test", ContinueOnError) - fs.Usage = func() { helpCalled = true } - var flag bool - fs.BoolVar(&flag, "flag", false, "regular flag") - // Regular flag invocation should work - err := fs.Parse([]string{"--flag=true"}) - if err != nil { - t.Fatal("expected no error; got ", err) - } - if !flag { - t.Error("flag was not set by --flag") - } - if helpCalled { - t.Error("help called for regular flag") - helpCalled = false // reset for next test - } - // Help flag should work as expected. - err = fs.Parse([]string{"--help"}) - if err == nil { - t.Fatal("error expected") - } - if err != ErrHelp { - t.Fatal("expected ErrHelp; got ", err) - } - if !helpCalled { - t.Fatal("help was not called") - } - // If we define a help flag, that should override. - var help bool - fs.BoolVar(&help, "help", false, "help flag") - helpCalled = false - err = fs.Parse([]string{"--help"}) - if err != nil { - t.Fatal("expected no error for defined --help; got ", err) - } - if helpCalled { - t.Fatal("help was called; should not have been for defined help flag") - } -} - -func TestNoInterspersed(t *testing.T) { - f := NewFlagSet("test", ContinueOnError) - f.SetInterspersed(false) - f.Bool("true", true, "always true") - f.Bool("false", false, "always false") - err := f.Parse([]string{"--true", "break", "--false"}) - if err != nil { - t.Fatal("expected no error; got ", err) - } - args := f.Args() - if len(args) != 2 || args[0] != "break" || args[1] != "--false" { - t.Fatal("expected interspersed options/non-options to fail") - } -} - -func TestTermination(t *testing.T) { - f := NewFlagSet("termination", ContinueOnError) - boolFlag := f.BoolP("bool", "l", false, "bool value") - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - arg1 := "ls" - arg2 := "-l" - args := []string{ - "--", - arg1, - arg2, - } - f.SetOutput(ioutil.Discard) - if err := f.Parse(args); err != nil { - t.Fatal("expected no error; got ", err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - if *boolFlag { - t.Error("expected boolFlag=false, got true") - } - if len(f.Args()) != 2 { - t.Errorf("expected 2 arguments, got %d: %v", len(f.Args()), f.Args()) - } - if f.Args()[0] != arg1 { - t.Errorf("expected argument %q got %q", arg1, f.Args()[0]) - } - if f.Args()[1] != arg2 { - t.Errorf("expected argument %q got %q", arg2, f.Args()[1]) - } - if f.ArgsLenAtDash() != 0 { - t.Errorf("expected argsLenAtDash %d got %d", 0, f.ArgsLenAtDash()) - } -} - -func TestDeprecatedFlagInDocs(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("badflag", true, "always true") - f.MarkDeprecated("badflag", "use --good-flag instead") - - out := new(bytes.Buffer) - f.SetOutput(out) - f.PrintDefaults() - - if strings.Contains(out.String(), "badflag") { - t.Errorf("found deprecated flag in usage!") - } -} - -func TestDeprecatedFlagShorthandInDocs(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - name := "noshorthandflag" - f.BoolP(name, "n", true, "always true") - f.MarkShorthandDeprecated("noshorthandflag", fmt.Sprintf("use --%s instead", name)) - - out := new(bytes.Buffer) - f.SetOutput(out) - f.PrintDefaults() - - if strings.Contains(out.String(), "-n,") { - t.Errorf("found deprecated flag shorthand in usage!") - } -} - -func parseReturnStderr(t *testing.T, f *FlagSet, args []string) (string, error) { - oldStderr := os.Stderr - r, w, _ := os.Pipe() - os.Stderr = w - - err := f.Parse(args) - - outC := make(chan string) - // copy the output in a separate goroutine so printing can't block indefinitely - go func() { - var buf bytes.Buffer - io.Copy(&buf, r) - outC <- buf.String() - }() - - w.Close() - os.Stderr = oldStderr - out := <-outC - - return out, err -} - -func TestDeprecatedFlagUsage(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("badflag", true, "always true") - usageMsg := "use --good-flag instead" - f.MarkDeprecated("badflag", usageMsg) - - args := []string{"--badflag"} - out, err := parseReturnStderr(t, f, args) - if err != nil { - t.Fatal("expected no error; got ", err) - } - - if !strings.Contains(out, usageMsg) { - t.Errorf("usageMsg not printed when using a deprecated flag!") - } -} - -func TestDeprecatedFlagShorthandUsage(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - name := "noshorthandflag" - f.BoolP(name, "n", true, "always true") - usageMsg := fmt.Sprintf("use --%s instead", name) - f.MarkShorthandDeprecated(name, usageMsg) - - args := []string{"-n"} - out, err := parseReturnStderr(t, f, args) - if err != nil { - t.Fatal("expected no error; got ", err) - } - - if !strings.Contains(out, usageMsg) { - t.Errorf("usageMsg not printed when using a deprecated flag!") - } -} - -func TestDeprecatedFlagUsageNormalized(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("bad-double_flag", true, "always true") - f.SetNormalizeFunc(wordSepNormalizeFunc) - usageMsg := "use --good-flag instead" - f.MarkDeprecated("bad_double-flag", usageMsg) - - args := []string{"--bad_double_flag"} - out, err := parseReturnStderr(t, f, args) - if err != nil { - t.Fatal("expected no error; got ", err) - } - - if !strings.Contains(out, usageMsg) { - t.Errorf("usageMsg not printed when using a deprecated flag!") - } -} - -// Name normalization function should be called only once on flag addition -func TestMultipleNormalizeFlagNameInvocations(t *testing.T) { - normalizeFlagNameInvocations = 0 - - f := NewFlagSet("normalized", ContinueOnError) - f.SetNormalizeFunc(wordSepNormalizeFunc) - f.Bool("with_under_flag", false, "bool value") - - if normalizeFlagNameInvocations != 1 { - t.Fatal("Expected normalizeFlagNameInvocations to be 1; got ", normalizeFlagNameInvocations) - } -} - -// -func TestHiddenFlagInUsage(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("secretFlag", true, "shhh") - f.MarkHidden("secretFlag") - - out := new(bytes.Buffer) - f.SetOutput(out) - f.PrintDefaults() - - if strings.Contains(out.String(), "secretFlag") { - t.Errorf("found hidden flag in usage!") - } -} - -// -func TestHiddenFlagUsage(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("secretFlag", true, "shhh") - f.MarkHidden("secretFlag") - - args := []string{"--secretFlag"} - out, err := parseReturnStderr(t, f, args) - if err != nil { - t.Fatal("expected no error; got ", err) - } - - if strings.Contains(out, "shhh") { - t.Errorf("usage message printed when using a hidden flag!") - } -} - -const defaultOutput = ` --A for bootstrapping, allow 'any' type - --Alongflagname disable bounds checking - -C, --CCC a boolean defaulting to true (default true) - --D path set relative path for local imports - -E, --EEE num[=1234] a num with NoOptDefVal (default 4321) - --F number a non-zero number (default 2.7) - --G float a float that defaults to zero - --IP ip IP address with no default - --IPMask ipMask Netmask address with no default - --IPNet ipNet IP network with no default - --Ints ints int slice with zero default - --N int a non-zero int (default 27) - --ND1 string[="bar"] a string with NoOptDefVal (default "foo") - --ND2 num[=4321] a num with NoOptDefVal (default 1234) - --StringArray stringArray string array with zero default - --StringSlice strings string slice with zero default - --Z int an int that defaults to zero - --custom custom custom Value implementation - --customP custom a VarP with default (default 10) - --maxT timeout set timeout for dial -` - -// Custom value that satisfies the Value interface. -type customValue int - -func (cv *customValue) String() string { return fmt.Sprintf("%v", *cv) } - -func (cv *customValue) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 64) - *cv = customValue(v) - return err -} - -func (cv *customValue) Type() string { return "custom" } - -func TestPrintDefaults(t *testing.T) { - fs := NewFlagSet("print defaults test", ContinueOnError) - var buf bytes.Buffer - fs.SetOutput(&buf) - fs.Bool("A", false, "for bootstrapping, allow 'any' type") - fs.Bool("Alongflagname", false, "disable bounds checking") - fs.BoolP("CCC", "C", true, "a boolean defaulting to true") - fs.String("D", "", "set relative `path` for local imports") - fs.Float64("F", 2.7, "a non-zero `number`") - fs.Float64("G", 0, "a float that defaults to zero") - fs.Int("N", 27, "a non-zero int") - fs.IntSlice("Ints", []int{}, "int slice with zero default") - fs.IP("IP", nil, "IP address with no default") - fs.IPMask("IPMask", nil, "Netmask address with no default") - fs.IPNet("IPNet", net.IPNet{}, "IP network with no default") - fs.Int("Z", 0, "an int that defaults to zero") - fs.Duration("maxT", 0, "set `timeout` for dial") - fs.String("ND1", "foo", "a string with NoOptDefVal") - fs.Lookup("ND1").NoOptDefVal = "bar" - fs.Int("ND2", 1234, "a `num` with NoOptDefVal") - fs.Lookup("ND2").NoOptDefVal = "4321" - fs.IntP("EEE", "E", 4321, "a `num` with NoOptDefVal") - fs.ShorthandLookup("E").NoOptDefVal = "1234" - fs.StringSlice("StringSlice", []string{}, "string slice with zero default") - fs.StringArray("StringArray", []string{}, "string array with zero default") - - var cv customValue - fs.Var(&cv, "custom", "custom Value implementation") - - cv2 := customValue(10) - fs.VarP(&cv2, "customP", "", "a VarP with default") - - fs.PrintDefaults() - got := buf.String() - if got != defaultOutput { - fmt.Println("\n" + got) - fmt.Println("\n" + defaultOutput) - t.Errorf("got %q want %q\n", got, defaultOutput) - } -} - -func TestVisitAllFlagOrder(t *testing.T) { - fs := NewFlagSet("TestVisitAllFlagOrder", ContinueOnError) - fs.SortFlags = false - // https://github.com/spf13/pflag/issues/120 - fs.SetNormalizeFunc(func(f *FlagSet, name string) NormalizedName { - return NormalizedName(name) - }) - - names := []string{"C", "B", "A", "D"} - for _, name := range names { - fs.Bool(name, false, "") - } - - i := 0 - fs.VisitAll(func(f *Flag) { - if names[i] != f.Name { - t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name) - } - i++ - }) -} - -func TestVisitFlagOrder(t *testing.T) { - fs := NewFlagSet("TestVisitFlagOrder", ContinueOnError) - fs.SortFlags = false - names := []string{"C", "B", "A", "D"} - for _, name := range names { - fs.Bool(name, false, "") - fs.Set(name, "true") - } - - i := 0 - fs.Visit(func(f *Flag) { - if names[i] != f.Name { - t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name) - } - i++ - }) -} diff --git a/vendor/github.com/spf13/pflag/golangflag_test.go b/vendor/github.com/spf13/pflag/golangflag_test.go deleted file mode 100644 index 77e2d7d80a3d..000000000000 --- a/vendor/github.com/spf13/pflag/golangflag_test.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pflag - -import ( - goflag "flag" - "testing" -) - -func TestGoflags(t *testing.T) { - goflag.String("stringFlag", "stringFlag", "stringFlag") - goflag.Bool("boolFlag", false, "boolFlag") - - f := NewFlagSet("test", ContinueOnError) - - f.AddGoFlagSet(goflag.CommandLine) - err := f.Parse([]string{"--stringFlag=bob", "--boolFlag"}) - if err != nil { - t.Fatal("expected no error; get", err) - } - - getString, err := f.GetString("stringFlag") - if err != nil { - t.Fatal("expected no error; get", err) - } - if getString != "bob" { - t.Fatalf("expected getString=bob but got getString=%s", getString) - } - - getBool, err := f.GetBool("boolFlag") - if err != nil { - t.Fatal("expected no error; get", err) - } - if getBool != true { - t.Fatalf("expected getBool=true but got getBool=%v", getBool) - } -} diff --git a/vendor/github.com/spf13/pflag/int_slice_test.go b/vendor/github.com/spf13/pflag/int_slice_test.go deleted file mode 100644 index 745aecb950a2..000000000000 --- a/vendor/github.com/spf13/pflag/int_slice_test.go +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pflag - -import ( - "fmt" - "strconv" - "strings" - "testing" -) - -func setUpISFlagSet(isp *[]int) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.IntSliceVar(isp, "is", []int{}, "Command separated list!") - return f -} - -func setUpISFlagSetWithDefault(isp *[]int) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.IntSliceVar(isp, "is", []int{0, 1}, "Command separated list!") - return f -} - -func TestEmptyIS(t *testing.T) { - var is []int - f := setUpISFlagSet(&is) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getIS, err := f.GetIntSlice("is") - if err != nil { - t.Fatal("got an error from GetIntSlice():", err) - } - if len(getIS) != 0 { - t.Fatalf("got is %v with len=%d but expected length=0", getIS, len(getIS)) - } -} - -func TestIS(t *testing.T) { - var is []int - f := setUpISFlagSet(&is) - - vals := []string{"1", "2", "4", "3"} - arg := fmt.Sprintf("--is=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range is { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %s but got: %d", i, vals[i], v) - } - } - getIS, err := f.GetIntSlice("is") - if err != nil { - t.Fatalf("got error: %v", err) - } - for i, v := range getIS { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %s but got: %d from GetIntSlice", i, vals[i], v) - } - } -} - -func TestISDefault(t *testing.T) { - var is []int - f := setUpISFlagSetWithDefault(&is) - - vals := []string{"0", "1"} - - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range is { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %d but got: %d", i, d, v) - } - } - - getIS, err := f.GetIntSlice("is") - if err != nil { - t.Fatal("got an error from GetIntSlice():", err) - } - for i, v := range getIS { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatal("got an error from GetIntSlice():", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %d from GetIntSlice but got: %d", i, d, v) - } - } -} - -func TestISWithDefault(t *testing.T) { - var is []int - f := setUpISFlagSetWithDefault(&is) - - vals := []string{"1", "2"} - arg := fmt.Sprintf("--is=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range is { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %d but got: %d", i, d, v) - } - } - - getIS, err := f.GetIntSlice("is") - if err != nil { - t.Fatal("got an error from GetIntSlice():", err) - } - for i, v := range getIS { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %d from GetIntSlice but got: %d", i, d, v) - } - } -} - -func TestISCalledTwice(t *testing.T) { - var is []int - f := setUpISFlagSet(&is) - - in := []string{"1,2", "3"} - expected := []int{1, 2, 3} - argfmt := "--is=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range is { - if expected[i] != v { - t.Fatalf("expected is[%d] to be %d but got: %d", i, expected[i], v) - } - } -} diff --git a/vendor/github.com/spf13/pflag/ip_slice_test.go b/vendor/github.com/spf13/pflag/ip_slice_test.go deleted file mode 100644 index b0c681c5b2ac..000000000000 --- a/vendor/github.com/spf13/pflag/ip_slice_test.go +++ /dev/null @@ -1,222 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "strings" - "testing" -) - -func setUpIPSFlagSet(ipsp *[]net.IP) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.IPSliceVar(ipsp, "ips", []net.IP{}, "Command separated list!") - return f -} - -func setUpIPSFlagSetWithDefault(ipsp *[]net.IP) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.IPSliceVar(ipsp, "ips", - []net.IP{ - net.ParseIP("192.168.1.1"), - net.ParseIP("0:0:0:0:0:0:0:1"), - }, - "Command separated list!") - return f -} - -func TestEmptyIP(t *testing.T) { - var ips []net.IP - f := setUpIPSFlagSet(&ips) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getIPS, err := f.GetIPSlice("ips") - if err != nil { - t.Fatal("got an error from GetIPSlice():", err) - } - if len(getIPS) != 0 { - t.Fatalf("got ips %v with len=%d but expected length=0", getIPS, len(getIPS)) - } -} - -func TestIPS(t *testing.T) { - var ips []net.IP - f := setUpIPSFlagSet(&ips) - - vals := []string{"192.168.1.1", "10.0.0.1", "0:0:0:0:0:0:0:2"} - arg := fmt.Sprintf("--ips=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ips { - if ip := net.ParseIP(vals[i]); ip == nil { - t.Fatalf("invalid string being converted to IP address: %s", vals[i]) - } else if !ip.Equal(v) { - t.Fatalf("expected ips[%d] to be %s but got: %s from GetIPSlice", i, vals[i], v) - } - } -} - -func TestIPSDefault(t *testing.T) { - var ips []net.IP - f := setUpIPSFlagSetWithDefault(&ips) - - vals := []string{"192.168.1.1", "0:0:0:0:0:0:0:1"} - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ips { - if ip := net.ParseIP(vals[i]); ip == nil { - t.Fatalf("invalid string being converted to IP address: %s", vals[i]) - } else if !ip.Equal(v) { - t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getIPS, err := f.GetIPSlice("ips") - if err != nil { - t.Fatal("got an error from GetIPSlice") - } - for i, v := range getIPS { - if ip := net.ParseIP(vals[i]); ip == nil { - t.Fatalf("invalid string being converted to IP address: %s", vals[i]) - } else if !ip.Equal(v) { - t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v) - } - } -} - -func TestIPSWithDefault(t *testing.T) { - var ips []net.IP - f := setUpIPSFlagSetWithDefault(&ips) - - vals := []string{"192.168.1.1", "0:0:0:0:0:0:0:1"} - arg := fmt.Sprintf("--ips=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ips { - if ip := net.ParseIP(vals[i]); ip == nil { - t.Fatalf("invalid string being converted to IP address: %s", vals[i]) - } else if !ip.Equal(v) { - t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getIPS, err := f.GetIPSlice("ips") - if err != nil { - t.Fatal("got an error from GetIPSlice") - } - for i, v := range getIPS { - if ip := net.ParseIP(vals[i]); ip == nil { - t.Fatalf("invalid string being converted to IP address: %s", vals[i]) - } else if !ip.Equal(v) { - t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v) - } - } -} - -func TestIPSCalledTwice(t *testing.T) { - var ips []net.IP - f := setUpIPSFlagSet(&ips) - - in := []string{"192.168.1.2,0:0:0:0:0:0:0:1", "10.0.0.1"} - expected := []net.IP{net.ParseIP("192.168.1.2"), net.ParseIP("0:0:0:0:0:0:0:1"), net.ParseIP("10.0.0.1")} - argfmt := "ips=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ips { - if !expected[i].Equal(v) { - t.Fatalf("expected ips[%d] to be %s but got: %s", i, expected[i], v) - } - } -} - -func TestIPSBadQuoting(t *testing.T) { - - tests := []struct { - Want []net.IP - FlagArg []string - }{ - { - Want: []net.IP{ - net.ParseIP("a4ab:61d:f03e:5d7d:fad7:d4c2:a1a5:568"), - net.ParseIP("203.107.49.208"), - net.ParseIP("14.57.204.90"), - }, - FlagArg: []string{ - "a4ab:61d:f03e:5d7d:fad7:d4c2:a1a5:568", - "203.107.49.208", - "14.57.204.90", - }, - }, - { - Want: []net.IP{ - net.ParseIP("204.228.73.195"), - net.ParseIP("86.141.15.94"), - }, - FlagArg: []string{ - "204.228.73.195", - "86.141.15.94", - }, - }, - { - Want: []net.IP{ - net.ParseIP("c70c:db36:3001:890f:c6ea:3f9b:7a39:cc3f"), - net.ParseIP("4d17:1d6e:e699:bd7a:88c5:5e7e:ac6a:4472"), - }, - FlagArg: []string{ - "c70c:db36:3001:890f:c6ea:3f9b:7a39:cc3f", - "4d17:1d6e:e699:bd7a:88c5:5e7e:ac6a:4472", - }, - }, - { - Want: []net.IP{ - net.ParseIP("5170:f971:cfac:7be3:512a:af37:952c:bc33"), - net.ParseIP("93.21.145.140"), - net.ParseIP("2cac:61d3:c5ff:6caf:73e0:1b1a:c336:c1ca"), - }, - FlagArg: []string{ - " 5170:f971:cfac:7be3:512a:af37:952c:bc33 , 93.21.145.140 ", - "2cac:61d3:c5ff:6caf:73e0:1b1a:c336:c1ca", - }, - }, - { - Want: []net.IP{ - net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"), - net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"), - net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"), - net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"), - }, - FlagArg: []string{ - `"2e5e:66b2:6441:848:5b74:76ea:574c:3a7b, 2e5e:66b2:6441:848:5b74:76ea:574c:3a7b,2e5e:66b2:6441:848:5b74:76ea:574c:3a7b "`, - " 2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"}, - }, - } - - for i, test := range tests { - - var ips []net.IP - f := setUpIPSFlagSet(&ips) - - if err := f.Parse([]string{fmt.Sprintf("--ips=%s", strings.Join(test.FlagArg, ","))}); err != nil { - t.Fatalf("flag parsing failed with error: %s\nparsing:\t%#v\nwant:\t\t%s", - err, test.FlagArg, test.Want[i]) - } - - for j, b := range ips { - if !b.Equal(test.Want[j]) { - t.Fatalf("bad value parsed for test %d on net.IP %d:\nwant:\t%s\ngot:\t%s", i, j, test.Want[j], b) - } - } - } -} diff --git a/vendor/github.com/spf13/pflag/ip_test.go b/vendor/github.com/spf13/pflag/ip_test.go deleted file mode 100644 index 1fec50e4252d..000000000000 --- a/vendor/github.com/spf13/pflag/ip_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "os" - "testing" -) - -func setUpIP(ip *net.IP) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.IPVar(ip, "address", net.ParseIP("0.0.0.0"), "IP Address") - return f -} - -func TestIP(t *testing.T) { - testCases := []struct { - input string - success bool - expected string - }{ - {"0.0.0.0", true, "0.0.0.0"}, - {" 0.0.0.0 ", true, "0.0.0.0"}, - {"1.2.3.4", true, "1.2.3.4"}, - {"127.0.0.1", true, "127.0.0.1"}, - {"255.255.255.255", true, "255.255.255.255"}, - {"", false, ""}, - {"0", false, ""}, - {"localhost", false, ""}, - {"0.0.0", false, ""}, - {"0.0.0.", false, ""}, - {"0.0.0.0.", false, ""}, - {"0.0.0.256", false, ""}, - {"0 . 0 . 0 . 0", false, ""}, - } - - devnull, _ := os.Open(os.DevNull) - os.Stderr = devnull - for i := range testCases { - var addr net.IP - f := setUpIP(&addr) - - tc := &testCases[i] - - arg := fmt.Sprintf("--address=%s", tc.input) - err := f.Parse([]string{arg}) - if err != nil && tc.success == true { - t.Errorf("expected success, got %q", err) - continue - } else if err == nil && tc.success == false { - t.Errorf("expected failure") - continue - } else if tc.success { - ip, err := f.GetIP("address") - if err != nil { - t.Errorf("Got error trying to fetch the IP flag: %v", err) - } - if ip.String() != tc.expected { - t.Errorf("expected %q, got %q", tc.expected, ip.String()) - } - } - } -} diff --git a/vendor/github.com/spf13/pflag/ipnet_test.go b/vendor/github.com/spf13/pflag/ipnet_test.go deleted file mode 100644 index 335b6fa156d3..000000000000 --- a/vendor/github.com/spf13/pflag/ipnet_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "os" - "testing" -) - -func setUpIPNet(ip *net.IPNet) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - _, def, _ := net.ParseCIDR("0.0.0.0/0") - f.IPNetVar(ip, "address", *def, "IP Address") - return f -} - -func TestIPNet(t *testing.T) { - testCases := []struct { - input string - success bool - expected string - }{ - {"0.0.0.0/0", true, "0.0.0.0/0"}, - {" 0.0.0.0/0 ", true, "0.0.0.0/0"}, - {"1.2.3.4/8", true, "1.0.0.0/8"}, - {"127.0.0.1/16", true, "127.0.0.0/16"}, - {"255.255.255.255/19", true, "255.255.224.0/19"}, - {"255.255.255.255/32", true, "255.255.255.255/32"}, - {"", false, ""}, - {"/0", false, ""}, - {"0", false, ""}, - {"0/0", false, ""}, - {"localhost/0", false, ""}, - {"0.0.0/4", false, ""}, - {"0.0.0./8", false, ""}, - {"0.0.0.0./12", false, ""}, - {"0.0.0.256/16", false, ""}, - {"0.0.0.0 /20", false, ""}, - {"0.0.0.0/ 24", false, ""}, - {"0 . 0 . 0 . 0 / 28", false, ""}, - {"0.0.0.0/33", false, ""}, - } - - devnull, _ := os.Open(os.DevNull) - os.Stderr = devnull - for i := range testCases { - var addr net.IPNet - f := setUpIPNet(&addr) - - tc := &testCases[i] - - arg := fmt.Sprintf("--address=%s", tc.input) - err := f.Parse([]string{arg}) - if err != nil && tc.success == true { - t.Errorf("expected success, got %q", err) - continue - } else if err == nil && tc.success == false { - t.Errorf("expected failure") - continue - } else if tc.success { - ip, err := f.GetIPNet("address") - if err != nil { - t.Errorf("Got error trying to fetch the IP flag: %v", err) - } - if ip.String() != tc.expected { - t.Errorf("expected %q, got %q", tc.expected, ip.String()) - } - } - } -} diff --git a/vendor/github.com/spf13/pflag/string_array_test.go b/vendor/github.com/spf13/pflag/string_array_test.go deleted file mode 100644 index 1ceac8c6c699..000000000000 --- a/vendor/github.com/spf13/pflag/string_array_test.go +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pflag - -import ( - "fmt" - "testing" -) - -func setUpSAFlagSet(sap *[]string) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.StringArrayVar(sap, "sa", []string{}, "Command separated list!") - return f -} - -func setUpSAFlagSetWithDefault(sap *[]string) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.StringArrayVar(sap, "sa", []string{"default", "values"}, "Command separated list!") - return f -} - -func TestEmptySA(t *testing.T) { - var sa []string - f := setUpSAFlagSet(&sa) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getSA, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("got an error from GetStringArray():", err) - } - if len(getSA) != 0 { - t.Fatalf("got sa %v with len=%d but expected length=0", getSA, len(getSA)) - } -} - -func TestEmptySAValue(t *testing.T) { - var sa []string - f := setUpSAFlagSet(&sa) - err := f.Parse([]string{"--sa="}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getSA, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("got an error from GetStringArray():", err) - } - if len(getSA) != 0 { - t.Fatalf("got sa %v with len=%d but expected length=0", getSA, len(getSA)) - } -} - -func TestSADefault(t *testing.T) { - var sa []string - f := setUpSAFlagSetWithDefault(&sa) - - vals := []string{"default", "values"} - - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range sa { - if vals[i] != v { - t.Fatalf("expected sa[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getSA, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("got an error from GetStringArray():", err) - } - for i, v := range getSA { - if vals[i] != v { - t.Fatalf("expected sa[%d] to be %s from GetStringArray but got: %s", i, vals[i], v) - } - } -} - -func TestSAWithDefault(t *testing.T) { - var sa []string - f := setUpSAFlagSetWithDefault(&sa) - - val := "one" - arg := fmt.Sprintf("--sa=%s", val) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(sa) != 1 { - t.Fatalf("expected number of values to be %d but %d", 1, len(sa)) - } - - if sa[0] != val { - t.Fatalf("expected value to be %s but got: %s", sa[0], val) - } - - getSA, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("got an error from GetStringArray():", err) - } - - if len(getSA) != 1 { - t.Fatalf("expected number of values to be %d but %d", 1, len(getSA)) - } - - if getSA[0] != val { - t.Fatalf("expected value to be %s but got: %s", getSA[0], val) - } -} - -func TestSACalledTwice(t *testing.T) { - var sa []string - f := setUpSAFlagSet(&sa) - - in := []string{"one", "two"} - expected := []string{"one", "two"} - argfmt := "--sa=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(sa) { - t.Fatalf("expected number of sa to be %d but got: %d", len(expected), len(sa)) - } - for i, v := range sa { - if expected[i] != v { - t.Fatalf("expected sa[%d] to be %s but got: %s", i, expected[i], v) - } - } - - values, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(values) { - t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(sa)) - } - for i, v := range values { - if expected[i] != v { - t.Fatalf("expected got sa[%d] to be %s but got: %s", i, expected[i], v) - } - } -} - -func TestSAWithSpecialChar(t *testing.T) { - var sa []string - f := setUpSAFlagSet(&sa) - - in := []string{"one,two", `"three"`, `"four,five",six`, "seven eight"} - expected := []string{"one,two", `"three"`, `"four,five",six`, "seven eight"} - argfmt := "--sa=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - arg3 := fmt.Sprintf(argfmt, in[2]) - arg4 := fmt.Sprintf(argfmt, in[3]) - err := f.Parse([]string{arg1, arg2, arg3, arg4}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(sa) { - t.Fatalf("expected number of sa to be %d but got: %d", len(expected), len(sa)) - } - for i, v := range sa { - if expected[i] != v { - t.Fatalf("expected sa[%d] to be %s but got: %s", i, expected[i], v) - } - } - - values, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(values) { - t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values)) - } - for i, v := range values { - if expected[i] != v { - t.Fatalf("expected got sa[%d] to be %s but got: %s", i, expected[i], v) - } - } -} - -func TestSAWithSquareBrackets(t *testing.T) { - var sa []string - f := setUpSAFlagSet(&sa) - - in := []string{"][]-[", "[a-z]", "[a-z]+"} - expected := []string{"][]-[", "[a-z]", "[a-z]+"} - argfmt := "--sa=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - arg3 := fmt.Sprintf(argfmt, in[2]) - err := f.Parse([]string{arg1, arg2, arg3}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(sa) { - t.Fatalf("expected number of sa to be %d but got: %d", len(expected), len(sa)) - } - for i, v := range sa { - if expected[i] != v { - t.Fatalf("expected sa[%d] to be %s but got: %s", i, expected[i], v) - } - } - - values, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(values) { - t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values)) - } - for i, v := range values { - if expected[i] != v { - t.Fatalf("expected got sa[%d] to be %s but got: %s", i, expected[i], v) - } - } -} diff --git a/vendor/github.com/spf13/pflag/string_slice_test.go b/vendor/github.com/spf13/pflag/string_slice_test.go deleted file mode 100644 index c41f3bd660d5..000000000000 --- a/vendor/github.com/spf13/pflag/string_slice_test.go +++ /dev/null @@ -1,253 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pflag - -import ( - "fmt" - "strings" - "testing" -) - -func setUpSSFlagSet(ssp *[]string) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.StringSliceVar(ssp, "ss", []string{}, "Command separated list!") - return f -} - -func setUpSSFlagSetWithDefault(ssp *[]string) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.StringSliceVar(ssp, "ss", []string{"default", "values"}, "Command separated list!") - return f -} - -func TestEmptySS(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getSS, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("got an error from GetStringSlice():", err) - } - if len(getSS) != 0 { - t.Fatalf("got ss %v with len=%d but expected length=0", getSS, len(getSS)) - } -} - -func TestEmptySSValue(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - err := f.Parse([]string{"--ss="}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getSS, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("got an error from GetStringSlice():", err) - } - if len(getSS) != 0 { - t.Fatalf("got ss %v with len=%d but expected length=0", getSS, len(getSS)) - } -} - -func TestSS(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - - vals := []string{"one", "two", "4", "3"} - arg := fmt.Sprintf("--ss=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ss { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getSS, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("got an error from GetStringSlice():", err) - } - for i, v := range getSS { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v) - } - } -} - -func TestSSDefault(t *testing.T) { - var ss []string - f := setUpSSFlagSetWithDefault(&ss) - - vals := []string{"default", "values"} - - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ss { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getSS, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("got an error from GetStringSlice():", err) - } - for i, v := range getSS { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v) - } - } -} - -func TestSSWithDefault(t *testing.T) { - var ss []string - f := setUpSSFlagSetWithDefault(&ss) - - vals := []string{"one", "two", "4", "3"} - arg := fmt.Sprintf("--ss=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ss { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getSS, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("got an error from GetStringSlice():", err) - } - for i, v := range getSS { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v) - } - } -} - -func TestSSCalledTwice(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - - in := []string{"one,two", "three"} - expected := []string{"one", "two", "three"} - argfmt := "--ss=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(ss) { - t.Fatalf("expected number of ss to be %d but got: %d", len(expected), len(ss)) - } - for i, v := range ss { - if expected[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v) - } - } - - values, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(values) { - t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(ss)) - } - for i, v := range values { - if expected[i] != v { - t.Fatalf("expected got ss[%d] to be %s but got: %s", i, expected[i], v) - } - } -} - -func TestSSWithComma(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - - in := []string{`"one,two"`, `"three"`, `"four,five",six`} - expected := []string{"one,two", "three", "four,five", "six"} - argfmt := "--ss=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - arg3 := fmt.Sprintf(argfmt, in[2]) - err := f.Parse([]string{arg1, arg2, arg3}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(ss) { - t.Fatalf("expected number of ss to be %d but got: %d", len(expected), len(ss)) - } - for i, v := range ss { - if expected[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v) - } - } - - values, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(values) { - t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values)) - } - for i, v := range values { - if expected[i] != v { - t.Fatalf("expected got ss[%d] to be %s but got: %s", i, expected[i], v) - } - } -} - -func TestSSWithSquareBrackets(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - - in := []string{`"[a-z]"`, `"[a-z]+"`} - expected := []string{"[a-z]", "[a-z]+"} - argfmt := "--ss=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(ss) { - t.Fatalf("expected number of ss to be %d but got: %d", len(expected), len(ss)) - } - for i, v := range ss { - if expected[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v) - } - } - - values, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(values) { - t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values)) - } - for i, v := range values { - if expected[i] != v { - t.Fatalf("expected got ss[%d] to be %s but got: %s", i, expected[i], v) - } - } -} diff --git a/vendor/github.com/spf13/pflag/uint_slice_test.go b/vendor/github.com/spf13/pflag/uint_slice_test.go deleted file mode 100644 index db1a19dc2d64..000000000000 --- a/vendor/github.com/spf13/pflag/uint_slice_test.go +++ /dev/null @@ -1,161 +0,0 @@ -package pflag - -import ( - "fmt" - "strconv" - "strings" - "testing" -) - -func setUpUISFlagSet(uisp *[]uint) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.UintSliceVar(uisp, "uis", []uint{}, "Command separated list!") - return f -} - -func setUpUISFlagSetWithDefault(uisp *[]uint) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.UintSliceVar(uisp, "uis", []uint{0, 1}, "Command separated list!") - return f -} - -func TestEmptyUIS(t *testing.T) { - var uis []uint - f := setUpUISFlagSet(&uis) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getUIS, err := f.GetUintSlice("uis") - if err != nil { - t.Fatal("got an error from GetUintSlice():", err) - } - if len(getUIS) != 0 { - t.Fatalf("got is %v with len=%d but expected length=0", getUIS, len(getUIS)) - } -} - -func TestUIS(t *testing.T) { - var uis []uint - f := setUpUISFlagSet(&uis) - - vals := []string{"1", "2", "4", "3"} - arg := fmt.Sprintf("--uis=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range uis { - u, err := strconv.ParseUint(vals[i], 10, 0) - if err != nil { - t.Fatalf("got error: %v", err) - } - if uint(u) != v { - t.Fatalf("expected uis[%d] to be %s but got %d", i, vals[i], v) - } - } - getUIS, err := f.GetUintSlice("uis") - if err != nil { - t.Fatalf("got error: %v", err) - } - for i, v := range getUIS { - u, err := strconv.ParseUint(vals[i], 10, 0) - if err != nil { - t.Fatalf("got error: %v", err) - } - if uint(u) != v { - t.Fatalf("expected uis[%d] to be %s but got: %d from GetUintSlice", i, vals[i], v) - } - } -} - -func TestUISDefault(t *testing.T) { - var uis []uint - f := setUpUISFlagSetWithDefault(&uis) - - vals := []string{"0", "1"} - - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range uis { - u, err := strconv.ParseUint(vals[i], 10, 0) - if err != nil { - t.Fatalf("got error: %v", err) - } - if uint(u) != v { - t.Fatalf("expect uis[%d] to be %d but got: %d", i, u, v) - } - } - - getUIS, err := f.GetUintSlice("uis") - if err != nil { - t.Fatal("got an error from GetUintSlice():", err) - } - for i, v := range getUIS { - u, err := strconv.ParseUint(vals[i], 10, 0) - if err != nil { - t.Fatal("got an error from GetIntSlice():", err) - } - if uint(u) != v { - t.Fatalf("expected uis[%d] to be %d from GetUintSlice but got: %d", i, u, v) - } - } -} - -func TestUISWithDefault(t *testing.T) { - var uis []uint - f := setUpUISFlagSetWithDefault(&uis) - - vals := []string{"1", "2"} - arg := fmt.Sprintf("--uis=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range uis { - u, err := strconv.ParseUint(vals[i], 10, 0) - if err != nil { - t.Fatalf("got error: %v", err) - } - if uint(u) != v { - t.Fatalf("expected uis[%d] to be %d from GetUintSlice but got: %d", i, u, v) - } - } - - getUIS, err := f.GetUintSlice("uis") - if err != nil { - t.Fatal("got an error from GetUintSlice():", err) - } - for i, v := range getUIS { - u, err := strconv.ParseUint(vals[i], 10, 0) - if err != nil { - t.Fatalf("got error: %v", err) - } - if uint(u) != v { - t.Fatalf("expected uis[%d] to be %d from GetUintSlice but got: %d", i, u, v) - } - } -} - -func TestUISCalledTwice(t *testing.T) { - var uis []uint - f := setUpUISFlagSet(&uis) - - in := []string{"1,2", "3"} - expected := []int{1, 2, 3} - argfmt := "--uis=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range uis { - if uint(expected[i]) != v { - t.Fatalf("expected uis[%d] to be %d but got: %d", i, expected[i], v) - } - } -} diff --git a/vendor/golang.org/x/crypto/curve25519/BUILD b/vendor/golang.org/x/crypto/curve25519/BUILD index ed06a617e137..2c5638b2dcc1 100644 --- a/vendor/golang.org/x/crypto/curve25519/BUILD +++ b/vendor/golang.org/x/crypto/curve25519/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -42,13 +42,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = ["curve25519_test.go"], - importpath = "golang.org/x/crypto/curve25519", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/golang.org/x/crypto/curve25519/curve25519_test.go b/vendor/golang.org/x/crypto/curve25519/curve25519_test.go deleted file mode 100644 index 051a8301f080..000000000000 --- a/vendor/golang.org/x/crypto/curve25519/curve25519_test.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package curve25519 - -import ( - "fmt" - "testing" -) - -const expectedHex = "89161fde887b2b53de549af483940106ecc114d6982daa98256de23bdf77661a" - -func TestBaseScalarMult(t *testing.T) { - var a, b [32]byte - in := &a - out := &b - a[0] = 1 - - for i := 0; i < 200; i++ { - ScalarBaseMult(out, in) - in, out = out, in - } - - result := fmt.Sprintf("%x", in[:]) - if result != expectedHex { - t.Errorf("incorrect result: got %s, want %s", result, expectedHex) - } -} - -func BenchmarkScalarBaseMult(b *testing.B) { - var in, out [32]byte - in[0] = 1 - - b.SetBytes(32) - for i := 0; i < b.N; i++ { - ScalarBaseMult(&out, &in) - } -} diff --git a/vendor/golang.org/x/crypto/ed25519/BUILD b/vendor/golang.org/x/crypto/ed25519/BUILD index 7be0aca8ff6a..3315a838d974 100644 --- a/vendor/golang.org/x/crypto/ed25519/BUILD +++ b/vendor/golang.org/x/crypto/ed25519/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -8,14 +8,6 @@ go_library( deps = ["//vendor/golang.org/x/crypto/ed25519/internal/edwards25519:go_default_library"], ) -go_test( - name = "go_default_test", - srcs = ["ed25519_test.go"], - importpath = "golang.org/x/crypto/ed25519", - library = ":go_default_library", - deps = ["//vendor/golang.org/x/crypto/ed25519/internal/edwards25519:go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/golang.org/x/crypto/ed25519/ed25519_test.go b/vendor/golang.org/x/crypto/ed25519/ed25519_test.go deleted file mode 100644 index e272f8a557f9..000000000000 --- a/vendor/golang.org/x/crypto/ed25519/ed25519_test.go +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ed25519 - -import ( - "bufio" - "bytes" - "compress/gzip" - "crypto" - "crypto/rand" - "encoding/hex" - "os" - "strings" - "testing" - - "golang.org/x/crypto/ed25519/internal/edwards25519" -) - -type zeroReader struct{} - -func (zeroReader) Read(buf []byte) (int, error) { - for i := range buf { - buf[i] = 0 - } - return len(buf), nil -} - -func TestUnmarshalMarshal(t *testing.T) { - pub, _, _ := GenerateKey(rand.Reader) - - var A edwards25519.ExtendedGroupElement - var pubBytes [32]byte - copy(pubBytes[:], pub) - if !A.FromBytes(&pubBytes) { - t.Fatalf("ExtendedGroupElement.FromBytes failed") - } - - var pub2 [32]byte - A.ToBytes(&pub2) - - if pubBytes != pub2 { - t.Errorf("FromBytes(%v)->ToBytes does not round-trip, got %x\n", pubBytes, pub2) - } -} - -func TestSignVerify(t *testing.T) { - var zero zeroReader - public, private, _ := GenerateKey(zero) - - message := []byte("test message") - sig := Sign(private, message) - if !Verify(public, message, sig) { - t.Errorf("valid signature rejected") - } - - wrongMessage := []byte("wrong message") - if Verify(public, wrongMessage, sig) { - t.Errorf("signature of different message accepted") - } -} - -func TestCryptoSigner(t *testing.T) { - var zero zeroReader - public, private, _ := GenerateKey(zero) - - signer := crypto.Signer(private) - - publicInterface := signer.Public() - public2, ok := publicInterface.(PublicKey) - if !ok { - t.Fatalf("expected PublicKey from Public() but got %T", publicInterface) - } - - if !bytes.Equal(public, public2) { - t.Errorf("public keys do not match: original:%x vs Public():%x", public, public2) - } - - message := []byte("message") - var noHash crypto.Hash - signature, err := signer.Sign(zero, message, noHash) - if err != nil { - t.Fatalf("error from Sign(): %s", err) - } - - if !Verify(public, message, signature) { - t.Errorf("Verify failed on signature from Sign()") - } -} - -func TestGolden(t *testing.T) { - // sign.input.gz is a selection of test cases from - // https://ed25519.cr.yp.to/python/sign.input - testDataZ, err := os.Open("testdata/sign.input.gz") - if err != nil { - t.Fatal(err) - } - defer testDataZ.Close() - testData, err := gzip.NewReader(testDataZ) - if err != nil { - t.Fatal(err) - } - defer testData.Close() - - scanner := bufio.NewScanner(testData) - lineNo := 0 - - for scanner.Scan() { - lineNo++ - - line := scanner.Text() - parts := strings.Split(line, ":") - if len(parts) != 5 { - t.Fatalf("bad number of parts on line %d", lineNo) - } - - privBytes, _ := hex.DecodeString(parts[0]) - pubKey, _ := hex.DecodeString(parts[1]) - msg, _ := hex.DecodeString(parts[2]) - sig, _ := hex.DecodeString(parts[3]) - // The signatures in the test vectors also include the message - // at the end, but we just want R and S. - sig = sig[:SignatureSize] - - if l := len(pubKey); l != PublicKeySize { - t.Fatalf("bad public key length on line %d: got %d bytes", lineNo, l) - } - - var priv [PrivateKeySize]byte - copy(priv[:], privBytes) - copy(priv[32:], pubKey) - - sig2 := Sign(priv[:], msg) - if !bytes.Equal(sig, sig2[:]) { - t.Errorf("different signature result on line %d: %x vs %x", lineNo, sig, sig2) - } - - if !Verify(pubKey, msg, sig2) { - t.Errorf("signature failed to verify on line %d", lineNo) - } - } - - if err := scanner.Err(); err != nil { - t.Fatalf("error reading test data: %s", err) - } -} - -func BenchmarkKeyGeneration(b *testing.B) { - var zero zeroReader - for i := 0; i < b.N; i++ { - if _, _, err := GenerateKey(zero); err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkSigning(b *testing.B) { - var zero zeroReader - _, priv, err := GenerateKey(zero) - if err != nil { - b.Fatal(err) - } - message := []byte("Hello, world!") - b.ResetTimer() - for i := 0; i < b.N; i++ { - Sign(priv, message) - } -} - -func BenchmarkVerification(b *testing.B) { - var zero zeroReader - pub, priv, err := GenerateKey(zero) - if err != nil { - b.Fatal(err) - } - message := []byte("Hello, world!") - signature := Sign(priv, message) - b.ResetTimer() - for i := 0; i < b.N; i++ { - Verify(pub, message, signature) - } -} diff --git a/vendor/golang.org/x/crypto/ssh/BUILD b/vendor/golang.org/x/crypto/ssh/BUILD index bd8030e57f77..2780d2f78e3e 100644 --- a/vendor/golang.org/x/crypto/ssh/BUILD +++ b/vendor/golang.org/x/crypto/ssh/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -32,45 +32,6 @@ go_library( ], ) -go_test( - name = "go_default_test", - srcs = [ - "benchmark_test.go", - "buffer_test.go", - "certs_test.go", - "cipher_test.go", - "client_auth_test.go", - "client_test.go", - "handshake_test.go", - "kex_test.go", - "keys_test.go", - "mempipe_test.go", - "messages_test.go", - "mux_test.go", - "session_test.go", - "tcpip_test.go", - "testdata_test.go", - "transport_test.go", - ], - importpath = "golang.org/x/crypto/ssh", - library = ":go_default_library", - deps = [ - "//vendor/golang.org/x/crypto/ed25519:go_default_library", - "//vendor/golang.org/x/crypto/ssh/terminal:go_default_library", - "//vendor/golang.org/x/crypto/ssh/testdata:go_default_library", - ], -) - -go_test( - name = "go_default_xtest", - srcs = ["example_test.go"], - importpath = "golang.org/x/crypto/ssh_test", - deps = [ - ":go_default_library", - "//vendor/golang.org/x/crypto/ssh/terminal:go_default_library", - ], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/golang.org/x/crypto/ssh/benchmark_test.go b/vendor/golang.org/x/crypto/ssh/benchmark_test.go deleted file mode 100644 index d9f7eb9b60ac..000000000000 --- a/vendor/golang.org/x/crypto/ssh/benchmark_test.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -import ( - "errors" - "io" - "net" - "testing" -) - -type server struct { - *ServerConn - chans <-chan NewChannel -} - -func newServer(c net.Conn, conf *ServerConfig) (*server, error) { - sconn, chans, reqs, err := NewServerConn(c, conf) - if err != nil { - return nil, err - } - go DiscardRequests(reqs) - return &server{sconn, chans}, nil -} - -func (s *server) Accept() (NewChannel, error) { - n, ok := <-s.chans - if !ok { - return nil, io.EOF - } - return n, nil -} - -func sshPipe() (Conn, *server, error) { - c1, c2, err := netPipe() - if err != nil { - return nil, nil, err - } - - clientConf := ClientConfig{ - User: "user", - } - serverConf := ServerConfig{ - NoClientAuth: true, - } - serverConf.AddHostKey(testSigners["ecdsa"]) - done := make(chan *server, 1) - go func() { - server, err := newServer(c2, &serverConf) - if err != nil { - done <- nil - } - done <- server - }() - - client, _, reqs, err := NewClientConn(c1, "", &clientConf) - if err != nil { - return nil, nil, err - } - - server := <-done - if server == nil { - return nil, nil, errors.New("server handshake failed.") - } - go DiscardRequests(reqs) - - return client, server, nil -} - -func BenchmarkEndToEnd(b *testing.B) { - b.StopTimer() - - client, server, err := sshPipe() - if err != nil { - b.Fatalf("sshPipe: %v", err) - } - - defer client.Close() - defer server.Close() - - size := (1 << 20) - input := make([]byte, size) - output := make([]byte, size) - b.SetBytes(int64(size)) - done := make(chan int, 1) - - go func() { - newCh, err := server.Accept() - if err != nil { - b.Fatalf("Client: %v", err) - } - ch, incoming, err := newCh.Accept() - go DiscardRequests(incoming) - for i := 0; i < b.N; i++ { - if _, err := io.ReadFull(ch, output); err != nil { - b.Fatalf("ReadFull: %v", err) - } - } - ch.Close() - done <- 1 - }() - - ch, in, err := client.OpenChannel("speed", nil) - if err != nil { - b.Fatalf("OpenChannel: %v", err) - } - go DiscardRequests(in) - - b.ResetTimer() - b.StartTimer() - for i := 0; i < b.N; i++ { - if _, err := ch.Write(input); err != nil { - b.Fatalf("WriteFull: %v", err) - } - } - ch.Close() - b.StopTimer() - - <-done -} diff --git a/vendor/golang.org/x/crypto/ssh/buffer_test.go b/vendor/golang.org/x/crypto/ssh/buffer_test.go deleted file mode 100644 index d5781cb3da99..000000000000 --- a/vendor/golang.org/x/crypto/ssh/buffer_test.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -import ( - "io" - "testing" -) - -var alphabet = []byte("abcdefghijklmnopqrstuvwxyz") - -func TestBufferReadwrite(t *testing.T) { - b := newBuffer() - b.write(alphabet[:10]) - r, _ := b.Read(make([]byte, 10)) - if r != 10 { - t.Fatalf("Expected written == read == 10, written: 10, read %d", r) - } - - b = newBuffer() - b.write(alphabet[:5]) - r, _ = b.Read(make([]byte, 10)) - if r != 5 { - t.Fatalf("Expected written == read == 5, written: 5, read %d", r) - } - - b = newBuffer() - b.write(alphabet[:10]) - r, _ = b.Read(make([]byte, 5)) - if r != 5 { - t.Fatalf("Expected written == 10, read == 5, written: 10, read %d", r) - } - - b = newBuffer() - b.write(alphabet[:5]) - b.write(alphabet[5:15]) - r, _ = b.Read(make([]byte, 10)) - r2, _ := b.Read(make([]byte, 10)) - if r != 10 || r2 != 5 || 15 != r+r2 { - t.Fatal("Expected written == read == 15") - } -} - -func TestBufferClose(t *testing.T) { - b := newBuffer() - b.write(alphabet[:10]) - b.eof() - _, err := b.Read(make([]byte, 5)) - if err != nil { - t.Fatal("expected read of 5 to not return EOF") - } - b = newBuffer() - b.write(alphabet[:10]) - b.eof() - r, err := b.Read(make([]byte, 5)) - r2, err2 := b.Read(make([]byte, 10)) - if r != 5 || r2 != 5 || err != nil || err2 != nil { - t.Fatal("expected reads of 5 and 5") - } - - b = newBuffer() - b.write(alphabet[:10]) - b.eof() - r, err = b.Read(make([]byte, 5)) - r2, err2 = b.Read(make([]byte, 10)) - r3, err3 := b.Read(make([]byte, 10)) - if r != 5 || r2 != 5 || r3 != 0 || err != nil || err2 != nil || err3 != io.EOF { - t.Fatal("expected reads of 5 and 5 and 0, with EOF") - } - - b = newBuffer() - b.write(make([]byte, 5)) - b.write(make([]byte, 10)) - b.eof() - r, err = b.Read(make([]byte, 9)) - r2, err2 = b.Read(make([]byte, 3)) - r3, err3 = b.Read(make([]byte, 3)) - r4, err4 := b.Read(make([]byte, 10)) - if err != nil || err2 != nil || err3 != nil || err4 != io.EOF { - t.Fatalf("Expected EOF on forth read only, err=%v, err2=%v, err3=%v, err4=%v", err, err2, err3, err4) - } - if r != 9 || r2 != 3 || r3 != 3 || r4 != 0 { - t.Fatal("Expected written == read == 15", r, r2, r3, r4) - } -} diff --git a/vendor/golang.org/x/crypto/ssh/certs_test.go b/vendor/golang.org/x/crypto/ssh/certs_test.go deleted file mode 100644 index 0200531f4c7d..000000000000 --- a/vendor/golang.org/x/crypto/ssh/certs_test.go +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -import ( - "bytes" - "crypto/rand" - "reflect" - "testing" - "time" -) - -// Cert generated by ssh-keygen 6.0p1 Debian-4. -// % ssh-keygen -s ca-key -I test user-key -const exampleSSHCert = `ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAgb1srW/W3ZDjYAO45xLYAwzHBDLsJ4Ux6ICFIkTjb1LEAAAADAQABAAAAYQCkoR51poH0wE8w72cqSB8Sszx+vAhzcMdCO0wqHTj7UNENHWEXGrU0E0UQekD7U+yhkhtoyjbPOVIP7hNa6aRk/ezdh/iUnCIt4Jt1v3Z1h1P+hA4QuYFMHNB+rmjPwAcAAAAAAAAAAAAAAAEAAAAEdGVzdAAAAAAAAAAAAAAAAP//////////AAAAAAAAAIIAAAAVcGVybWl0LVgxMS1mb3J3YXJkaW5nAAAAAAAAABdwZXJtaXQtYWdlbnQtZm9yd2FyZGluZwAAAAAAAAAWcGVybWl0LXBvcnQtZm9yd2FyZGluZwAAAAAAAAAKcGVybWl0LXB0eQAAAAAAAAAOcGVybWl0LXVzZXItcmMAAAAAAAAAAAAAAHcAAAAHc3NoLXJzYQAAAAMBAAEAAABhANFS2kaktpSGc+CcmEKPyw9mJC4nZKxHKTgLVZeaGbFZOvJTNzBspQHdy7Q1uKSfktxpgjZnksiu/tFF9ngyY2KFoc+U88ya95IZUycBGCUbBQ8+bhDtw/icdDGQD5WnUwAAAG8AAAAHc3NoLXJzYQAAAGC8Y9Z2LQKhIhxf52773XaWrXdxP0t3GBVo4A10vUWiYoAGepr6rQIoGGXFxT4B9Gp+nEBJjOwKDXPrAevow0T9ca8gZN+0ykbhSrXLE5Ao48rqr3zP4O1/9P7e6gp0gw8=` - -func TestParseCert(t *testing.T) { - authKeyBytes := []byte(exampleSSHCert) - - key, _, _, rest, err := ParseAuthorizedKey(authKeyBytes) - if err != nil { - t.Fatalf("ParseAuthorizedKey: %v", err) - } - if len(rest) > 0 { - t.Errorf("rest: got %q, want empty", rest) - } - - if _, ok := key.(*Certificate); !ok { - t.Fatalf("got %v (%T), want *Certificate", key, key) - } - - marshaled := MarshalAuthorizedKey(key) - // Before comparison, remove the trailing newline that - // MarshalAuthorizedKey adds. - marshaled = marshaled[:len(marshaled)-1] - if !bytes.Equal(authKeyBytes, marshaled) { - t.Errorf("marshaled certificate does not match original: got %q, want %q", marshaled, authKeyBytes) - } -} - -// Cert generated by ssh-keygen OpenSSH_6.8p1 OS X 10.10.3 -// % ssh-keygen -s ca -I testcert -O source-address=192.168.1.0/24 -O force-command=/bin/sleep user.pub -// user.pub key: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDACh1rt2DXfV3hk6fszSQcQ/rueMId0kVD9U7nl8cfEnFxqOCrNT92g4laQIGl2mn8lsGZfTLg8ksHq3gkvgO3oo/0wHy4v32JeBOHTsN5AL4gfHNEhWeWb50ev47hnTsRIt9P4dxogeUo/hTu7j9+s9lLpEQXCvq6xocXQt0j8MV9qZBBXFLXVT3cWIkSqOdwt/5ZBg+1GSrc7WfCXVWgTk4a20uPMuJPxU4RQwZW6X3+O8Pqo8C3cW0OzZRFP6gUYUKUsTI5WntlS+LAxgw1mZNsozFGdbiOPRnEryE3SRldh9vjDR3tin1fGpA5P7+CEB/bqaXtG3V+F2OkqaMN -// Critical Options: -// force-command /bin/sleep -// source-address 192.168.1.0/24 -// Extensions: -// permit-X11-forwarding -// permit-agent-forwarding -// permit-port-forwarding -// permit-pty -// permit-user-rc -const exampleSSHCertWithOptions = `ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAgDyysCJY0XrO1n03EeRRoITnTPdjENFmWDs9X58PP3VUAAAADAQABAAABAQDACh1rt2DXfV3hk6fszSQcQ/rueMId0kVD9U7nl8cfEnFxqOCrNT92g4laQIGl2mn8lsGZfTLg8ksHq3gkvgO3oo/0wHy4v32JeBOHTsN5AL4gfHNEhWeWb50ev47hnTsRIt9P4dxogeUo/hTu7j9+s9lLpEQXCvq6xocXQt0j8MV9qZBBXFLXVT3cWIkSqOdwt/5ZBg+1GSrc7WfCXVWgTk4a20uPMuJPxU4RQwZW6X3+O8Pqo8C3cW0OzZRFP6gUYUKUsTI5WntlS+LAxgw1mZNsozFGdbiOPRnEryE3SRldh9vjDR3tin1fGpA5P7+CEB/bqaXtG3V+F2OkqaMNAAAAAAAAAAAAAAABAAAACHRlc3RjZXJ0AAAAAAAAAAAAAAAA//////////8AAABLAAAADWZvcmNlLWNvbW1hbmQAAAAOAAAACi9iaW4vc2xlZXAAAAAOc291cmNlLWFkZHJlc3MAAAASAAAADjE5Mi4xNjguMS4wLzI0AAAAggAAABVwZXJtaXQtWDExLWZvcndhcmRpbmcAAAAAAAAAF3Blcm1pdC1hZ2VudC1mb3J3YXJkaW5nAAAAAAAAABZwZXJtaXQtcG9ydC1mb3J3YXJkaW5nAAAAAAAAAApwZXJtaXQtcHR5AAAAAAAAAA5wZXJtaXQtdXNlci1yYwAAAAAAAAAAAAABFwAAAAdzc2gtcnNhAAAAAwEAAQAAAQEAwU+c5ui5A8+J/CFpjW8wCa52bEODA808WWQDCSuTG/eMXNf59v9Y8Pk0F1E9dGCosSNyVcB/hacUrc6He+i97+HJCyKavBsE6GDxrjRyxYqAlfcOXi/IVmaUGiO8OQ39d4GHrjToInKvExSUeleQyH4Y4/e27T/pILAqPFL3fyrvMLT5qU9QyIt6zIpa7GBP5+urouNavMprV3zsfIqNBbWypinOQAw823a5wN+zwXnhZrgQiHZ/USG09Y6k98y1dTVz8YHlQVR4D3lpTAsKDKJ5hCH9WU4fdf+lU8OyNGaJ/vz0XNqxcToe1l4numLTnaoSuH89pHryjqurB7lJKwAAAQ8AAAAHc3NoLXJzYQAAAQCaHvUIoPL1zWUHIXLvu96/HU1s/i4CAW2IIEuGgxCUCiFj6vyTyYtgxQxcmbfZf6eaITlS6XJZa7Qq4iaFZh75C1DXTX8labXhRSD4E2t//AIP9MC1rtQC5xo6FmbQ+BoKcDskr+mNACcbRSxs3IL3bwCfWDnIw2WbVox9ZdcthJKk4UoCW4ix4QwdHw7zlddlz++fGEEVhmTbll1SUkycGApPFBsAYRTMupUJcYPIeReBI/m8XfkoMk99bV8ZJQTAd7OekHY2/48Ff53jLmyDjP7kNw1F8OaPtkFs6dGJXta4krmaekPy87j+35In5hFj7yoOqvSbmYUkeX70/GGQ` - -func TestParseCertWithOptions(t *testing.T) { - opts := map[string]string{ - "source-address": "192.168.1.0/24", - "force-command": "/bin/sleep", - } - exts := map[string]string{ - "permit-X11-forwarding": "", - "permit-agent-forwarding": "", - "permit-port-forwarding": "", - "permit-pty": "", - "permit-user-rc": "", - } - authKeyBytes := []byte(exampleSSHCertWithOptions) - - key, _, _, rest, err := ParseAuthorizedKey(authKeyBytes) - if err != nil { - t.Fatalf("ParseAuthorizedKey: %v", err) - } - if len(rest) > 0 { - t.Errorf("rest: got %q, want empty", rest) - } - cert, ok := key.(*Certificate) - if !ok { - t.Fatalf("got %v (%T), want *Certificate", key, key) - } - if !reflect.DeepEqual(cert.CriticalOptions, opts) { - t.Errorf("unexpected critical options - got %v, want %v", cert.CriticalOptions, opts) - } - if !reflect.DeepEqual(cert.Extensions, exts) { - t.Errorf("unexpected Extensions - got %v, want %v", cert.Extensions, exts) - } - marshaled := MarshalAuthorizedKey(key) - // Before comparison, remove the trailing newline that - // MarshalAuthorizedKey adds. - marshaled = marshaled[:len(marshaled)-1] - if !bytes.Equal(authKeyBytes, marshaled) { - t.Errorf("marshaled certificate does not match original: got %q, want %q", marshaled, authKeyBytes) - } -} - -func TestValidateCert(t *testing.T) { - key, _, _, _, err := ParseAuthorizedKey([]byte(exampleSSHCert)) - if err != nil { - t.Fatalf("ParseAuthorizedKey: %v", err) - } - validCert, ok := key.(*Certificate) - if !ok { - t.Fatalf("got %v (%T), want *Certificate", key, key) - } - checker := CertChecker{} - checker.IsUserAuthority = func(k PublicKey) bool { - return bytes.Equal(k.Marshal(), validCert.SignatureKey.Marshal()) - } - - if err := checker.CheckCert("user", validCert); err != nil { - t.Errorf("Unable to validate certificate: %v", err) - } - invalidCert := &Certificate{ - Key: testPublicKeys["rsa"], - SignatureKey: testPublicKeys["ecdsa"], - ValidBefore: CertTimeInfinity, - Signature: &Signature{}, - } - if err := checker.CheckCert("user", invalidCert); err == nil { - t.Error("Invalid cert signature passed validation") - } -} - -func TestValidateCertTime(t *testing.T) { - cert := Certificate{ - ValidPrincipals: []string{"user"}, - Key: testPublicKeys["rsa"], - ValidAfter: 50, - ValidBefore: 100, - } - - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - - for ts, ok := range map[int64]bool{ - 25: false, - 50: true, - 99: true, - 100: false, - 125: false, - } { - checker := CertChecker{ - Clock: func() time.Time { return time.Unix(ts, 0) }, - } - checker.IsUserAuthority = func(k PublicKey) bool { - return bytes.Equal(k.Marshal(), - testPublicKeys["ecdsa"].Marshal()) - } - - if v := checker.CheckCert("user", &cert); (v == nil) != ok { - t.Errorf("Authenticate(%d): %v", ts, v) - } - } -} - -// TODO(hanwen): tests for -// -// host keys: -// * fallbacks - -func TestHostKeyCert(t *testing.T) { - cert := &Certificate{ - ValidPrincipals: []string{"hostname", "hostname.domain", "otherhost"}, - Key: testPublicKeys["rsa"], - ValidBefore: CertTimeInfinity, - CertType: HostCert, - } - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - - checker := &CertChecker{ - IsHostAuthority: func(p PublicKey, addr string) bool { - return addr == "hostname:22" && bytes.Equal(testPublicKeys["ecdsa"].Marshal(), p.Marshal()) - }, - } - - certSigner, err := NewCertSigner(cert, testSigners["rsa"]) - if err != nil { - t.Errorf("NewCertSigner: %v", err) - } - - for _, test := range []struct { - addr string - succeed bool - }{ - {addr: "hostname:22", succeed: true}, - {addr: "otherhost:22", succeed: false}, // The certificate is valid for 'otherhost' as hostname, but we only recognize the authority of the signer for the address 'hostname:22' - {addr: "lasthost:22", succeed: false}, - } { - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - errc := make(chan error) - - go func() { - conf := ServerConfig{ - NoClientAuth: true, - } - conf.AddHostKey(certSigner) - _, _, _, err := NewServerConn(c1, &conf) - errc <- err - }() - - config := &ClientConfig{ - User: "user", - HostKeyCallback: checker.CheckHostKey, - } - _, _, _, err = NewClientConn(c2, test.addr, config) - - if (err == nil) != test.succeed { - t.Fatalf("NewClientConn(%q): %v", test.addr, err) - } - - err = <-errc - if (err == nil) != test.succeed { - t.Fatalf("NewServerConn(%q): %v", test.addr, err) - } - } -} diff --git a/vendor/golang.org/x/crypto/ssh/cipher_test.go b/vendor/golang.org/x/crypto/ssh/cipher_test.go deleted file mode 100644 index 5cfa17a62de5..000000000000 --- a/vendor/golang.org/x/crypto/ssh/cipher_test.go +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -import ( - "bytes" - "crypto" - "crypto/aes" - "crypto/rand" - "testing" -) - -func TestDefaultCiphersExist(t *testing.T) { - for _, cipherAlgo := range supportedCiphers { - if _, ok := cipherModes[cipherAlgo]; !ok { - t.Errorf("default cipher %q is unknown", cipherAlgo) - } - } -} - -func TestPacketCiphers(t *testing.T) { - // Still test aes128cbc cipher although it's commented out. - cipherModes[aes128cbcID] = &streamCipherMode{16, aes.BlockSize, 0, nil} - defer delete(cipherModes, aes128cbcID) - - for cipher := range cipherModes { - for mac := range macModes { - kr := &kexResult{Hash: crypto.SHA1} - algs := directionAlgorithms{ - Cipher: cipher, - MAC: mac, - Compression: "none", - } - client, err := newPacketCipher(clientKeys, algs, kr) - if err != nil { - t.Errorf("newPacketCipher(client, %q, %q): %v", cipher, mac, err) - continue - } - server, err := newPacketCipher(clientKeys, algs, kr) - if err != nil { - t.Errorf("newPacketCipher(client, %q, %q): %v", cipher, mac, err) - continue - } - - want := "bla bla" - input := []byte(want) - buf := &bytes.Buffer{} - if err := client.writePacket(0, buf, rand.Reader, input); err != nil { - t.Errorf("writePacket(%q, %q): %v", cipher, mac, err) - continue - } - - packet, err := server.readPacket(0, buf) - if err != nil { - t.Errorf("readPacket(%q, %q): %v", cipher, mac, err) - continue - } - - if string(packet) != want { - t.Errorf("roundtrip(%q, %q): got %q, want %q", cipher, mac, packet, want) - } - } - } -} - -func TestCBCOracleCounterMeasure(t *testing.T) { - cipherModes[aes128cbcID] = &streamCipherMode{16, aes.BlockSize, 0, nil} - defer delete(cipherModes, aes128cbcID) - - kr := &kexResult{Hash: crypto.SHA1} - algs := directionAlgorithms{ - Cipher: aes128cbcID, - MAC: "hmac-sha1", - Compression: "none", - } - client, err := newPacketCipher(clientKeys, algs, kr) - if err != nil { - t.Fatalf("newPacketCipher(client): %v", err) - } - - want := "bla bla" - input := []byte(want) - buf := &bytes.Buffer{} - if err := client.writePacket(0, buf, rand.Reader, input); err != nil { - t.Errorf("writePacket: %v", err) - } - - packetSize := buf.Len() - buf.Write(make([]byte, 2*maxPacket)) - - // We corrupt each byte, but this usually will only test the - // 'packet too large' or 'MAC failure' cases. - lastRead := -1 - for i := 0; i < packetSize; i++ { - server, err := newPacketCipher(clientKeys, algs, kr) - if err != nil { - t.Fatalf("newPacketCipher(client): %v", err) - } - - fresh := &bytes.Buffer{} - fresh.Write(buf.Bytes()) - fresh.Bytes()[i] ^= 0x01 - - before := fresh.Len() - _, err = server.readPacket(0, fresh) - if err == nil { - t.Errorf("corrupt byte %d: readPacket succeeded ", i) - continue - } - if _, ok := err.(cbcError); !ok { - t.Errorf("corrupt byte %d: got %v (%T), want cbcError", i, err, err) - continue - } - - after := fresh.Len() - bytesRead := before - after - if bytesRead < maxPacket { - t.Errorf("corrupt byte %d: read %d bytes, want more than %d", i, bytesRead, maxPacket) - continue - } - - if i > 0 && bytesRead != lastRead { - t.Errorf("corrupt byte %d: read %d bytes, want %d bytes read", i, bytesRead, lastRead) - } - lastRead = bytesRead - } -} diff --git a/vendor/golang.org/x/crypto/ssh/client_auth_test.go b/vendor/golang.org/x/crypto/ssh/client_auth_test.go deleted file mode 100644 index 145b57a2bb70..000000000000 --- a/vendor/golang.org/x/crypto/ssh/client_auth_test.go +++ /dev/null @@ -1,628 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -import ( - "bytes" - "crypto/rand" - "errors" - "fmt" - "os" - "strings" - "testing" -) - -type keyboardInteractive map[string]string - -func (cr keyboardInteractive) Challenge(user string, instruction string, questions []string, echos []bool) ([]string, error) { - var answers []string - for _, q := range questions { - answers = append(answers, cr[q]) - } - return answers, nil -} - -// reused internally by tests -var clientPassword = "tiger" - -// tryAuth runs a handshake with a given config against an SSH server -// with config serverConfig -func tryAuth(t *testing.T, config *ClientConfig) error { - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - certChecker := CertChecker{ - IsUserAuthority: func(k PublicKey) bool { - return bytes.Equal(k.Marshal(), testPublicKeys["ecdsa"].Marshal()) - }, - UserKeyFallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) { - if conn.User() == "testuser" && bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) { - return nil, nil - } - - return nil, fmt.Errorf("pubkey for %q not acceptable", conn.User()) - }, - IsRevoked: func(c *Certificate) bool { - return c.Serial == 666 - }, - } - - serverConfig := &ServerConfig{ - PasswordCallback: func(conn ConnMetadata, pass []byte) (*Permissions, error) { - if conn.User() == "testuser" && string(pass) == clientPassword { - return nil, nil - } - return nil, errors.New("password auth failed") - }, - PublicKeyCallback: certChecker.Authenticate, - KeyboardInteractiveCallback: func(conn ConnMetadata, challenge KeyboardInteractiveChallenge) (*Permissions, error) { - ans, err := challenge("user", - "instruction", - []string{"question1", "question2"}, - []bool{true, true}) - if err != nil { - return nil, err - } - ok := conn.User() == "testuser" && ans[0] == "answer1" && ans[1] == "answer2" - if ok { - challenge("user", "motd", nil, nil) - return nil, nil - } - return nil, errors.New("keyboard-interactive failed") - }, - } - serverConfig.AddHostKey(testSigners["rsa"]) - - go newServer(c1, serverConfig) - _, _, _, err = NewClientConn(c2, "", config) - return err -} - -func TestClientAuthPublicKey(t *testing.T) { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(testSigners["rsa"]), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - if err := tryAuth(t, config); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } -} - -func TestAuthMethodPassword(t *testing.T) { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - Password(clientPassword), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - - if err := tryAuth(t, config); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } -} - -func TestAuthMethodFallback(t *testing.T) { - var passwordCalled bool - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(testSigners["rsa"]), - PasswordCallback( - func() (string, error) { - passwordCalled = true - return "WRONG", nil - }), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - - if err := tryAuth(t, config); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } - - if passwordCalled { - t.Errorf("password auth tried before public-key auth.") - } -} - -func TestAuthMethodWrongPassword(t *testing.T) { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - Password("wrong"), - PublicKeys(testSigners["rsa"]), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - - if err := tryAuth(t, config); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } -} - -func TestAuthMethodKeyboardInteractive(t *testing.T) { - answers := keyboardInteractive(map[string]string{ - "question1": "answer1", - "question2": "answer2", - }) - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - KeyboardInteractive(answers.Challenge), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - - if err := tryAuth(t, config); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } -} - -func TestAuthMethodWrongKeyboardInteractive(t *testing.T) { - answers := keyboardInteractive(map[string]string{ - "question1": "answer1", - "question2": "WRONG", - }) - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - KeyboardInteractive(answers.Challenge), - }, - } - - if err := tryAuth(t, config); err == nil { - t.Fatalf("wrong answers should not have authenticated with KeyboardInteractive") - } -} - -// the mock server will only authenticate ssh-rsa keys -func TestAuthMethodInvalidPublicKey(t *testing.T) { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(testSigners["dsa"]), - }, - } - - if err := tryAuth(t, config); err == nil { - t.Fatalf("dsa private key should not have authenticated with rsa public key") - } -} - -// the client should authenticate with the second key -func TestAuthMethodRSAandDSA(t *testing.T) { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(testSigners["dsa"], testSigners["rsa"]), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - if err := tryAuth(t, config); err != nil { - t.Fatalf("client could not authenticate with rsa key: %v", err) - } -} - -func TestClientHMAC(t *testing.T) { - for _, mac := range supportedMACs { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(testSigners["rsa"]), - }, - Config: Config{ - MACs: []string{mac}, - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - if err := tryAuth(t, config); err != nil { - t.Fatalf("client could not authenticate with mac algo %s: %v", mac, err) - } - } -} - -// issue 4285. -func TestClientUnsupportedCipher(t *testing.T) { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(), - }, - Config: Config{ - Ciphers: []string{"aes128-cbc"}, // not currently supported - }, - } - if err := tryAuth(t, config); err == nil { - t.Errorf("expected no ciphers in common") - } -} - -func TestClientUnsupportedKex(t *testing.T) { - if os.Getenv("GO_BUILDER_NAME") != "" { - t.Skip("skipping known-flaky test on the Go build dashboard; see golang.org/issue/15198") - } - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(), - }, - Config: Config{ - KeyExchanges: []string{"diffie-hellman-group-exchange-sha256"}, // not currently supported - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - if err := tryAuth(t, config); err == nil || !strings.Contains(err.Error(), "common algorithm") { - t.Errorf("got %v, expected 'common algorithm'", err) - } -} - -func TestClientLoginCert(t *testing.T) { - cert := &Certificate{ - Key: testPublicKeys["rsa"], - ValidBefore: CertTimeInfinity, - CertType: UserCert, - } - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - certSigner, err := NewCertSigner(cert, testSigners["rsa"]) - if err != nil { - t.Fatalf("NewCertSigner: %v", err) - } - - clientConfig := &ClientConfig{ - User: "user", - HostKeyCallback: InsecureIgnoreHostKey(), - } - clientConfig.Auth = append(clientConfig.Auth, PublicKeys(certSigner)) - - // should succeed - if err := tryAuth(t, clientConfig); err != nil { - t.Errorf("cert login failed: %v", err) - } - - // corrupted signature - cert.Signature.Blob[0]++ - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("cert login passed with corrupted sig") - } - - // revoked - cert.Serial = 666 - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("revoked cert login succeeded") - } - cert.Serial = 1 - - // sign with wrong key - cert.SignCert(rand.Reader, testSigners["dsa"]) - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("cert login passed with non-authoritative key") - } - - // host cert - cert.CertType = HostCert - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("cert login passed with wrong type") - } - cert.CertType = UserCert - - // principal specified - cert.ValidPrincipals = []string{"user"} - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err != nil { - t.Errorf("cert login failed: %v", err) - } - - // wrong principal specified - cert.ValidPrincipals = []string{"fred"} - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("cert login passed with wrong principal") - } - cert.ValidPrincipals = nil - - // added critical option - cert.CriticalOptions = map[string]string{"root-access": "yes"} - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("cert login passed with unrecognized critical option") - } - - // allowed source address - cert.CriticalOptions = map[string]string{"source-address": "127.0.0.42/24,::42/120"} - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err != nil { - t.Errorf("cert login with source-address failed: %v", err) - } - - // disallowed source address - cert.CriticalOptions = map[string]string{"source-address": "127.0.0.42,::42"} - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("cert login with source-address succeeded") - } -} - -func testPermissionsPassing(withPermissions bool, t *testing.T) { - serverConfig := &ServerConfig{ - PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) { - if conn.User() == "nopermissions" { - return nil, nil - } - return &Permissions{}, nil - }, - } - serverConfig.AddHostKey(testSigners["rsa"]) - - clientConfig := &ClientConfig{ - Auth: []AuthMethod{ - PublicKeys(testSigners["rsa"]), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - if withPermissions { - clientConfig.User = "permissions" - } else { - clientConfig.User = "nopermissions" - } - - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - go NewClientConn(c2, "", clientConfig) - serverConn, err := newServer(c1, serverConfig) - if err != nil { - t.Fatal(err) - } - if p := serverConn.Permissions; (p != nil) != withPermissions { - t.Fatalf("withPermissions is %t, but Permissions object is %#v", withPermissions, p) - } -} - -func TestPermissionsPassing(t *testing.T) { - testPermissionsPassing(true, t) -} - -func TestNoPermissionsPassing(t *testing.T) { - testPermissionsPassing(false, t) -} - -func TestRetryableAuth(t *testing.T) { - n := 0 - passwords := []string{"WRONG1", "WRONG2"} - - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - RetryableAuthMethod(PasswordCallback(func() (string, error) { - p := passwords[n] - n++ - return p, nil - }), 2), - PublicKeys(testSigners["rsa"]), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - - if err := tryAuth(t, config); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } - if n != 2 { - t.Fatalf("Did not try all passwords") - } -} - -func ExampleRetryableAuthMethod(t *testing.T) { - user := "testuser" - NumberOfPrompts := 3 - - // Normally this would be a callback that prompts the user to answer the - // provided questions - Cb := func(user, instruction string, questions []string, echos []bool) (answers []string, err error) { - return []string{"answer1", "answer2"}, nil - } - - config := &ClientConfig{ - HostKeyCallback: InsecureIgnoreHostKey(), - User: user, - Auth: []AuthMethod{ - RetryableAuthMethod(KeyboardInteractiveChallenge(Cb), NumberOfPrompts), - }, - } - - if err := tryAuth(t, config); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } -} - -// Test if username is received on server side when NoClientAuth is used -func TestClientAuthNone(t *testing.T) { - user := "testuser" - serverConfig := &ServerConfig{ - NoClientAuth: true, - } - serverConfig.AddHostKey(testSigners["rsa"]) - - clientConfig := &ClientConfig{ - User: user, - HostKeyCallback: InsecureIgnoreHostKey(), - } - - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - go NewClientConn(c2, "", clientConfig) - serverConn, err := newServer(c1, serverConfig) - if err != nil { - t.Fatalf("newServer: %v", err) - } - if serverConn.User() != user { - t.Fatalf("server: got %q, want %q", serverConn.User(), user) - } -} - -// Test if authentication attempts are limited on server when MaxAuthTries is set -func TestClientAuthMaxAuthTries(t *testing.T) { - user := "testuser" - - serverConfig := &ServerConfig{ - MaxAuthTries: 2, - PasswordCallback: func(conn ConnMetadata, pass []byte) (*Permissions, error) { - if conn.User() == "testuser" && string(pass) == "right" { - return nil, nil - } - return nil, errors.New("password auth failed") - }, - } - serverConfig.AddHostKey(testSigners["rsa"]) - - expectedErr := fmt.Errorf("ssh: handshake failed: %v", &disconnectMsg{ - Reason: 2, - Message: "too many authentication failures", - }) - - for tries := 2; tries < 4; tries++ { - n := tries - clientConfig := &ClientConfig{ - User: user, - Auth: []AuthMethod{ - RetryableAuthMethod(PasswordCallback(func() (string, error) { - n-- - if n == 0 { - return "right", nil - } - return "wrong", nil - }), tries), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - go newServer(c1, serverConfig) - _, _, _, err = NewClientConn(c2, "", clientConfig) - if tries > 2 { - if err == nil { - t.Fatalf("client: got no error, want %s", expectedErr) - } else if err.Error() != expectedErr.Error() { - t.Fatalf("client: got %s, want %s", err, expectedErr) - } - } else { - if err != nil { - t.Fatalf("client: got %s, want no error", err) - } - } - } -} - -// Test if authentication attempts are correctly limited on server -// when more public keys are provided then MaxAuthTries -func TestClientAuthMaxAuthTriesPublicKey(t *testing.T) { - signers := []Signer{} - for i := 0; i < 6; i++ { - signers = append(signers, testSigners["dsa"]) - } - - validConfig := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(append([]Signer{testSigners["rsa"]}, signers...)...), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - if err := tryAuth(t, validConfig); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } - - expectedErr := fmt.Errorf("ssh: handshake failed: %v", &disconnectMsg{ - Reason: 2, - Message: "too many authentication failures", - }) - invalidConfig := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(append(signers, testSigners["rsa"])...), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - if err := tryAuth(t, invalidConfig); err == nil { - t.Fatalf("client: got no error, want %s", expectedErr) - } else if err.Error() != expectedErr.Error() { - t.Fatalf("client: got %s, want %s", err, expectedErr) - } -} - -// Test whether authentication errors are being properly logged if all -// authentication methods have been exhausted -func TestClientAuthErrorList(t *testing.T) { - publicKeyErr := errors.New("This is an error from PublicKeyCallback") - - clientConfig := &ClientConfig{ - Auth: []AuthMethod{ - PublicKeys(testSigners["rsa"]), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - serverConfig := &ServerConfig{ - PublicKeyCallback: func(_ ConnMetadata, _ PublicKey) (*Permissions, error) { - return nil, publicKeyErr - }, - } - serverConfig.AddHostKey(testSigners["rsa"]) - - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - go NewClientConn(c2, "", clientConfig) - _, err = newServer(c1, serverConfig) - if err == nil { - t.Fatal("newServer: got nil, expected errors") - } - - authErrs, ok := err.(*ServerAuthError) - if !ok { - t.Fatalf("errors: got %T, want *ssh.ServerAuthError", err) - } - for i, e := range authErrs.Errors { - switch i { - case 0: - if e.Error() != "no auth passed yet" { - t.Fatalf("errors: got %v, want no auth passed yet", e.Error()) - } - case 1: - if e != publicKeyErr { - t.Fatalf("errors: got %v, want %v", e, publicKeyErr) - } - default: - t.Fatalf("errors: got %v, expected 2 errors", authErrs.Errors) - } - } -} diff --git a/vendor/golang.org/x/crypto/ssh/client_test.go b/vendor/golang.org/x/crypto/ssh/client_test.go deleted file mode 100644 index ccf56074d724..000000000000 --- a/vendor/golang.org/x/crypto/ssh/client_test.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -import ( - "net" - "strings" - "testing" -) - -func testClientVersion(t *testing.T, config *ClientConfig, expected string) { - clientConn, serverConn := net.Pipe() - defer clientConn.Close() - receivedVersion := make(chan string, 1) - config.HostKeyCallback = InsecureIgnoreHostKey() - go func() { - version, err := readVersion(serverConn) - if err != nil { - receivedVersion <- "" - } else { - receivedVersion <- string(version) - } - serverConn.Close() - }() - NewClientConn(clientConn, "", config) - actual := <-receivedVersion - if actual != expected { - t.Fatalf("got %s; want %s", actual, expected) - } -} - -func TestCustomClientVersion(t *testing.T) { - version := "Test-Client-Version-0.0" - testClientVersion(t, &ClientConfig{ClientVersion: version}, version) -} - -func TestDefaultClientVersion(t *testing.T) { - testClientVersion(t, &ClientConfig{}, packageVersion) -} - -func TestHostKeyCheck(t *testing.T) { - for _, tt := range []struct { - name string - wantError string - key PublicKey - }{ - {"no callback", "must specify HostKeyCallback", nil}, - {"correct key", "", testSigners["rsa"].PublicKey()}, - {"mismatch", "mismatch", testSigners["ecdsa"].PublicKey()}, - } { - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - serverConf := &ServerConfig{ - NoClientAuth: true, - } - serverConf.AddHostKey(testSigners["rsa"]) - - go NewServerConn(c1, serverConf) - clientConf := ClientConfig{ - User: "user", - } - if tt.key != nil { - clientConf.HostKeyCallback = FixedHostKey(tt.key) - } - - _, _, _, err = NewClientConn(c2, "", &clientConf) - if err != nil { - if tt.wantError == "" || !strings.Contains(err.Error(), tt.wantError) { - t.Errorf("%s: got error %q, missing %q", tt.name, err.Error(), tt.wantError) - } - } else if tt.wantError != "" { - t.Errorf("%s: succeeded, but want error string %q", tt.name, tt.wantError) - } - } -} diff --git a/vendor/golang.org/x/crypto/ssh/example_test.go b/vendor/golang.org/x/crypto/ssh/example_test.go deleted file mode 100644 index b910c7bf60ba..000000000000 --- a/vendor/golang.org/x/crypto/ssh/example_test.go +++ /dev/null @@ -1,320 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh_test - -import ( - "bufio" - "bytes" - "fmt" - "io/ioutil" - "log" - "net" - "net/http" - "os" - "path/filepath" - "strings" - - "golang.org/x/crypto/ssh" - "golang.org/x/crypto/ssh/terminal" -) - -func ExampleNewServerConn() { - // Public key authentication is done by comparing - // the public key of a received connection - // with the entries in the authorized_keys file. - authorizedKeysBytes, err := ioutil.ReadFile("authorized_keys") - if err != nil { - log.Fatalf("Failed to load authorized_keys, err: %v", err) - } - - authorizedKeysMap := map[string]bool{} - for len(authorizedKeysBytes) > 0 { - pubKey, _, _, rest, err := ssh.ParseAuthorizedKey(authorizedKeysBytes) - if err != nil { - log.Fatal(err) - } - - authorizedKeysMap[string(pubKey.Marshal())] = true - authorizedKeysBytes = rest - } - - // An SSH server is represented by a ServerConfig, which holds - // certificate details and handles authentication of ServerConns. - config := &ssh.ServerConfig{ - // Remove to disable password auth. - PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) { - // Should use constant-time compare (or better, salt+hash) in - // a production setting. - if c.User() == "testuser" && string(pass) == "tiger" { - return nil, nil - } - return nil, fmt.Errorf("password rejected for %q", c.User()) - }, - - // Remove to disable public key auth. - PublicKeyCallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) { - if authorizedKeysMap[string(pubKey.Marshal())] { - return &ssh.Permissions{ - // Record the public key used for authentication. - Extensions: map[string]string{ - "pubkey-fp": ssh.FingerprintSHA256(pubKey), - }, - }, nil - } - return nil, fmt.Errorf("unknown public key for %q", c.User()) - }, - } - - privateBytes, err := ioutil.ReadFile("id_rsa") - if err != nil { - log.Fatal("Failed to load private key: ", err) - } - - private, err := ssh.ParsePrivateKey(privateBytes) - if err != nil { - log.Fatal("Failed to parse private key: ", err) - } - - config.AddHostKey(private) - - // Once a ServerConfig has been configured, connections can be - // accepted. - listener, err := net.Listen("tcp", "0.0.0.0:2022") - if err != nil { - log.Fatal("failed to listen for connection: ", err) - } - nConn, err := listener.Accept() - if err != nil { - log.Fatal("failed to accept incoming connection: ", err) - } - - // Before use, a handshake must be performed on the incoming - // net.Conn. - conn, chans, reqs, err := ssh.NewServerConn(nConn, config) - if err != nil { - log.Fatal("failed to handshake: ", err) - } - log.Printf("logged in with key %s", conn.Permissions.Extensions["pubkey-fp"]) - - // The incoming Request channel must be serviced. - go ssh.DiscardRequests(reqs) - - // Service the incoming Channel channel. - for newChannel := range chans { - // Channels have a type, depending on the application level - // protocol intended. In the case of a shell, the type is - // "session" and ServerShell may be used to present a simple - // terminal interface. - if newChannel.ChannelType() != "session" { - newChannel.Reject(ssh.UnknownChannelType, "unknown channel type") - continue - } - channel, requests, err := newChannel.Accept() - if err != nil { - log.Fatalf("Could not accept channel: %v", err) - } - - // Sessions have out-of-band requests such as "shell", - // "pty-req" and "env". Here we handle only the - // "shell" request. - go func(in <-chan *ssh.Request) { - for req := range in { - req.Reply(req.Type == "shell", nil) - } - }(requests) - - term := terminal.NewTerminal(channel, "> ") - - go func() { - defer channel.Close() - for { - line, err := term.ReadLine() - if err != nil { - break - } - fmt.Println(line) - } - }() - } -} - -func ExampleHostKeyCheck() { - // Every client must provide a host key check. Here is a - // simple-minded parse of OpenSSH's known_hosts file - host := "hostname" - file, err := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts")) - if err != nil { - log.Fatal(err) - } - defer file.Close() - - scanner := bufio.NewScanner(file) - var hostKey ssh.PublicKey - for scanner.Scan() { - fields := strings.Split(scanner.Text(), " ") - if len(fields) != 3 { - continue - } - if strings.Contains(fields[0], host) { - var err error - hostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes()) - if err != nil { - log.Fatalf("error parsing %q: %v", fields[2], err) - } - break - } - } - - if hostKey == nil { - log.Fatalf("no hostkey for %s", host) - } - - config := ssh.ClientConfig{ - User: os.Getenv("USER"), - HostKeyCallback: ssh.FixedHostKey(hostKey), - } - - _, err = ssh.Dial("tcp", host+":22", &config) - log.Println(err) -} - -func ExampleDial() { - var hostKey ssh.PublicKey - // An SSH client is represented with a ClientConn. - // - // To authenticate with the remote server you must pass at least one - // implementation of AuthMethod via the Auth field in ClientConfig, - // and provide a HostKeyCallback. - config := &ssh.ClientConfig{ - User: "username", - Auth: []ssh.AuthMethod{ - ssh.Password("yourpassword"), - }, - HostKeyCallback: ssh.FixedHostKey(hostKey), - } - client, err := ssh.Dial("tcp", "yourserver.com:22", config) - if err != nil { - log.Fatal("Failed to dial: ", err) - } - - // Each ClientConn can support multiple interactive sessions, - // represented by a Session. - session, err := client.NewSession() - if err != nil { - log.Fatal("Failed to create session: ", err) - } - defer session.Close() - - // Once a Session is created, you can execute a single command on - // the remote side using the Run method. - var b bytes.Buffer - session.Stdout = &b - if err := session.Run("/usr/bin/whoami"); err != nil { - log.Fatal("Failed to run: " + err.Error()) - } - fmt.Println(b.String()) -} - -func ExamplePublicKeys() { - var hostKey ssh.PublicKey - // A public key may be used to authenticate against the remote - // server by using an unencrypted PEM-encoded private key file. - // - // If you have an encrypted private key, the crypto/x509 package - // can be used to decrypt it. - key, err := ioutil.ReadFile("/home/user/.ssh/id_rsa") - if err != nil { - log.Fatalf("unable to read private key: %v", err) - } - - // Create the Signer for this private key. - signer, err := ssh.ParsePrivateKey(key) - if err != nil { - log.Fatalf("unable to parse private key: %v", err) - } - - config := &ssh.ClientConfig{ - User: "user", - Auth: []ssh.AuthMethod{ - // Use the PublicKeys method for remote authentication. - ssh.PublicKeys(signer), - }, - HostKeyCallback: ssh.FixedHostKey(hostKey), - } - - // Connect to the remote server and perform the SSH handshake. - client, err := ssh.Dial("tcp", "host.com:22", config) - if err != nil { - log.Fatalf("unable to connect: %v", err) - } - defer client.Close() -} - -func ExampleClient_Listen() { - var hostKey ssh.PublicKey - config := &ssh.ClientConfig{ - User: "username", - Auth: []ssh.AuthMethod{ - ssh.Password("password"), - }, - HostKeyCallback: ssh.FixedHostKey(hostKey), - } - // Dial your ssh server. - conn, err := ssh.Dial("tcp", "localhost:22", config) - if err != nil { - log.Fatal("unable to connect: ", err) - } - defer conn.Close() - - // Request the remote side to open port 8080 on all interfaces. - l, err := conn.Listen("tcp", "0.0.0.0:8080") - if err != nil { - log.Fatal("unable to register tcp forward: ", err) - } - defer l.Close() - - // Serve HTTP with your SSH server acting as a reverse proxy. - http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { - fmt.Fprintf(resp, "Hello world!\n") - })) -} - -func ExampleSession_RequestPty() { - var hostKey ssh.PublicKey - // Create client config - config := &ssh.ClientConfig{ - User: "username", - Auth: []ssh.AuthMethod{ - ssh.Password("password"), - }, - HostKeyCallback: ssh.FixedHostKey(hostKey), - } - // Connect to ssh server - conn, err := ssh.Dial("tcp", "localhost:22", config) - if err != nil { - log.Fatal("unable to connect: ", err) - } - defer conn.Close() - // Create a session - session, err := conn.NewSession() - if err != nil { - log.Fatal("unable to create session: ", err) - } - defer session.Close() - // Set up terminal modes - modes := ssh.TerminalModes{ - ssh.ECHO: 0, // disable echoing - ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud - ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud - } - // Request pseudo terminal - if err := session.RequestPty("xterm", 40, 80, modes); err != nil { - log.Fatal("request for pseudo terminal failed: ", err) - } - // Start remote shell - if err := session.Shell(); err != nil { - log.Fatal("failed to start shell: ", err) - } -} diff --git a/vendor/golang.org/x/crypto/ssh/handshake_test.go b/vendor/golang.org/x/crypto/ssh/handshake_test.go deleted file mode 100644 index 91d493568973..000000000000 --- a/vendor/golang.org/x/crypto/ssh/handshake_test.go +++ /dev/null @@ -1,559 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -import ( - "bytes" - "crypto/rand" - "errors" - "fmt" - "io" - "net" - "reflect" - "runtime" - "strings" - "sync" - "testing" -) - -type testChecker struct { - calls []string -} - -func (t *testChecker) Check(dialAddr string, addr net.Addr, key PublicKey) error { - if dialAddr == "bad" { - return fmt.Errorf("dialAddr is bad") - } - - if tcpAddr, ok := addr.(*net.TCPAddr); !ok || tcpAddr == nil { - return fmt.Errorf("testChecker: got %T want *net.TCPAddr", addr) - } - - t.calls = append(t.calls, fmt.Sprintf("%s %v %s %x", dialAddr, addr, key.Type(), key.Marshal())) - - return nil -} - -// netPipe is analogous to net.Pipe, but it uses a real net.Conn, and -// therefore is buffered (net.Pipe deadlocks if both sides start with -// a write.) -func netPipe() (net.Conn, net.Conn, error) { - listener, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - listener, err = net.Listen("tcp", "[::1]:0") - if err != nil { - return nil, nil, err - } - } - defer listener.Close() - c1, err := net.Dial("tcp", listener.Addr().String()) - if err != nil { - return nil, nil, err - } - - c2, err := listener.Accept() - if err != nil { - c1.Close() - return nil, nil, err - } - - return c1, c2, nil -} - -// noiseTransport inserts ignore messages to check that the read loop -// and the key exchange filters out these messages. -type noiseTransport struct { - keyingTransport -} - -func (t *noiseTransport) writePacket(p []byte) error { - ignore := []byte{msgIgnore} - if err := t.keyingTransport.writePacket(ignore); err != nil { - return err - } - debug := []byte{msgDebug, 1, 2, 3} - if err := t.keyingTransport.writePacket(debug); err != nil { - return err - } - - return t.keyingTransport.writePacket(p) -} - -func addNoiseTransport(t keyingTransport) keyingTransport { - return &noiseTransport{t} -} - -// handshakePair creates two handshakeTransports connected with each -// other. If the noise argument is true, both transports will try to -// confuse the other side by sending ignore and debug messages. -func handshakePair(clientConf *ClientConfig, addr string, noise bool) (client *handshakeTransport, server *handshakeTransport, err error) { - a, b, err := netPipe() - if err != nil { - return nil, nil, err - } - - var trC, trS keyingTransport - - trC = newTransport(a, rand.Reader, true) - trS = newTransport(b, rand.Reader, false) - if noise { - trC = addNoiseTransport(trC) - trS = addNoiseTransport(trS) - } - clientConf.SetDefaults() - - v := []byte("version") - client = newClientTransport(trC, v, v, clientConf, addr, a.RemoteAddr()) - - serverConf := &ServerConfig{} - serverConf.AddHostKey(testSigners["ecdsa"]) - serverConf.AddHostKey(testSigners["rsa"]) - serverConf.SetDefaults() - server = newServerTransport(trS, v, v, serverConf) - - if err := server.waitSession(); err != nil { - return nil, nil, fmt.Errorf("server.waitSession: %v", err) - } - if err := client.waitSession(); err != nil { - return nil, nil, fmt.Errorf("client.waitSession: %v", err) - } - - return client, server, nil -} - -func TestHandshakeBasic(t *testing.T) { - if runtime.GOOS == "plan9" { - t.Skip("see golang.org/issue/7237") - } - - checker := &syncChecker{ - waitCall: make(chan int, 10), - called: make(chan int, 10), - } - - checker.waitCall <- 1 - trC, trS, err := handshakePair(&ClientConfig{HostKeyCallback: checker.Check}, "addr", false) - if err != nil { - t.Fatalf("handshakePair: %v", err) - } - - defer trC.Close() - defer trS.Close() - - // Let first kex complete normally. - <-checker.called - - clientDone := make(chan int, 0) - gotHalf := make(chan int, 0) - const N = 20 - - go func() { - defer close(clientDone) - // Client writes a bunch of stuff, and does a key - // change in the middle. This should not confuse the - // handshake in progress. We do this twice, so we test - // that the packet buffer is reset correctly. - for i := 0; i < N; i++ { - p := []byte{msgRequestSuccess, byte(i)} - if err := trC.writePacket(p); err != nil { - t.Fatalf("sendPacket: %v", err) - } - if (i % 10) == 5 { - <-gotHalf - // halfway through, we request a key change. - trC.requestKeyExchange() - - // Wait until we can be sure the key - // change has really started before we - // write more. - <-checker.called - } - if (i % 10) == 7 { - // write some packets until the kex - // completes, to test buffering of - // packets. - checker.waitCall <- 1 - } - } - }() - - // Server checks that client messages come in cleanly - i := 0 - err = nil - for ; i < N; i++ { - var p []byte - p, err = trS.readPacket() - if err != nil { - break - } - if (i % 10) == 5 { - gotHalf <- 1 - } - - want := []byte{msgRequestSuccess, byte(i)} - if bytes.Compare(p, want) != 0 { - t.Errorf("message %d: got %v, want %v", i, p, want) - } - } - <-clientDone - if err != nil && err != io.EOF { - t.Fatalf("server error: %v", err) - } - if i != N { - t.Errorf("received %d messages, want 10.", i) - } - - close(checker.called) - if _, ok := <-checker.called; ok { - // If all went well, we registered exactly 2 key changes: one - // that establishes the session, and one that we requested - // additionally. - t.Fatalf("got another host key checks after 2 handshakes") - } -} - -func TestForceFirstKex(t *testing.T) { - // like handshakePair, but must access the keyingTransport. - checker := &testChecker{} - clientConf := &ClientConfig{HostKeyCallback: checker.Check} - a, b, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - - var trC, trS keyingTransport - - trC = newTransport(a, rand.Reader, true) - - // This is the disallowed packet: - trC.writePacket(Marshal(&serviceRequestMsg{serviceUserAuth})) - - // Rest of the setup. - trS = newTransport(b, rand.Reader, false) - clientConf.SetDefaults() - - v := []byte("version") - client := newClientTransport(trC, v, v, clientConf, "addr", a.RemoteAddr()) - - serverConf := &ServerConfig{} - serverConf.AddHostKey(testSigners["ecdsa"]) - serverConf.AddHostKey(testSigners["rsa"]) - serverConf.SetDefaults() - server := newServerTransport(trS, v, v, serverConf) - - defer client.Close() - defer server.Close() - - // We setup the initial key exchange, but the remote side - // tries to send serviceRequestMsg in cleartext, which is - // disallowed. - - if err := server.waitSession(); err == nil { - t.Errorf("server first kex init should reject unexpected packet") - } -} - -func TestHandshakeAutoRekeyWrite(t *testing.T) { - checker := &syncChecker{ - called: make(chan int, 10), - waitCall: nil, - } - clientConf := &ClientConfig{HostKeyCallback: checker.Check} - clientConf.RekeyThreshold = 500 - trC, trS, err := handshakePair(clientConf, "addr", false) - if err != nil { - t.Fatalf("handshakePair: %v", err) - } - defer trC.Close() - defer trS.Close() - - input := make([]byte, 251) - input[0] = msgRequestSuccess - - done := make(chan int, 1) - const numPacket = 5 - go func() { - defer close(done) - j := 0 - for ; j < numPacket; j++ { - if p, err := trS.readPacket(); err != nil { - break - } else if !bytes.Equal(input, p) { - t.Errorf("got packet type %d, want %d", p[0], input[0]) - } - } - - if j != numPacket { - t.Errorf("got %d, want 5 messages", j) - } - }() - - <-checker.called - - for i := 0; i < numPacket; i++ { - p := make([]byte, len(input)) - copy(p, input) - if err := trC.writePacket(p); err != nil { - t.Errorf("writePacket: %v", err) - } - if i == 2 { - // Make sure the kex is in progress. - <-checker.called - } - - } - <-done -} - -type syncChecker struct { - waitCall chan int - called chan int -} - -func (c *syncChecker) Check(dialAddr string, addr net.Addr, key PublicKey) error { - c.called <- 1 - if c.waitCall != nil { - <-c.waitCall - } - return nil -} - -func TestHandshakeAutoRekeyRead(t *testing.T) { - sync := &syncChecker{ - called: make(chan int, 2), - waitCall: nil, - } - clientConf := &ClientConfig{ - HostKeyCallback: sync.Check, - } - clientConf.RekeyThreshold = 500 - - trC, trS, err := handshakePair(clientConf, "addr", false) - if err != nil { - t.Fatalf("handshakePair: %v", err) - } - defer trC.Close() - defer trS.Close() - - packet := make([]byte, 501) - packet[0] = msgRequestSuccess - if err := trS.writePacket(packet); err != nil { - t.Fatalf("writePacket: %v", err) - } - - // While we read out the packet, a key change will be - // initiated. - done := make(chan int, 1) - go func() { - defer close(done) - if _, err := trC.readPacket(); err != nil { - t.Fatalf("readPacket(client): %v", err) - } - - }() - - <-done - <-sync.called -} - -// errorKeyingTransport generates errors after a given number of -// read/write operations. -type errorKeyingTransport struct { - packetConn - readLeft, writeLeft int -} - -func (n *errorKeyingTransport) prepareKeyChange(*algorithms, *kexResult) error { - return nil -} - -func (n *errorKeyingTransport) getSessionID() []byte { - return nil -} - -func (n *errorKeyingTransport) writePacket(packet []byte) error { - if n.writeLeft == 0 { - n.Close() - return errors.New("barf") - } - - n.writeLeft-- - return n.packetConn.writePacket(packet) -} - -func (n *errorKeyingTransport) readPacket() ([]byte, error) { - if n.readLeft == 0 { - n.Close() - return nil, errors.New("barf") - } - - n.readLeft-- - return n.packetConn.readPacket() -} - -func TestHandshakeErrorHandlingRead(t *testing.T) { - for i := 0; i < 20; i++ { - testHandshakeErrorHandlingN(t, i, -1, false) - } -} - -func TestHandshakeErrorHandlingWrite(t *testing.T) { - for i := 0; i < 20; i++ { - testHandshakeErrorHandlingN(t, -1, i, false) - } -} - -func TestHandshakeErrorHandlingReadCoupled(t *testing.T) { - for i := 0; i < 20; i++ { - testHandshakeErrorHandlingN(t, i, -1, true) - } -} - -func TestHandshakeErrorHandlingWriteCoupled(t *testing.T) { - for i := 0; i < 20; i++ { - testHandshakeErrorHandlingN(t, -1, i, true) - } -} - -// testHandshakeErrorHandlingN runs handshakes, injecting errors. If -// handshakeTransport deadlocks, the go runtime will detect it and -// panic. -func testHandshakeErrorHandlingN(t *testing.T, readLimit, writeLimit int, coupled bool) { - msg := Marshal(&serviceRequestMsg{strings.Repeat("x", int(minRekeyThreshold)/4)}) - - a, b := memPipe() - defer a.Close() - defer b.Close() - - key := testSigners["ecdsa"] - serverConf := Config{RekeyThreshold: minRekeyThreshold} - serverConf.SetDefaults() - serverConn := newHandshakeTransport(&errorKeyingTransport{a, readLimit, writeLimit}, &serverConf, []byte{'a'}, []byte{'b'}) - serverConn.hostKeys = []Signer{key} - go serverConn.readLoop() - go serverConn.kexLoop() - - clientConf := Config{RekeyThreshold: 10 * minRekeyThreshold} - clientConf.SetDefaults() - clientConn := newHandshakeTransport(&errorKeyingTransport{b, -1, -1}, &clientConf, []byte{'a'}, []byte{'b'}) - clientConn.hostKeyAlgorithms = []string{key.PublicKey().Type()} - clientConn.hostKeyCallback = InsecureIgnoreHostKey() - go clientConn.readLoop() - go clientConn.kexLoop() - - var wg sync.WaitGroup - - for _, hs := range []packetConn{serverConn, clientConn} { - if !coupled { - wg.Add(2) - go func(c packetConn) { - for i := 0; ; i++ { - str := fmt.Sprintf("%08x", i) + strings.Repeat("x", int(minRekeyThreshold)/4-8) - err := c.writePacket(Marshal(&serviceRequestMsg{str})) - if err != nil { - break - } - } - wg.Done() - c.Close() - }(hs) - go func(c packetConn) { - for { - _, err := c.readPacket() - if err != nil { - break - } - } - wg.Done() - }(hs) - } else { - wg.Add(1) - go func(c packetConn) { - for { - _, err := c.readPacket() - if err != nil { - break - } - if err := c.writePacket(msg); err != nil { - break - } - - } - wg.Done() - }(hs) - } - } - wg.Wait() -} - -func TestDisconnect(t *testing.T) { - if runtime.GOOS == "plan9" { - t.Skip("see golang.org/issue/7237") - } - checker := &testChecker{} - trC, trS, err := handshakePair(&ClientConfig{HostKeyCallback: checker.Check}, "addr", false) - if err != nil { - t.Fatalf("handshakePair: %v", err) - } - - defer trC.Close() - defer trS.Close() - - trC.writePacket([]byte{msgRequestSuccess, 0, 0}) - errMsg := &disconnectMsg{ - Reason: 42, - Message: "such is life", - } - trC.writePacket(Marshal(errMsg)) - trC.writePacket([]byte{msgRequestSuccess, 0, 0}) - - packet, err := trS.readPacket() - if err != nil { - t.Fatalf("readPacket 1: %v", err) - } - if packet[0] != msgRequestSuccess { - t.Errorf("got packet %v, want packet type %d", packet, msgRequestSuccess) - } - - _, err = trS.readPacket() - if err == nil { - t.Errorf("readPacket 2 succeeded") - } else if !reflect.DeepEqual(err, errMsg) { - t.Errorf("got error %#v, want %#v", err, errMsg) - } - - _, err = trS.readPacket() - if err == nil { - t.Errorf("readPacket 3 succeeded") - } -} - -func TestHandshakeRekeyDefault(t *testing.T) { - clientConf := &ClientConfig{ - Config: Config{ - Ciphers: []string{"aes128-ctr"}, - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - trC, trS, err := handshakePair(clientConf, "addr", false) - if err != nil { - t.Fatalf("handshakePair: %v", err) - } - defer trC.Close() - defer trS.Close() - - trC.writePacket([]byte{msgRequestSuccess, 0, 0}) - trC.Close() - - rgb := (1024 + trC.readBytesLeft) >> 30 - wgb := (1024 + trC.writeBytesLeft) >> 30 - - if rgb != 64 { - t.Errorf("got rekey after %dG read, want 64G", rgb) - } - if wgb != 64 { - t.Errorf("got rekey after %dG write, want 64G", wgb) - } -} diff --git a/vendor/golang.org/x/crypto/ssh/kex_test.go b/vendor/golang.org/x/crypto/ssh/kex_test.go deleted file mode 100644 index 12ca0acd31d0..000000000000 --- a/vendor/golang.org/x/crypto/ssh/kex_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -// Key exchange tests. - -import ( - "crypto/rand" - "reflect" - "testing" -) - -func TestKexes(t *testing.T) { - type kexResultErr struct { - result *kexResult - err error - } - - for name, kex := range kexAlgoMap { - a, b := memPipe() - - s := make(chan kexResultErr, 1) - c := make(chan kexResultErr, 1) - var magics handshakeMagics - go func() { - r, e := kex.Client(a, rand.Reader, &magics) - a.Close() - c <- kexResultErr{r, e} - }() - go func() { - r, e := kex.Server(b, rand.Reader, &magics, testSigners["ecdsa"]) - b.Close() - s <- kexResultErr{r, e} - }() - - clientRes := <-c - serverRes := <-s - if clientRes.err != nil { - t.Errorf("client: %v", clientRes.err) - } - if serverRes.err != nil { - t.Errorf("server: %v", serverRes.err) - } - if !reflect.DeepEqual(clientRes.result, serverRes.result) { - t.Errorf("kex %q: mismatch %#v, %#v", name, clientRes.result, serverRes.result) - } - } -} diff --git a/vendor/golang.org/x/crypto/ssh/keys_test.go b/vendor/golang.org/x/crypto/ssh/keys_test.go deleted file mode 100644 index 20ab954e2afa..000000000000 --- a/vendor/golang.org/x/crypto/ssh/keys_test.go +++ /dev/null @@ -1,500 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -import ( - "bytes" - "crypto/dsa" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "encoding/base64" - "fmt" - "reflect" - "strings" - "testing" - - "golang.org/x/crypto/ed25519" - "golang.org/x/crypto/ssh/testdata" -) - -func rawKey(pub PublicKey) interface{} { - switch k := pub.(type) { - case *rsaPublicKey: - return (*rsa.PublicKey)(k) - case *dsaPublicKey: - return (*dsa.PublicKey)(k) - case *ecdsaPublicKey: - return (*ecdsa.PublicKey)(k) - case ed25519PublicKey: - return (ed25519.PublicKey)(k) - case *Certificate: - return k - } - panic("unknown key type") -} - -func TestKeyMarshalParse(t *testing.T) { - for _, priv := range testSigners { - pub := priv.PublicKey() - roundtrip, err := ParsePublicKey(pub.Marshal()) - if err != nil { - t.Errorf("ParsePublicKey(%T): %v", pub, err) - } - - k1 := rawKey(pub) - k2 := rawKey(roundtrip) - - if !reflect.DeepEqual(k1, k2) { - t.Errorf("got %#v in roundtrip, want %#v", k2, k1) - } - } -} - -func TestUnsupportedCurves(t *testing.T) { - raw, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader) - if err != nil { - t.Fatalf("GenerateKey: %v", err) - } - - if _, err = NewSignerFromKey(raw); err == nil || !strings.Contains(err.Error(), "only P-256") { - t.Fatalf("NewPrivateKey should not succeed with P-224, got: %v", err) - } - - if _, err = NewPublicKey(&raw.PublicKey); err == nil || !strings.Contains(err.Error(), "only P-256") { - t.Fatalf("NewPublicKey should not succeed with P-224, got: %v", err) - } -} - -func TestNewPublicKey(t *testing.T) { - for _, k := range testSigners { - raw := rawKey(k.PublicKey()) - // Skip certificates, as NewPublicKey does not support them. - if _, ok := raw.(*Certificate); ok { - continue - } - pub, err := NewPublicKey(raw) - if err != nil { - t.Errorf("NewPublicKey(%#v): %v", raw, err) - } - if !reflect.DeepEqual(k.PublicKey(), pub) { - t.Errorf("NewPublicKey(%#v) = %#v, want %#v", raw, pub, k.PublicKey()) - } - } -} - -func TestKeySignVerify(t *testing.T) { - for _, priv := range testSigners { - pub := priv.PublicKey() - - data := []byte("sign me") - sig, err := priv.Sign(rand.Reader, data) - if err != nil { - t.Fatalf("Sign(%T): %v", priv, err) - } - - if err := pub.Verify(data, sig); err != nil { - t.Errorf("publicKey.Verify(%T): %v", priv, err) - } - sig.Blob[5]++ - if err := pub.Verify(data, sig); err == nil { - t.Errorf("publicKey.Verify on broken sig did not fail") - } - } -} - -func TestParseRSAPrivateKey(t *testing.T) { - key := testPrivateKeys["rsa"] - - rsa, ok := key.(*rsa.PrivateKey) - if !ok { - t.Fatalf("got %T, want *rsa.PrivateKey", rsa) - } - - if err := rsa.Validate(); err != nil { - t.Errorf("Validate: %v", err) - } -} - -func TestParseECPrivateKey(t *testing.T) { - key := testPrivateKeys["ecdsa"] - - ecKey, ok := key.(*ecdsa.PrivateKey) - if !ok { - t.Fatalf("got %T, want *ecdsa.PrivateKey", ecKey) - } - - if !validateECPublicKey(ecKey.Curve, ecKey.X, ecKey.Y) { - t.Fatalf("public key does not validate.") - } -} - -// See Issue https://github.com/golang/go/issues/6650. -func TestParseEncryptedPrivateKeysFails(t *testing.T) { - const wantSubstring = "encrypted" - for i, tt := range testdata.PEMEncryptedKeys { - _, err := ParsePrivateKey(tt.PEMBytes) - if err == nil { - t.Errorf("#%d key %s: ParsePrivateKey successfully parsed, expected an error", i, tt.Name) - continue - } - - if !strings.Contains(err.Error(), wantSubstring) { - t.Errorf("#%d key %s: got error %q, want substring %q", i, tt.Name, err, wantSubstring) - } - } -} - -// Parse encrypted private keys with passphrase -func TestParseEncryptedPrivateKeysWithPassphrase(t *testing.T) { - data := []byte("sign me") - for _, tt := range testdata.PEMEncryptedKeys { - s, err := ParsePrivateKeyWithPassphrase(tt.PEMBytes, []byte(tt.EncryptionKey)) - if err != nil { - t.Fatalf("ParsePrivateKeyWithPassphrase returned error: %s", err) - continue - } - sig, err := s.Sign(rand.Reader, data) - if err != nil { - t.Fatalf("dsa.Sign: %v", err) - } - if err := s.PublicKey().Verify(data, sig); err != nil { - t.Errorf("Verify failed: %v", err) - } - } - - tt := testdata.PEMEncryptedKeys[0] - _, err := ParsePrivateKeyWithPassphrase(tt.PEMBytes, []byte("incorrect")) - if err != x509.IncorrectPasswordError { - t.Fatalf("got %v want IncorrectPasswordError", err) - } -} - -func TestParseDSA(t *testing.T) { - // We actually exercise the ParsePrivateKey codepath here, as opposed to - // using the ParseRawPrivateKey+NewSignerFromKey path that testdata_test.go - // uses. - s, err := ParsePrivateKey(testdata.PEMBytes["dsa"]) - if err != nil { - t.Fatalf("ParsePrivateKey returned error: %s", err) - } - - data := []byte("sign me") - sig, err := s.Sign(rand.Reader, data) - if err != nil { - t.Fatalf("dsa.Sign: %v", err) - } - - if err := s.PublicKey().Verify(data, sig); err != nil { - t.Errorf("Verify failed: %v", err) - } -} - -// Tests for authorized_keys parsing. - -// getTestKey returns a public key, and its base64 encoding. -func getTestKey() (PublicKey, string) { - k := testPublicKeys["rsa"] - - b := &bytes.Buffer{} - e := base64.NewEncoder(base64.StdEncoding, b) - e.Write(k.Marshal()) - e.Close() - - return k, b.String() -} - -func TestMarshalParsePublicKey(t *testing.T) { - pub, pubSerialized := getTestKey() - line := fmt.Sprintf("%s %s user@host", pub.Type(), pubSerialized) - - authKeys := MarshalAuthorizedKey(pub) - actualFields := strings.Fields(string(authKeys)) - if len(actualFields) == 0 { - t.Fatalf("failed authKeys: %v", authKeys) - } - - // drop the comment - expectedFields := strings.Fields(line)[0:2] - - if !reflect.DeepEqual(actualFields, expectedFields) { - t.Errorf("got %v, expected %v", actualFields, expectedFields) - } - - actPub, _, _, _, err := ParseAuthorizedKey([]byte(line)) - if err != nil { - t.Fatalf("cannot parse %v: %v", line, err) - } - if !reflect.DeepEqual(actPub, pub) { - t.Errorf("got %v, expected %v", actPub, pub) - } -} - -type authResult struct { - pubKey PublicKey - options []string - comments string - rest string - ok bool -} - -func testAuthorizedKeys(t *testing.T, authKeys []byte, expected []authResult) { - rest := authKeys - var values []authResult - for len(rest) > 0 { - var r authResult - var err error - r.pubKey, r.comments, r.options, rest, err = ParseAuthorizedKey(rest) - r.ok = (err == nil) - t.Log(err) - r.rest = string(rest) - values = append(values, r) - } - - if !reflect.DeepEqual(values, expected) { - t.Errorf("got %#v, expected %#v", values, expected) - } -} - -func TestAuthorizedKeyBasic(t *testing.T) { - pub, pubSerialized := getTestKey() - line := "ssh-rsa " + pubSerialized + " user@host" - testAuthorizedKeys(t, []byte(line), - []authResult{ - {pub, nil, "user@host", "", true}, - }) -} - -func TestAuth(t *testing.T) { - pub, pubSerialized := getTestKey() - authWithOptions := []string{ - `# comments to ignore before any keys...`, - ``, - `env="HOME=/home/root",no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host`, - `# comments to ignore, along with a blank line`, - ``, - `env="HOME=/home/root2" ssh-rsa ` + pubSerialized + ` user2@host2`, - ``, - `# more comments, plus a invalid entry`, - `ssh-rsa data-that-will-not-parse user@host3`, - } - for _, eol := range []string{"\n", "\r\n"} { - authOptions := strings.Join(authWithOptions, eol) - rest2 := strings.Join(authWithOptions[3:], eol) - rest3 := strings.Join(authWithOptions[6:], eol) - testAuthorizedKeys(t, []byte(authOptions), []authResult{ - {pub, []string{`env="HOME=/home/root"`, "no-port-forwarding"}, "user@host", rest2, true}, - {pub, []string{`env="HOME=/home/root2"`}, "user2@host2", rest3, true}, - {nil, nil, "", "", false}, - }) - } -} - -func TestAuthWithQuotedSpaceInEnv(t *testing.T) { - pub, pubSerialized := getTestKey() - authWithQuotedSpaceInEnv := []byte(`env="HOME=/home/root dir",no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host`) - testAuthorizedKeys(t, []byte(authWithQuotedSpaceInEnv), []authResult{ - {pub, []string{`env="HOME=/home/root dir"`, "no-port-forwarding"}, "user@host", "", true}, - }) -} - -func TestAuthWithQuotedCommaInEnv(t *testing.T) { - pub, pubSerialized := getTestKey() - authWithQuotedCommaInEnv := []byte(`env="HOME=/home/root,dir",no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host`) - testAuthorizedKeys(t, []byte(authWithQuotedCommaInEnv), []authResult{ - {pub, []string{`env="HOME=/home/root,dir"`, "no-port-forwarding"}, "user@host", "", true}, - }) -} - -func TestAuthWithQuotedQuoteInEnv(t *testing.T) { - pub, pubSerialized := getTestKey() - authWithQuotedQuoteInEnv := []byte(`env="HOME=/home/\"root dir",no-port-forwarding` + "\t" + `ssh-rsa` + "\t" + pubSerialized + ` user@host`) - authWithDoubleQuotedQuote := []byte(`no-port-forwarding,env="HOME=/home/ \"root dir\"" ssh-rsa ` + pubSerialized + "\t" + `user@host`) - testAuthorizedKeys(t, []byte(authWithQuotedQuoteInEnv), []authResult{ - {pub, []string{`env="HOME=/home/\"root dir"`, "no-port-forwarding"}, "user@host", "", true}, - }) - - testAuthorizedKeys(t, []byte(authWithDoubleQuotedQuote), []authResult{ - {pub, []string{"no-port-forwarding", `env="HOME=/home/ \"root dir\""`}, "user@host", "", true}, - }) -} - -func TestAuthWithInvalidSpace(t *testing.T) { - _, pubSerialized := getTestKey() - authWithInvalidSpace := []byte(`env="HOME=/home/root dir", no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host -#more to follow but still no valid keys`) - testAuthorizedKeys(t, []byte(authWithInvalidSpace), []authResult{ - {nil, nil, "", "", false}, - }) -} - -func TestAuthWithMissingQuote(t *testing.T) { - pub, pubSerialized := getTestKey() - authWithMissingQuote := []byte(`env="HOME=/home/root,no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host -env="HOME=/home/root",shared-control ssh-rsa ` + pubSerialized + ` user@host`) - - testAuthorizedKeys(t, []byte(authWithMissingQuote), []authResult{ - {pub, []string{`env="HOME=/home/root"`, `shared-control`}, "user@host", "", true}, - }) -} - -func TestInvalidEntry(t *testing.T) { - authInvalid := []byte(`ssh-rsa`) - _, _, _, _, err := ParseAuthorizedKey(authInvalid) - if err == nil { - t.Errorf("got valid entry for %q", authInvalid) - } -} - -var knownHostsParseTests = []struct { - input string - err string - - marker string - comment string - hosts []string - rest string -}{ - { - "", - "EOF", - - "", "", nil, "", - }, - { - "# Just a comment", - "EOF", - - "", "", nil, "", - }, - { - " \t ", - "EOF", - - "", "", nil, "", - }, - { - "localhost ssh-rsa {RSAPUB}", - "", - - "", "", []string{"localhost"}, "", - }, - { - "localhost\tssh-rsa {RSAPUB}", - "", - - "", "", []string{"localhost"}, "", - }, - { - "localhost\tssh-rsa {RSAPUB}\tcomment comment", - "", - - "", "comment comment", []string{"localhost"}, "", - }, - { - "localhost\tssh-rsa {RSAPUB}\tcomment comment\n", - "", - - "", "comment comment", []string{"localhost"}, "", - }, - { - "localhost\tssh-rsa {RSAPUB}\tcomment comment\r\n", - "", - - "", "comment comment", []string{"localhost"}, "", - }, - { - "localhost\tssh-rsa {RSAPUB}\tcomment comment\r\nnext line", - "", - - "", "comment comment", []string{"localhost"}, "next line", - }, - { - "localhost,[host2:123]\tssh-rsa {RSAPUB}\tcomment comment", - "", - - "", "comment comment", []string{"localhost", "[host2:123]"}, "", - }, - { - "@marker \tlocalhost,[host2:123]\tssh-rsa {RSAPUB}", - "", - - "marker", "", []string{"localhost", "[host2:123]"}, "", - }, - { - "@marker \tlocalhost,[host2:123]\tssh-rsa aabbccdd", - "short read", - - "", "", nil, "", - }, -} - -func TestKnownHostsParsing(t *testing.T) { - rsaPub, rsaPubSerialized := getTestKey() - - for i, test := range knownHostsParseTests { - var expectedKey PublicKey - const rsaKeyToken = "{RSAPUB}" - - input := test.input - if strings.Contains(input, rsaKeyToken) { - expectedKey = rsaPub - input = strings.Replace(test.input, rsaKeyToken, rsaPubSerialized, -1) - } - - marker, hosts, pubKey, comment, rest, err := ParseKnownHosts([]byte(input)) - if err != nil { - if len(test.err) == 0 { - t.Errorf("#%d: unexpectedly failed with %q", i, err) - } else if !strings.Contains(err.Error(), test.err) { - t.Errorf("#%d: expected error containing %q, but got %q", i, test.err, err) - } - continue - } else if len(test.err) != 0 { - t.Errorf("#%d: succeeded but expected error including %q", i, test.err) - continue - } - - if !reflect.DeepEqual(expectedKey, pubKey) { - t.Errorf("#%d: expected key %#v, but got %#v", i, expectedKey, pubKey) - } - - if marker != test.marker { - t.Errorf("#%d: expected marker %q, but got %q", i, test.marker, marker) - } - - if comment != test.comment { - t.Errorf("#%d: expected comment %q, but got %q", i, test.comment, comment) - } - - if !reflect.DeepEqual(test.hosts, hosts) { - t.Errorf("#%d: expected hosts %#v, but got %#v", i, test.hosts, hosts) - } - - if rest := string(rest); rest != test.rest { - t.Errorf("#%d: expected remaining input to be %q, but got %q", i, test.rest, rest) - } - } -} - -func TestFingerprintLegacyMD5(t *testing.T) { - pub, _ := getTestKey() - fingerprint := FingerprintLegacyMD5(pub) - want := "fb:61:6d:1a:e3:f0:95:45:3c:a0:79:be:4a:93:63:66" // ssh-keygen -lf -E md5 rsa - if fingerprint != want { - t.Errorf("got fingerprint %q want %q", fingerprint, want) - } -} - -func TestFingerprintSHA256(t *testing.T) { - pub, _ := getTestKey() - fingerprint := FingerprintSHA256(pub) - want := "SHA256:Anr3LjZK8YVpjrxu79myrW9Hrb/wpcMNpVvTq/RcBm8" // ssh-keygen -lf rsa - if fingerprint != want { - t.Errorf("got fingerprint %q want %q", fingerprint, want) - } -} diff --git a/vendor/golang.org/x/crypto/ssh/mempipe_test.go b/vendor/golang.org/x/crypto/ssh/mempipe_test.go deleted file mode 100644 index 8697cd6140a7..000000000000 --- a/vendor/golang.org/x/crypto/ssh/mempipe_test.go +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -import ( - "io" - "sync" - "testing" -) - -// An in-memory packetConn. It is safe to call Close and writePacket -// from different goroutines. -type memTransport struct { - eof bool - pending [][]byte - write *memTransport - sync.Mutex - *sync.Cond -} - -func (t *memTransport) readPacket() ([]byte, error) { - t.Lock() - defer t.Unlock() - for { - if len(t.pending) > 0 { - r := t.pending[0] - t.pending = t.pending[1:] - return r, nil - } - if t.eof { - return nil, io.EOF - } - t.Cond.Wait() - } -} - -func (t *memTransport) closeSelf() error { - t.Lock() - defer t.Unlock() - if t.eof { - return io.EOF - } - t.eof = true - t.Cond.Broadcast() - return nil -} - -func (t *memTransport) Close() error { - err := t.write.closeSelf() - t.closeSelf() - return err -} - -func (t *memTransport) writePacket(p []byte) error { - t.write.Lock() - defer t.write.Unlock() - if t.write.eof { - return io.EOF - } - c := make([]byte, len(p)) - copy(c, p) - t.write.pending = append(t.write.pending, c) - t.write.Cond.Signal() - return nil -} - -func memPipe() (a, b packetConn) { - t1 := memTransport{} - t2 := memTransport{} - t1.write = &t2 - t2.write = &t1 - t1.Cond = sync.NewCond(&t1.Mutex) - t2.Cond = sync.NewCond(&t2.Mutex) - return &t1, &t2 -} - -func TestMemPipe(t *testing.T) { - a, b := memPipe() - if err := a.writePacket([]byte{42}); err != nil { - t.Fatalf("writePacket: %v", err) - } - if err := a.Close(); err != nil { - t.Fatal("Close: ", err) - } - p, err := b.readPacket() - if err != nil { - t.Fatal("readPacket: ", err) - } - if len(p) != 1 || p[0] != 42 { - t.Fatalf("got %v, want {42}", p) - } - p, err = b.readPacket() - if err != io.EOF { - t.Fatalf("got %v, %v, want EOF", p, err) - } -} - -func TestDoubleClose(t *testing.T) { - a, _ := memPipe() - err := a.Close() - if err != nil { - t.Errorf("Close: %v", err) - } - err = a.Close() - if err != io.EOF { - t.Errorf("expect EOF on double close.") - } -} diff --git a/vendor/golang.org/x/crypto/ssh/messages_test.go b/vendor/golang.org/x/crypto/ssh/messages_test.go deleted file mode 100644 index e79076412ab4..000000000000 --- a/vendor/golang.org/x/crypto/ssh/messages_test.go +++ /dev/null @@ -1,288 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -import ( - "bytes" - "math/big" - "math/rand" - "reflect" - "testing" - "testing/quick" -) - -var intLengthTests = []struct { - val, length int -}{ - {0, 4 + 0}, - {1, 4 + 1}, - {127, 4 + 1}, - {128, 4 + 2}, - {-1, 4 + 1}, -} - -func TestIntLength(t *testing.T) { - for _, test := range intLengthTests { - v := new(big.Int).SetInt64(int64(test.val)) - length := intLength(v) - if length != test.length { - t.Errorf("For %d, got length %d but expected %d", test.val, length, test.length) - } - } -} - -type msgAllTypes struct { - Bool bool `sshtype:"21"` - Array [16]byte - Uint64 uint64 - Uint32 uint32 - Uint8 uint8 - String string - Strings []string - Bytes []byte - Int *big.Int - Rest []byte `ssh:"rest"` -} - -func (t *msgAllTypes) Generate(rand *rand.Rand, size int) reflect.Value { - m := &msgAllTypes{} - m.Bool = rand.Intn(2) == 1 - randomBytes(m.Array[:], rand) - m.Uint64 = uint64(rand.Int63n(1<<63 - 1)) - m.Uint32 = uint32(rand.Intn((1 << 31) - 1)) - m.Uint8 = uint8(rand.Intn(1 << 8)) - m.String = string(m.Array[:]) - m.Strings = randomNameList(rand) - m.Bytes = m.Array[:] - m.Int = randomInt(rand) - m.Rest = m.Array[:] - return reflect.ValueOf(m) -} - -func TestMarshalUnmarshal(t *testing.T) { - rand := rand.New(rand.NewSource(0)) - iface := &msgAllTypes{} - ty := reflect.ValueOf(iface).Type() - - n := 100 - if testing.Short() { - n = 5 - } - for j := 0; j < n; j++ { - v, ok := quick.Value(ty, rand) - if !ok { - t.Errorf("failed to create value") - break - } - - m1 := v.Elem().Interface() - m2 := iface - - marshaled := Marshal(m1) - if err := Unmarshal(marshaled, m2); err != nil { - t.Errorf("Unmarshal %#v: %s", m1, err) - break - } - - if !reflect.DeepEqual(v.Interface(), m2) { - t.Errorf("got: %#v\nwant:%#v\n%x", m2, m1, marshaled) - break - } - } -} - -func TestUnmarshalEmptyPacket(t *testing.T) { - var b []byte - var m channelRequestSuccessMsg - if err := Unmarshal(b, &m); err == nil { - t.Fatalf("unmarshal of empty slice succeeded") - } -} - -func TestUnmarshalUnexpectedPacket(t *testing.T) { - type S struct { - I uint32 `sshtype:"43"` - S string - B bool - } - - s := S{11, "hello", true} - packet := Marshal(s) - packet[0] = 42 - roundtrip := S{} - err := Unmarshal(packet, &roundtrip) - if err == nil { - t.Fatal("expected error, not nil") - } -} - -func TestMarshalPtr(t *testing.T) { - s := struct { - S string - }{"hello"} - - m1 := Marshal(s) - m2 := Marshal(&s) - if !bytes.Equal(m1, m2) { - t.Errorf("got %q, want %q for marshaled pointer", m2, m1) - } -} - -func TestBareMarshalUnmarshal(t *testing.T) { - type S struct { - I uint32 - S string - B bool - } - - s := S{42, "hello", true} - packet := Marshal(s) - roundtrip := S{} - Unmarshal(packet, &roundtrip) - - if !reflect.DeepEqual(s, roundtrip) { - t.Errorf("got %#v, want %#v", roundtrip, s) - } -} - -func TestBareMarshal(t *testing.T) { - type S2 struct { - I uint32 - } - s := S2{42} - packet := Marshal(s) - i, rest, ok := parseUint32(packet) - if len(rest) > 0 || !ok { - t.Errorf("parseInt(%q): parse error", packet) - } - if i != s.I { - t.Errorf("got %d, want %d", i, s.I) - } -} - -func TestUnmarshalShortKexInitPacket(t *testing.T) { - // This used to panic. - // Issue 11348 - packet := []byte{0x14, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0xff, 0xff, 0xff, 0xff} - kim := &kexInitMsg{} - if err := Unmarshal(packet, kim); err == nil { - t.Error("truncated packet unmarshaled without error") - } -} - -func TestMarshalMultiTag(t *testing.T) { - var res struct { - A uint32 `sshtype:"1|2"` - } - - good1 := struct { - A uint32 `sshtype:"1"` - }{ - 1, - } - good2 := struct { - A uint32 `sshtype:"2"` - }{ - 1, - } - - if e := Unmarshal(Marshal(good1), &res); e != nil { - t.Errorf("error unmarshaling multipart tag: %v", e) - } - - if e := Unmarshal(Marshal(good2), &res); e != nil { - t.Errorf("error unmarshaling multipart tag: %v", e) - } - - bad1 := struct { - A uint32 `sshtype:"3"` - }{ - 1, - } - if e := Unmarshal(Marshal(bad1), &res); e == nil { - t.Errorf("bad struct unmarshaled without error") - } -} - -func randomBytes(out []byte, rand *rand.Rand) { - for i := 0; i < len(out); i++ { - out[i] = byte(rand.Int31()) - } -} - -func randomNameList(rand *rand.Rand) []string { - ret := make([]string, rand.Int31()&15) - for i := range ret { - s := make([]byte, 1+(rand.Int31()&15)) - for j := range s { - s[j] = 'a' + uint8(rand.Int31()&15) - } - ret[i] = string(s) - } - return ret -} - -func randomInt(rand *rand.Rand) *big.Int { - return new(big.Int).SetInt64(int64(int32(rand.Uint32()))) -} - -func (*kexInitMsg) Generate(rand *rand.Rand, size int) reflect.Value { - ki := &kexInitMsg{} - randomBytes(ki.Cookie[:], rand) - ki.KexAlgos = randomNameList(rand) - ki.ServerHostKeyAlgos = randomNameList(rand) - ki.CiphersClientServer = randomNameList(rand) - ki.CiphersServerClient = randomNameList(rand) - ki.MACsClientServer = randomNameList(rand) - ki.MACsServerClient = randomNameList(rand) - ki.CompressionClientServer = randomNameList(rand) - ki.CompressionServerClient = randomNameList(rand) - ki.LanguagesClientServer = randomNameList(rand) - ki.LanguagesServerClient = randomNameList(rand) - if rand.Int31()&1 == 1 { - ki.FirstKexFollows = true - } - return reflect.ValueOf(ki) -} - -func (*kexDHInitMsg) Generate(rand *rand.Rand, size int) reflect.Value { - dhi := &kexDHInitMsg{} - dhi.X = randomInt(rand) - return reflect.ValueOf(dhi) -} - -var ( - _kexInitMsg = new(kexInitMsg).Generate(rand.New(rand.NewSource(0)), 10).Elem().Interface() - _kexDHInitMsg = new(kexDHInitMsg).Generate(rand.New(rand.NewSource(0)), 10).Elem().Interface() - - _kexInit = Marshal(_kexInitMsg) - _kexDHInit = Marshal(_kexDHInitMsg) -) - -func BenchmarkMarshalKexInitMsg(b *testing.B) { - for i := 0; i < b.N; i++ { - Marshal(_kexInitMsg) - } -} - -func BenchmarkUnmarshalKexInitMsg(b *testing.B) { - m := new(kexInitMsg) - for i := 0; i < b.N; i++ { - Unmarshal(_kexInit, m) - } -} - -func BenchmarkMarshalKexDHInitMsg(b *testing.B) { - for i := 0; i < b.N; i++ { - Marshal(_kexDHInitMsg) - } -} - -func BenchmarkUnmarshalKexDHInitMsg(b *testing.B) { - m := new(kexDHInitMsg) - for i := 0; i < b.N; i++ { - Unmarshal(_kexDHInit, m) - } -} diff --git a/vendor/golang.org/x/crypto/ssh/mux_test.go b/vendor/golang.org/x/crypto/ssh/mux_test.go deleted file mode 100644 index 25d2181d6215..000000000000 --- a/vendor/golang.org/x/crypto/ssh/mux_test.go +++ /dev/null @@ -1,505 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -import ( - "io" - "io/ioutil" - "sync" - "testing" -) - -func muxPair() (*mux, *mux) { - a, b := memPipe() - - s := newMux(a) - c := newMux(b) - - return s, c -} - -// Returns both ends of a channel, and the mux for the the 2nd -// channel. -func channelPair(t *testing.T) (*channel, *channel, *mux) { - c, s := muxPair() - - res := make(chan *channel, 1) - go func() { - newCh, ok := <-s.incomingChannels - if !ok { - t.Fatalf("No incoming channel") - } - if newCh.ChannelType() != "chan" { - t.Fatalf("got type %q want chan", newCh.ChannelType()) - } - ch, _, err := newCh.Accept() - if err != nil { - t.Fatalf("Accept %v", err) - } - res <- ch.(*channel) - }() - - ch, err := c.openChannel("chan", nil) - if err != nil { - t.Fatalf("OpenChannel: %v", err) - } - - return <-res, ch, c -} - -// Test that stderr and stdout can be addressed from different -// goroutines. This is intended for use with the race detector. -func TestMuxChannelExtendedThreadSafety(t *testing.T) { - writer, reader, mux := channelPair(t) - defer writer.Close() - defer reader.Close() - defer mux.Close() - - var wr, rd sync.WaitGroup - magic := "hello world" - - wr.Add(2) - go func() { - io.WriteString(writer, magic) - wr.Done() - }() - go func() { - io.WriteString(writer.Stderr(), magic) - wr.Done() - }() - - rd.Add(2) - go func() { - c, err := ioutil.ReadAll(reader) - if string(c) != magic { - t.Fatalf("stdout read got %q, want %q (error %s)", c, magic, err) - } - rd.Done() - }() - go func() { - c, err := ioutil.ReadAll(reader.Stderr()) - if string(c) != magic { - t.Fatalf("stderr read got %q, want %q (error %s)", c, magic, err) - } - rd.Done() - }() - - wr.Wait() - writer.CloseWrite() - rd.Wait() -} - -func TestMuxReadWrite(t *testing.T) { - s, c, mux := channelPair(t) - defer s.Close() - defer c.Close() - defer mux.Close() - - magic := "hello world" - magicExt := "hello stderr" - go func() { - _, err := s.Write([]byte(magic)) - if err != nil { - t.Fatalf("Write: %v", err) - } - _, err = s.Extended(1).Write([]byte(magicExt)) - if err != nil { - t.Fatalf("Write: %v", err) - } - err = s.Close() - if err != nil { - t.Fatalf("Close: %v", err) - } - }() - - var buf [1024]byte - n, err := c.Read(buf[:]) - if err != nil { - t.Fatalf("server Read: %v", err) - } - got := string(buf[:n]) - if got != magic { - t.Fatalf("server: got %q want %q", got, magic) - } - - n, err = c.Extended(1).Read(buf[:]) - if err != nil { - t.Fatalf("server Read: %v", err) - } - - got = string(buf[:n]) - if got != magicExt { - t.Fatalf("server: got %q want %q", got, magic) - } -} - -func TestMuxChannelOverflow(t *testing.T) { - reader, writer, mux := channelPair(t) - defer reader.Close() - defer writer.Close() - defer mux.Close() - - wDone := make(chan int, 1) - go func() { - if _, err := writer.Write(make([]byte, channelWindowSize)); err != nil { - t.Errorf("could not fill window: %v", err) - } - writer.Write(make([]byte, 1)) - wDone <- 1 - }() - writer.remoteWin.waitWriterBlocked() - - // Send 1 byte. - packet := make([]byte, 1+4+4+1) - packet[0] = msgChannelData - marshalUint32(packet[1:], writer.remoteId) - marshalUint32(packet[5:], uint32(1)) - packet[9] = 42 - - if err := writer.mux.conn.writePacket(packet); err != nil { - t.Errorf("could not send packet") - } - if _, err := reader.SendRequest("hello", true, nil); err == nil { - t.Errorf("SendRequest succeeded.") - } - <-wDone -} - -func TestMuxChannelCloseWriteUnblock(t *testing.T) { - reader, writer, mux := channelPair(t) - defer reader.Close() - defer writer.Close() - defer mux.Close() - - wDone := make(chan int, 1) - go func() { - if _, err := writer.Write(make([]byte, channelWindowSize)); err != nil { - t.Errorf("could not fill window: %v", err) - } - if _, err := writer.Write(make([]byte, 1)); err != io.EOF { - t.Errorf("got %v, want EOF for unblock write", err) - } - wDone <- 1 - }() - - writer.remoteWin.waitWriterBlocked() - reader.Close() - <-wDone -} - -func TestMuxConnectionCloseWriteUnblock(t *testing.T) { - reader, writer, mux := channelPair(t) - defer reader.Close() - defer writer.Close() - defer mux.Close() - - wDone := make(chan int, 1) - go func() { - if _, err := writer.Write(make([]byte, channelWindowSize)); err != nil { - t.Errorf("could not fill window: %v", err) - } - if _, err := writer.Write(make([]byte, 1)); err != io.EOF { - t.Errorf("got %v, want EOF for unblock write", err) - } - wDone <- 1 - }() - - writer.remoteWin.waitWriterBlocked() - mux.Close() - <-wDone -} - -func TestMuxReject(t *testing.T) { - client, server := muxPair() - defer server.Close() - defer client.Close() - - go func() { - ch, ok := <-server.incomingChannels - if !ok { - t.Fatalf("Accept") - } - if ch.ChannelType() != "ch" || string(ch.ExtraData()) != "extra" { - t.Fatalf("unexpected channel: %q, %q", ch.ChannelType(), ch.ExtraData()) - } - ch.Reject(RejectionReason(42), "message") - }() - - ch, err := client.openChannel("ch", []byte("extra")) - if ch != nil { - t.Fatal("openChannel not rejected") - } - - ocf, ok := err.(*OpenChannelError) - if !ok { - t.Errorf("got %#v want *OpenChannelError", err) - } else if ocf.Reason != 42 || ocf.Message != "message" { - t.Errorf("got %#v, want {Reason: 42, Message: %q}", ocf, "message") - } - - want := "ssh: rejected: unknown reason 42 (message)" - if err.Error() != want { - t.Errorf("got %q, want %q", err.Error(), want) - } -} - -func TestMuxChannelRequest(t *testing.T) { - client, server, mux := channelPair(t) - defer server.Close() - defer client.Close() - defer mux.Close() - - var received int - var wg sync.WaitGroup - wg.Add(1) - go func() { - for r := range server.incomingRequests { - received++ - r.Reply(r.Type == "yes", nil) - } - wg.Done() - }() - _, err := client.SendRequest("yes", false, nil) - if err != nil { - t.Fatalf("SendRequest: %v", err) - } - ok, err := client.SendRequest("yes", true, nil) - if err != nil { - t.Fatalf("SendRequest: %v", err) - } - - if !ok { - t.Errorf("SendRequest(yes): %v", ok) - - } - - ok, err = client.SendRequest("no", true, nil) - if err != nil { - t.Fatalf("SendRequest: %v", err) - } - if ok { - t.Errorf("SendRequest(no): %v", ok) - - } - - client.Close() - wg.Wait() - - if received != 3 { - t.Errorf("got %d requests, want %d", received, 3) - } -} - -func TestMuxGlobalRequest(t *testing.T) { - clientMux, serverMux := muxPair() - defer serverMux.Close() - defer clientMux.Close() - - var seen bool - go func() { - for r := range serverMux.incomingRequests { - seen = seen || r.Type == "peek" - if r.WantReply { - err := r.Reply(r.Type == "yes", - append([]byte(r.Type), r.Payload...)) - if err != nil { - t.Errorf("AckRequest: %v", err) - } - } - } - }() - - _, _, err := clientMux.SendRequest("peek", false, nil) - if err != nil { - t.Errorf("SendRequest: %v", err) - } - - ok, data, err := clientMux.SendRequest("yes", true, []byte("a")) - if !ok || string(data) != "yesa" || err != nil { - t.Errorf("SendRequest(\"yes\", true, \"a\"): %v %v %v", - ok, data, err) - } - if ok, data, err := clientMux.SendRequest("yes", true, []byte("a")); !ok || string(data) != "yesa" || err != nil { - t.Errorf("SendRequest(\"yes\", true, \"a\"): %v %v %v", - ok, data, err) - } - - if ok, data, err := clientMux.SendRequest("no", true, []byte("a")); ok || string(data) != "noa" || err != nil { - t.Errorf("SendRequest(\"no\", true, \"a\"): %v %v %v", - ok, data, err) - } - - if !seen { - t.Errorf("never saw 'peek' request") - } -} - -func TestMuxGlobalRequestUnblock(t *testing.T) { - clientMux, serverMux := muxPair() - defer serverMux.Close() - defer clientMux.Close() - - result := make(chan error, 1) - go func() { - _, _, err := clientMux.SendRequest("hello", true, nil) - result <- err - }() - - <-serverMux.incomingRequests - serverMux.conn.Close() - err := <-result - - if err != io.EOF { - t.Errorf("want EOF, got %v", io.EOF) - } -} - -func TestMuxChannelRequestUnblock(t *testing.T) { - a, b, connB := channelPair(t) - defer a.Close() - defer b.Close() - defer connB.Close() - - result := make(chan error, 1) - go func() { - _, err := a.SendRequest("hello", true, nil) - result <- err - }() - - <-b.incomingRequests - connB.conn.Close() - err := <-result - - if err != io.EOF { - t.Errorf("want EOF, got %v", err) - } -} - -func TestMuxCloseChannel(t *testing.T) { - r, w, mux := channelPair(t) - defer mux.Close() - defer r.Close() - defer w.Close() - - result := make(chan error, 1) - go func() { - var b [1024]byte - _, err := r.Read(b[:]) - result <- err - }() - if err := w.Close(); err != nil { - t.Errorf("w.Close: %v", err) - } - - if _, err := w.Write([]byte("hello")); err != io.EOF { - t.Errorf("got err %v, want io.EOF after Close", err) - } - - if err := <-result; err != io.EOF { - t.Errorf("got %v (%T), want io.EOF", err, err) - } -} - -func TestMuxCloseWriteChannel(t *testing.T) { - r, w, mux := channelPair(t) - defer mux.Close() - - result := make(chan error, 1) - go func() { - var b [1024]byte - _, err := r.Read(b[:]) - result <- err - }() - if err := w.CloseWrite(); err != nil { - t.Errorf("w.CloseWrite: %v", err) - } - - if _, err := w.Write([]byte("hello")); err != io.EOF { - t.Errorf("got err %v, want io.EOF after CloseWrite", err) - } - - if err := <-result; err != io.EOF { - t.Errorf("got %v (%T), want io.EOF", err, err) - } -} - -func TestMuxInvalidRecord(t *testing.T) { - a, b := muxPair() - defer a.Close() - defer b.Close() - - packet := make([]byte, 1+4+4+1) - packet[0] = msgChannelData - marshalUint32(packet[1:], 29348723 /* invalid channel id */) - marshalUint32(packet[5:], 1) - packet[9] = 42 - - a.conn.writePacket(packet) - go a.SendRequest("hello", false, nil) - // 'a' wrote an invalid packet, so 'b' has exited. - req, ok := <-b.incomingRequests - if ok { - t.Errorf("got request %#v after receiving invalid packet", req) - } -} - -func TestZeroWindowAdjust(t *testing.T) { - a, b, mux := channelPair(t) - defer a.Close() - defer b.Close() - defer mux.Close() - - go func() { - io.WriteString(a, "hello") - // bogus adjust. - a.sendMessage(windowAdjustMsg{}) - io.WriteString(a, "world") - a.Close() - }() - - want := "helloworld" - c, _ := ioutil.ReadAll(b) - if string(c) != want { - t.Errorf("got %q want %q", c, want) - } -} - -func TestMuxMaxPacketSize(t *testing.T) { - a, b, mux := channelPair(t) - defer a.Close() - defer b.Close() - defer mux.Close() - - large := make([]byte, a.maxRemotePayload+1) - packet := make([]byte, 1+4+4+1+len(large)) - packet[0] = msgChannelData - marshalUint32(packet[1:], a.remoteId) - marshalUint32(packet[5:], uint32(len(large))) - packet[9] = 42 - - if err := a.mux.conn.writePacket(packet); err != nil { - t.Errorf("could not send packet") - } - - go a.SendRequest("hello", false, nil) - - _, ok := <-b.incomingRequests - if ok { - t.Errorf("connection still alive after receiving large packet.") - } -} - -// Don't ship code with debug=true. -func TestDebug(t *testing.T) { - if debugMux { - t.Error("mux debug switched on") - } - if debugHandshake { - t.Error("handshake debug switched on") - } - if debugTransport { - t.Error("transport debug switched on") - } -} diff --git a/vendor/golang.org/x/crypto/ssh/session_test.go b/vendor/golang.org/x/crypto/ssh/session_test.go deleted file mode 100644 index 7dce6dd699be..000000000000 --- a/vendor/golang.org/x/crypto/ssh/session_test.go +++ /dev/null @@ -1,774 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -// Session tests. - -import ( - "bytes" - crypto_rand "crypto/rand" - "errors" - "io" - "io/ioutil" - "math/rand" - "net" - "testing" - - "golang.org/x/crypto/ssh/terminal" -) - -type serverType func(Channel, <-chan *Request, *testing.T) - -// dial constructs a new test server and returns a *ClientConn. -func dial(handler serverType, t *testing.T) *Client { - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - - go func() { - defer c1.Close() - conf := ServerConfig{ - NoClientAuth: true, - } - conf.AddHostKey(testSigners["rsa"]) - - _, chans, reqs, err := NewServerConn(c1, &conf) - if err != nil { - t.Fatalf("Unable to handshake: %v", err) - } - go DiscardRequests(reqs) - - for newCh := range chans { - if newCh.ChannelType() != "session" { - newCh.Reject(UnknownChannelType, "unknown channel type") - continue - } - - ch, inReqs, err := newCh.Accept() - if err != nil { - t.Errorf("Accept: %v", err) - continue - } - go func() { - handler(ch, inReqs, t) - }() - } - }() - - config := &ClientConfig{ - User: "testuser", - HostKeyCallback: InsecureIgnoreHostKey(), - } - - conn, chans, reqs, err := NewClientConn(c2, "", config) - if err != nil { - t.Fatalf("unable to dial remote side: %v", err) - } - - return NewClient(conn, chans, reqs) -} - -// Test a simple string is returned to session.Stdout. -func TestSessionShell(t *testing.T) { - conn := dial(shellHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - stdout := new(bytes.Buffer) - session.Stdout = stdout - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %s", err) - } - if err := session.Wait(); err != nil { - t.Fatalf("Remote command did not exit cleanly: %v", err) - } - actual := stdout.String() - if actual != "golang" { - t.Fatalf("Remote shell did not return expected string: expected=golang, actual=%s", actual) - } -} - -// TODO(dfc) add support for Std{in,err}Pipe when the Server supports it. - -// Test a simple string is returned via StdoutPipe. -func TestSessionStdoutPipe(t *testing.T) { - conn := dial(shellHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - stdout, err := session.StdoutPipe() - if err != nil { - t.Fatalf("Unable to request StdoutPipe(): %v", err) - } - var buf bytes.Buffer - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - done := make(chan bool, 1) - go func() { - if _, err := io.Copy(&buf, stdout); err != nil { - t.Errorf("Copy of stdout failed: %v", err) - } - done <- true - }() - if err := session.Wait(); err != nil { - t.Fatalf("Remote command did not exit cleanly: %v", err) - } - <-done - actual := buf.String() - if actual != "golang" { - t.Fatalf("Remote shell did not return expected string: expected=golang, actual=%s", actual) - } -} - -// Test that a simple string is returned via the Output helper, -// and that stderr is discarded. -func TestSessionOutput(t *testing.T) { - conn := dial(fixedOutputHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - - buf, err := session.Output("") // cmd is ignored by fixedOutputHandler - if err != nil { - t.Error("Remote command did not exit cleanly:", err) - } - w := "this-is-stdout." - g := string(buf) - if g != w { - t.Error("Remote command did not return expected string:") - t.Logf("want %q", w) - t.Logf("got %q", g) - } -} - -// Test that both stdout and stderr are returned -// via the CombinedOutput helper. -func TestSessionCombinedOutput(t *testing.T) { - conn := dial(fixedOutputHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - - buf, err := session.CombinedOutput("") // cmd is ignored by fixedOutputHandler - if err != nil { - t.Error("Remote command did not exit cleanly:", err) - } - const stdout = "this-is-stdout." - const stderr = "this-is-stderr." - g := string(buf) - if g != stdout+stderr && g != stderr+stdout { - t.Error("Remote command did not return expected string:") - t.Logf("want %q, or %q", stdout+stderr, stderr+stdout) - t.Logf("got %q", g) - } -} - -// Test non-0 exit status is returned correctly. -func TestExitStatusNonZero(t *testing.T) { - conn := dial(exitStatusNonZeroHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err == nil { - t.Fatalf("expected command to fail but it didn't") - } - e, ok := err.(*ExitError) - if !ok { - t.Fatalf("expected *ExitError but got %T", err) - } - if e.ExitStatus() != 15 { - t.Fatalf("expected command to exit with 15 but got %v", e.ExitStatus()) - } -} - -// Test 0 exit status is returned correctly. -func TestExitStatusZero(t *testing.T) { - conn := dial(exitStatusZeroHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err != nil { - t.Fatalf("expected nil but got %v", err) - } -} - -// Test exit signal and status are both returned correctly. -func TestExitSignalAndStatus(t *testing.T) { - conn := dial(exitSignalAndStatusHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err == nil { - t.Fatalf("expected command to fail but it didn't") - } - e, ok := err.(*ExitError) - if !ok { - t.Fatalf("expected *ExitError but got %T", err) - } - if e.Signal() != "TERM" || e.ExitStatus() != 15 { - t.Fatalf("expected command to exit with signal TERM and status 15 but got signal %s and status %v", e.Signal(), e.ExitStatus()) - } -} - -// Test exit signal and status are both returned correctly. -func TestKnownExitSignalOnly(t *testing.T) { - conn := dial(exitSignalHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err == nil { - t.Fatalf("expected command to fail but it didn't") - } - e, ok := err.(*ExitError) - if !ok { - t.Fatalf("expected *ExitError but got %T", err) - } - if e.Signal() != "TERM" || e.ExitStatus() != 143 { - t.Fatalf("expected command to exit with signal TERM and status 143 but got signal %s and status %v", e.Signal(), e.ExitStatus()) - } -} - -// Test exit signal and status are both returned correctly. -func TestUnknownExitSignal(t *testing.T) { - conn := dial(exitSignalUnknownHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err == nil { - t.Fatalf("expected command to fail but it didn't") - } - e, ok := err.(*ExitError) - if !ok { - t.Fatalf("expected *ExitError but got %T", err) - } - if e.Signal() != "SYS" || e.ExitStatus() != 128 { - t.Fatalf("expected command to exit with signal SYS and status 128 but got signal %s and status %v", e.Signal(), e.ExitStatus()) - } -} - -func TestExitWithoutStatusOrSignal(t *testing.T) { - conn := dial(exitWithoutSignalOrStatus, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err == nil { - t.Fatalf("expected command to fail but it didn't") - } - if _, ok := err.(*ExitMissingError); !ok { - t.Fatalf("got %T want *ExitMissingError", err) - } -} - -// windowTestBytes is the number of bytes that we'll send to the SSH server. -const windowTestBytes = 16000 * 200 - -// TestServerWindow writes random data to the server. The server is expected to echo -// the same data back, which is compared against the original. -func TestServerWindow(t *testing.T) { - origBuf := bytes.NewBuffer(make([]byte, 0, windowTestBytes)) - io.CopyN(origBuf, crypto_rand.Reader, windowTestBytes) - origBytes := origBuf.Bytes() - - conn := dial(echoHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatal(err) - } - defer session.Close() - result := make(chan []byte) - - go func() { - defer close(result) - echoedBuf := bytes.NewBuffer(make([]byte, 0, windowTestBytes)) - serverStdout, err := session.StdoutPipe() - if err != nil { - t.Errorf("StdoutPipe failed: %v", err) - return - } - n, err := copyNRandomly("stdout", echoedBuf, serverStdout, windowTestBytes) - if err != nil && err != io.EOF { - t.Errorf("Read only %d bytes from server, expected %d: %v", n, windowTestBytes, err) - } - result <- echoedBuf.Bytes() - }() - - serverStdin, err := session.StdinPipe() - if err != nil { - t.Fatalf("StdinPipe failed: %v", err) - } - written, err := copyNRandomly("stdin", serverStdin, origBuf, windowTestBytes) - if err != nil { - t.Fatalf("failed to copy origBuf to serverStdin: %v", err) - } - if written != windowTestBytes { - t.Fatalf("Wrote only %d of %d bytes to server", written, windowTestBytes) - } - - echoedBytes := <-result - - if !bytes.Equal(origBytes, echoedBytes) { - t.Fatalf("Echoed buffer differed from original, orig %d, echoed %d", len(origBytes), len(echoedBytes)) - } -} - -// Verify the client can handle a keepalive packet from the server. -func TestClientHandlesKeepalives(t *testing.T) { - conn := dial(channelKeepaliveSender, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatal(err) - } - defer session.Close() - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err != nil { - t.Fatalf("expected nil but got: %v", err) - } -} - -type exitStatusMsg struct { - Status uint32 -} - -type exitSignalMsg struct { - Signal string - CoreDumped bool - Errmsg string - Lang string -} - -func handleTerminalRequests(in <-chan *Request) { - for req := range in { - ok := false - switch req.Type { - case "shell": - ok = true - if len(req.Payload) > 0 { - // We don't accept any commands, only the default shell. - ok = false - } - case "env": - ok = true - } - req.Reply(ok, nil) - } -} - -func newServerShell(ch Channel, in <-chan *Request, prompt string) *terminal.Terminal { - term := terminal.NewTerminal(ch, prompt) - go handleTerminalRequests(in) - return term -} - -func exitStatusZeroHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - // this string is returned to stdout - shell := newServerShell(ch, in, "> ") - readLine(shell, t) - sendStatus(0, ch, t) -} - -func exitStatusNonZeroHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - shell := newServerShell(ch, in, "> ") - readLine(shell, t) - sendStatus(15, ch, t) -} - -func exitSignalAndStatusHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - shell := newServerShell(ch, in, "> ") - readLine(shell, t) - sendStatus(15, ch, t) - sendSignal("TERM", ch, t) -} - -func exitSignalHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - shell := newServerShell(ch, in, "> ") - readLine(shell, t) - sendSignal("TERM", ch, t) -} - -func exitSignalUnknownHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - shell := newServerShell(ch, in, "> ") - readLine(shell, t) - sendSignal("SYS", ch, t) -} - -func exitWithoutSignalOrStatus(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - shell := newServerShell(ch, in, "> ") - readLine(shell, t) -} - -func shellHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - // this string is returned to stdout - shell := newServerShell(ch, in, "golang") - readLine(shell, t) - sendStatus(0, ch, t) -} - -// Ignores the command, writes fixed strings to stderr and stdout. -// Strings are "this-is-stdout." and "this-is-stderr.". -func fixedOutputHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - _, err := ch.Read(nil) - - req, ok := <-in - if !ok { - t.Fatalf("error: expected channel request, got: %#v", err) - return - } - - // ignore request, always send some text - req.Reply(true, nil) - - _, err = io.WriteString(ch, "this-is-stdout.") - if err != nil { - t.Fatalf("error writing on server: %v", err) - } - _, err = io.WriteString(ch.Stderr(), "this-is-stderr.") - if err != nil { - t.Fatalf("error writing on server: %v", err) - } - sendStatus(0, ch, t) -} - -func readLine(shell *terminal.Terminal, t *testing.T) { - if _, err := shell.ReadLine(); err != nil && err != io.EOF { - t.Errorf("unable to read line: %v", err) - } -} - -func sendStatus(status uint32, ch Channel, t *testing.T) { - msg := exitStatusMsg{ - Status: status, - } - if _, err := ch.SendRequest("exit-status", false, Marshal(&msg)); err != nil { - t.Errorf("unable to send status: %v", err) - } -} - -func sendSignal(signal string, ch Channel, t *testing.T) { - sig := exitSignalMsg{ - Signal: signal, - CoreDumped: false, - Errmsg: "Process terminated", - Lang: "en-GB-oed", - } - if _, err := ch.SendRequest("exit-signal", false, Marshal(&sig)); err != nil { - t.Errorf("unable to send signal: %v", err) - } -} - -func discardHandler(ch Channel, t *testing.T) { - defer ch.Close() - io.Copy(ioutil.Discard, ch) -} - -func echoHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - if n, err := copyNRandomly("echohandler", ch, ch, windowTestBytes); err != nil { - t.Errorf("short write, wrote %d, expected %d: %v ", n, windowTestBytes, err) - } -} - -// copyNRandomly copies n bytes from src to dst. It uses a variable, and random, -// buffer size to exercise more code paths. -func copyNRandomly(title string, dst io.Writer, src io.Reader, n int) (int, error) { - var ( - buf = make([]byte, 32*1024) - written int - remaining = n - ) - for remaining > 0 { - l := rand.Intn(1 << 15) - if remaining < l { - l = remaining - } - nr, er := src.Read(buf[:l]) - nw, ew := dst.Write(buf[:nr]) - remaining -= nw - written += nw - if ew != nil { - return written, ew - } - if nr != nw { - return written, io.ErrShortWrite - } - if er != nil && er != io.EOF { - return written, er - } - } - return written, nil -} - -func channelKeepaliveSender(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - shell := newServerShell(ch, in, "> ") - readLine(shell, t) - if _, err := ch.SendRequest("keepalive@openssh.com", true, nil); err != nil { - t.Errorf("unable to send channel keepalive request: %v", err) - } - sendStatus(0, ch, t) -} - -func TestClientWriteEOF(t *testing.T) { - conn := dial(simpleEchoHandler, t) - defer conn.Close() - - session, err := conn.NewSession() - if err != nil { - t.Fatal(err) - } - defer session.Close() - stdin, err := session.StdinPipe() - if err != nil { - t.Fatalf("StdinPipe failed: %v", err) - } - stdout, err := session.StdoutPipe() - if err != nil { - t.Fatalf("StdoutPipe failed: %v", err) - } - - data := []byte(`0000`) - _, err = stdin.Write(data) - if err != nil { - t.Fatalf("Write failed: %v", err) - } - stdin.Close() - - res, err := ioutil.ReadAll(stdout) - if err != nil { - t.Fatalf("Read failed: %v", err) - } - - if !bytes.Equal(data, res) { - t.Fatalf("Read differed from write, wrote: %v, read: %v", data, res) - } -} - -func simpleEchoHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - data, err := ioutil.ReadAll(ch) - if err != nil { - t.Errorf("handler read error: %v", err) - } - _, err = ch.Write(data) - if err != nil { - t.Errorf("handler write error: %v", err) - } -} - -func TestSessionID(t *testing.T) { - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - serverID := make(chan []byte, 1) - clientID := make(chan []byte, 1) - - serverConf := &ServerConfig{ - NoClientAuth: true, - } - serverConf.AddHostKey(testSigners["ecdsa"]) - clientConf := &ClientConfig{ - HostKeyCallback: InsecureIgnoreHostKey(), - User: "user", - } - - go func() { - conn, chans, reqs, err := NewServerConn(c1, serverConf) - if err != nil { - t.Fatalf("server handshake: %v", err) - } - serverID <- conn.SessionID() - go DiscardRequests(reqs) - for ch := range chans { - ch.Reject(Prohibited, "") - } - }() - - go func() { - conn, chans, reqs, err := NewClientConn(c2, "", clientConf) - if err != nil { - t.Fatalf("client handshake: %v", err) - } - clientID <- conn.SessionID() - go DiscardRequests(reqs) - for ch := range chans { - ch.Reject(Prohibited, "") - } - }() - - s := <-serverID - c := <-clientID - if bytes.Compare(s, c) != 0 { - t.Errorf("server session ID (%x) != client session ID (%x)", s, c) - } else if len(s) == 0 { - t.Errorf("client and server SessionID were empty.") - } -} - -type noReadConn struct { - readSeen bool - net.Conn -} - -func (c *noReadConn) Close() error { - return nil -} - -func (c *noReadConn) Read(b []byte) (int, error) { - c.readSeen = true - return 0, errors.New("noReadConn error") -} - -func TestInvalidServerConfiguration(t *testing.T) { - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - serveConn := noReadConn{Conn: c1} - serverConf := &ServerConfig{} - - NewServerConn(&serveConn, serverConf) - if serveConn.readSeen { - t.Fatalf("NewServerConn attempted to Read() from Conn while configuration is missing host key") - } - - serverConf.AddHostKey(testSigners["ecdsa"]) - - NewServerConn(&serveConn, serverConf) - if serveConn.readSeen { - t.Fatalf("NewServerConn attempted to Read() from Conn while configuration is missing authentication method") - } -} - -func TestHostKeyAlgorithms(t *testing.T) { - serverConf := &ServerConfig{ - NoClientAuth: true, - } - serverConf.AddHostKey(testSigners["rsa"]) - serverConf.AddHostKey(testSigners["ecdsa"]) - - connect := func(clientConf *ClientConfig, want string) { - var alg string - clientConf.HostKeyCallback = func(h string, a net.Addr, key PublicKey) error { - alg = key.Type() - return nil - } - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - go NewServerConn(c1, serverConf) - _, _, _, err = NewClientConn(c2, "", clientConf) - if err != nil { - t.Fatalf("NewClientConn: %v", err) - } - if alg != want { - t.Errorf("selected key algorithm %s, want %s", alg, want) - } - } - - // By default, we get the preferred algorithm, which is ECDSA 256. - - clientConf := &ClientConfig{ - HostKeyCallback: InsecureIgnoreHostKey(), - } - connect(clientConf, KeyAlgoECDSA256) - - // Client asks for RSA explicitly. - clientConf.HostKeyAlgorithms = []string{KeyAlgoRSA} - connect(clientConf, KeyAlgoRSA) - - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - go NewServerConn(c1, serverConf) - clientConf.HostKeyAlgorithms = []string{"nonexistent-hostkey-algo"} - _, _, _, err = NewClientConn(c2, "", clientConf) - if err == nil { - t.Fatal("succeeded connecting with unknown hostkey algorithm") - } -} diff --git a/vendor/golang.org/x/crypto/ssh/tcpip_test.go b/vendor/golang.org/x/crypto/ssh/tcpip_test.go deleted file mode 100644 index f1265cb4964e..000000000000 --- a/vendor/golang.org/x/crypto/ssh/tcpip_test.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -import ( - "testing" -) - -func TestAutoPortListenBroken(t *testing.T) { - broken := "SSH-2.0-OpenSSH_5.9hh11" - works := "SSH-2.0-OpenSSH_6.1" - if !isBrokenOpenSSHVersion(broken) { - t.Errorf("version %q not marked as broken", broken) - } - if isBrokenOpenSSHVersion(works) { - t.Errorf("version %q marked as broken", works) - } -} diff --git a/vendor/golang.org/x/crypto/ssh/testdata_test.go b/vendor/golang.org/x/crypto/ssh/testdata_test.go deleted file mode 100644 index 2da8c79dc64a..000000000000 --- a/vendor/golang.org/x/crypto/ssh/testdata_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// IMPLEMENTATION NOTE: To avoid a package loop, this file is in three places: -// ssh/, ssh/agent, and ssh/test/. It should be kept in sync across all three -// instances. - -package ssh - -import ( - "crypto/rand" - "fmt" - - "golang.org/x/crypto/ssh/testdata" -) - -var ( - testPrivateKeys map[string]interface{} - testSigners map[string]Signer - testPublicKeys map[string]PublicKey -) - -func init() { - var err error - - n := len(testdata.PEMBytes) - testPrivateKeys = make(map[string]interface{}, n) - testSigners = make(map[string]Signer, n) - testPublicKeys = make(map[string]PublicKey, n) - for t, k := range testdata.PEMBytes { - testPrivateKeys[t], err = ParseRawPrivateKey(k) - if err != nil { - panic(fmt.Sprintf("Unable to parse test key %s: %v", t, err)) - } - testSigners[t], err = NewSignerFromKey(testPrivateKeys[t]) - if err != nil { - panic(fmt.Sprintf("Unable to create signer for test key %s: %v", t, err)) - } - testPublicKeys[t] = testSigners[t].PublicKey() - } - - // Create a cert and sign it for use in tests. - testCert := &Certificate{ - Nonce: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil - ValidPrincipals: []string{"gopher1", "gopher2"}, // increases test coverage - ValidAfter: 0, // unix epoch - ValidBefore: CertTimeInfinity, // The end of currently representable time. - Reserved: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil - Key: testPublicKeys["ecdsa"], - SignatureKey: testPublicKeys["rsa"], - Permissions: Permissions{ - CriticalOptions: map[string]string{}, - Extensions: map[string]string{}, - }, - } - testCert.SignCert(rand.Reader, testSigners["rsa"]) - testPrivateKeys["cert"] = testPrivateKeys["ecdsa"] - testSigners["cert"], err = NewCertSigner(testCert, testSigners["ecdsa"]) - if err != nil { - panic(fmt.Sprintf("Unable to create certificate signer: %v", err)) - } -} diff --git a/vendor/golang.org/x/crypto/ssh/transport_test.go b/vendor/golang.org/x/crypto/ssh/transport_test.go deleted file mode 100644 index 92d83abf93fb..000000000000 --- a/vendor/golang.org/x/crypto/ssh/transport_test.go +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ssh - -import ( - "bytes" - "crypto/rand" - "encoding/binary" - "strings" - "testing" -) - -func TestReadVersion(t *testing.T) { - longversion := strings.Repeat("SSH-2.0-bla", 50)[:253] - cases := map[string]string{ - "SSH-2.0-bla\r\n": "SSH-2.0-bla", - "SSH-2.0-bla\n": "SSH-2.0-bla", - longversion + "\r\n": longversion, - } - - for in, want := range cases { - result, err := readVersion(bytes.NewBufferString(in)) - if err != nil { - t.Errorf("readVersion(%q): %s", in, err) - } - got := string(result) - if got != want { - t.Errorf("got %q, want %q", got, want) - } - } -} - -func TestReadVersionError(t *testing.T) { - longversion := strings.Repeat("SSH-2.0-bla", 50)[:253] - cases := []string{ - longversion + "too-long\r\n", - } - for _, in := range cases { - if _, err := readVersion(bytes.NewBufferString(in)); err == nil { - t.Errorf("readVersion(%q) should have failed", in) - } - } -} - -func TestExchangeVersionsBasic(t *testing.T) { - v := "SSH-2.0-bla" - buf := bytes.NewBufferString(v + "\r\n") - them, err := exchangeVersions(buf, []byte("xyz")) - if err != nil { - t.Errorf("exchangeVersions: %v", err) - } - - if want := "SSH-2.0-bla"; string(them) != want { - t.Errorf("got %q want %q for our version", them, want) - } -} - -func TestExchangeVersions(t *testing.T) { - cases := []string{ - "not\x000allowed", - "not allowed\n", - } - for _, c := range cases { - buf := bytes.NewBufferString("SSH-2.0-bla\r\n") - if _, err := exchangeVersions(buf, []byte(c)); err == nil { - t.Errorf("exchangeVersions(%q): should have failed", c) - } - } -} - -type closerBuffer struct { - bytes.Buffer -} - -func (b *closerBuffer) Close() error { - return nil -} - -func TestTransportMaxPacketWrite(t *testing.T) { - buf := &closerBuffer{} - tr := newTransport(buf, rand.Reader, true) - huge := make([]byte, maxPacket+1) - err := tr.writePacket(huge) - if err == nil { - t.Errorf("transport accepted write for a huge packet.") - } -} - -func TestTransportMaxPacketReader(t *testing.T) { - var header [5]byte - huge := make([]byte, maxPacket+128) - binary.BigEndian.PutUint32(header[0:], uint32(len(huge))) - // padding. - header[4] = 0 - - buf := &closerBuffer{} - buf.Write(header[:]) - buf.Write(huge) - - tr := newTransport(buf, rand.Reader, true) - _, err := tr.readPacket() - if err == nil { - t.Errorf("transport succeeded reading huge packet.") - } else if !strings.Contains(err.Error(), "large") { - t.Errorf("got %q, should mention %q", err.Error(), "large") - } -} diff --git a/vendor/golang.org/x/net/context/BUILD b/vendor/golang.org/x/net/context/BUILD index 98e5bd65dd74..f145939b6535 100644 --- a/vendor/golang.org/x/net/context/BUILD +++ b/vendor/golang.org/x/net/context/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -11,20 +11,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = ["context_test.go"], - importpath = "golang.org/x/net/context", - library = ":go_default_library", -) - -go_test( - name = "go_default_xtest", - srcs = ["withtimeout_test.go"], - importpath = "golang.org/x/net/context_test", - deps = [":go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/golang.org/x/net/context/context_test.go b/vendor/golang.org/x/net/context/context_test.go deleted file mode 100644 index 62844131bd0a..000000000000 --- a/vendor/golang.org/x/net/context/context_test.go +++ /dev/null @@ -1,583 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.7 - -package context - -import ( - "fmt" - "math/rand" - "runtime" - "strings" - "sync" - "testing" - "time" -) - -// otherContext is a Context that's not one of the types defined in context.go. -// This lets us test code paths that differ based on the underlying type of the -// Context. -type otherContext struct { - Context -} - -func TestBackground(t *testing.T) { - c := Background() - if c == nil { - t.Fatalf("Background returned nil") - } - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - if got, want := fmt.Sprint(c), "context.Background"; got != want { - t.Errorf("Background().String() = %q want %q", got, want) - } -} - -func TestTODO(t *testing.T) { - c := TODO() - if c == nil { - t.Fatalf("TODO returned nil") - } - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - if got, want := fmt.Sprint(c), "context.TODO"; got != want { - t.Errorf("TODO().String() = %q want %q", got, want) - } -} - -func TestWithCancel(t *testing.T) { - c1, cancel := WithCancel(Background()) - - if got, want := fmt.Sprint(c1), "context.Background.WithCancel"; got != want { - t.Errorf("c1.String() = %q want %q", got, want) - } - - o := otherContext{c1} - c2, _ := WithCancel(o) - contexts := []Context{c1, o, c2} - - for i, c := range contexts { - if d := c.Done(); d == nil { - t.Errorf("c[%d].Done() == %v want non-nil", i, d) - } - if e := c.Err(); e != nil { - t.Errorf("c[%d].Err() == %v want nil", i, e) - } - - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - } - - cancel() - time.Sleep(100 * time.Millisecond) // let cancelation propagate - - for i, c := range contexts { - select { - case <-c.Done(): - default: - t.Errorf("<-c[%d].Done() blocked, but shouldn't have", i) - } - if e := c.Err(); e != Canceled { - t.Errorf("c[%d].Err() == %v want %v", i, e, Canceled) - } - } -} - -func TestParentFinishesChild(t *testing.T) { - // Context tree: - // parent -> cancelChild - // parent -> valueChild -> timerChild - parent, cancel := WithCancel(Background()) - cancelChild, stop := WithCancel(parent) - defer stop() - valueChild := WithValue(parent, "key", "value") - timerChild, stop := WithTimeout(valueChild, 10000*time.Hour) - defer stop() - - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - case x := <-cancelChild.Done(): - t.Errorf("<-cancelChild.Done() == %v want nothing (it should block)", x) - case x := <-timerChild.Done(): - t.Errorf("<-timerChild.Done() == %v want nothing (it should block)", x) - case x := <-valueChild.Done(): - t.Errorf("<-valueChild.Done() == %v want nothing (it should block)", x) - default: - } - - // The parent's children should contain the two cancelable children. - pc := parent.(*cancelCtx) - cc := cancelChild.(*cancelCtx) - tc := timerChild.(*timerCtx) - pc.mu.Lock() - if len(pc.children) != 2 || !pc.children[cc] || !pc.children[tc] { - t.Errorf("bad linkage: pc.children = %v, want %v and %v", - pc.children, cc, tc) - } - pc.mu.Unlock() - - if p, ok := parentCancelCtx(cc.Context); !ok || p != pc { - t.Errorf("bad linkage: parentCancelCtx(cancelChild.Context) = %v, %v want %v, true", p, ok, pc) - } - if p, ok := parentCancelCtx(tc.Context); !ok || p != pc { - t.Errorf("bad linkage: parentCancelCtx(timerChild.Context) = %v, %v want %v, true", p, ok, pc) - } - - cancel() - - pc.mu.Lock() - if len(pc.children) != 0 { - t.Errorf("pc.cancel didn't clear pc.children = %v", pc.children) - } - pc.mu.Unlock() - - // parent and children should all be finished. - check := func(ctx Context, name string) { - select { - case <-ctx.Done(): - default: - t.Errorf("<-%s.Done() blocked, but shouldn't have", name) - } - if e := ctx.Err(); e != Canceled { - t.Errorf("%s.Err() == %v want %v", name, e, Canceled) - } - } - check(parent, "parent") - check(cancelChild, "cancelChild") - check(valueChild, "valueChild") - check(timerChild, "timerChild") - - // WithCancel should return a canceled context on a canceled parent. - precanceledChild := WithValue(parent, "key", "value") - select { - case <-precanceledChild.Done(): - default: - t.Errorf("<-precanceledChild.Done() blocked, but shouldn't have") - } - if e := precanceledChild.Err(); e != Canceled { - t.Errorf("precanceledChild.Err() == %v want %v", e, Canceled) - } -} - -func TestChildFinishesFirst(t *testing.T) { - cancelable, stop := WithCancel(Background()) - defer stop() - for _, parent := range []Context{Background(), cancelable} { - child, cancel := WithCancel(parent) - - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - case x := <-child.Done(): - t.Errorf("<-child.Done() == %v want nothing (it should block)", x) - default: - } - - cc := child.(*cancelCtx) - pc, pcok := parent.(*cancelCtx) // pcok == false when parent == Background() - if p, ok := parentCancelCtx(cc.Context); ok != pcok || (ok && pc != p) { - t.Errorf("bad linkage: parentCancelCtx(cc.Context) = %v, %v want %v, %v", p, ok, pc, pcok) - } - - if pcok { - pc.mu.Lock() - if len(pc.children) != 1 || !pc.children[cc] { - t.Errorf("bad linkage: pc.children = %v, cc = %v", pc.children, cc) - } - pc.mu.Unlock() - } - - cancel() - - if pcok { - pc.mu.Lock() - if len(pc.children) != 0 { - t.Errorf("child's cancel didn't remove self from pc.children = %v", pc.children) - } - pc.mu.Unlock() - } - - // child should be finished. - select { - case <-child.Done(): - default: - t.Errorf("<-child.Done() blocked, but shouldn't have") - } - if e := child.Err(); e != Canceled { - t.Errorf("child.Err() == %v want %v", e, Canceled) - } - - // parent should not be finished. - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - default: - } - if e := parent.Err(); e != nil { - t.Errorf("parent.Err() == %v want nil", e) - } - } -} - -func testDeadline(c Context, wait time.Duration, t *testing.T) { - select { - case <-time.After(wait): - t.Fatalf("context should have timed out") - case <-c.Done(): - } - if e := c.Err(); e != DeadlineExceeded { - t.Errorf("c.Err() == %v want %v", e, DeadlineExceeded) - } -} - -func TestDeadline(t *testing.T) { - t.Parallel() - const timeUnit = 500 * time.Millisecond - c, _ := WithDeadline(Background(), time.Now().Add(1*timeUnit)) - if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { - t.Errorf("c.String() = %q want prefix %q", got, prefix) - } - testDeadline(c, 2*timeUnit, t) - - c, _ = WithDeadline(Background(), time.Now().Add(1*timeUnit)) - o := otherContext{c} - testDeadline(o, 2*timeUnit, t) - - c, _ = WithDeadline(Background(), time.Now().Add(1*timeUnit)) - o = otherContext{c} - c, _ = WithDeadline(o, time.Now().Add(3*timeUnit)) - testDeadline(c, 2*timeUnit, t) -} - -func TestTimeout(t *testing.T) { - t.Parallel() - const timeUnit = 500 * time.Millisecond - c, _ := WithTimeout(Background(), 1*timeUnit) - if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { - t.Errorf("c.String() = %q want prefix %q", got, prefix) - } - testDeadline(c, 2*timeUnit, t) - - c, _ = WithTimeout(Background(), 1*timeUnit) - o := otherContext{c} - testDeadline(o, 2*timeUnit, t) - - c, _ = WithTimeout(Background(), 1*timeUnit) - o = otherContext{c} - c, _ = WithTimeout(o, 3*timeUnit) - testDeadline(c, 2*timeUnit, t) -} - -func TestCanceledTimeout(t *testing.T) { - t.Parallel() - const timeUnit = 500 * time.Millisecond - c, _ := WithTimeout(Background(), 2*timeUnit) - o := otherContext{c} - c, cancel := WithTimeout(o, 4*timeUnit) - cancel() - time.Sleep(1 * timeUnit) // let cancelation propagate - select { - case <-c.Done(): - default: - t.Errorf("<-c.Done() blocked, but shouldn't have") - } - if e := c.Err(); e != Canceled { - t.Errorf("c.Err() == %v want %v", e, Canceled) - } -} - -type key1 int -type key2 int - -var k1 = key1(1) -var k2 = key2(1) // same int as k1, different type -var k3 = key2(3) // same type as k2, different int - -func TestValues(t *testing.T) { - check := func(c Context, nm, v1, v2, v3 string) { - if v, ok := c.Value(k1).(string); ok == (len(v1) == 0) || v != v1 { - t.Errorf(`%s.Value(k1).(string) = %q, %t want %q, %t`, nm, v, ok, v1, len(v1) != 0) - } - if v, ok := c.Value(k2).(string); ok == (len(v2) == 0) || v != v2 { - t.Errorf(`%s.Value(k2).(string) = %q, %t want %q, %t`, nm, v, ok, v2, len(v2) != 0) - } - if v, ok := c.Value(k3).(string); ok == (len(v3) == 0) || v != v3 { - t.Errorf(`%s.Value(k3).(string) = %q, %t want %q, %t`, nm, v, ok, v3, len(v3) != 0) - } - } - - c0 := Background() - check(c0, "c0", "", "", "") - - c1 := WithValue(Background(), k1, "c1k1") - check(c1, "c1", "c1k1", "", "") - - if got, want := fmt.Sprint(c1), `context.Background.WithValue(1, "c1k1")`; got != want { - t.Errorf("c.String() = %q want %q", got, want) - } - - c2 := WithValue(c1, k2, "c2k2") - check(c2, "c2", "c1k1", "c2k2", "") - - c3 := WithValue(c2, k3, "c3k3") - check(c3, "c2", "c1k1", "c2k2", "c3k3") - - c4 := WithValue(c3, k1, nil) - check(c4, "c4", "", "c2k2", "c3k3") - - o0 := otherContext{Background()} - check(o0, "o0", "", "", "") - - o1 := otherContext{WithValue(Background(), k1, "c1k1")} - check(o1, "o1", "c1k1", "", "") - - o2 := WithValue(o1, k2, "o2k2") - check(o2, "o2", "c1k1", "o2k2", "") - - o3 := otherContext{c4} - check(o3, "o3", "", "c2k2", "c3k3") - - o4 := WithValue(o3, k3, nil) - check(o4, "o4", "", "c2k2", "") -} - -func TestAllocs(t *testing.T) { - bg := Background() - for _, test := range []struct { - desc string - f func() - limit float64 - gccgoLimit float64 - }{ - { - desc: "Background()", - f: func() { Background() }, - limit: 0, - gccgoLimit: 0, - }, - { - desc: fmt.Sprintf("WithValue(bg, %v, nil)", k1), - f: func() { - c := WithValue(bg, k1, nil) - c.Value(k1) - }, - limit: 3, - gccgoLimit: 3, - }, - { - desc: "WithTimeout(bg, 15*time.Millisecond)", - f: func() { - c, _ := WithTimeout(bg, 15*time.Millisecond) - <-c.Done() - }, - limit: 8, - gccgoLimit: 16, - }, - { - desc: "WithCancel(bg)", - f: func() { - c, cancel := WithCancel(bg) - cancel() - <-c.Done() - }, - limit: 5, - gccgoLimit: 8, - }, - { - desc: "WithTimeout(bg, 100*time.Millisecond)", - f: func() { - c, cancel := WithTimeout(bg, 100*time.Millisecond) - cancel() - <-c.Done() - }, - limit: 8, - gccgoLimit: 25, - }, - } { - limit := test.limit - if runtime.Compiler == "gccgo" { - // gccgo does not yet do escape analysis. - // TODO(iant): Remove this when gccgo does do escape analysis. - limit = test.gccgoLimit - } - if n := testing.AllocsPerRun(100, test.f); n > limit { - t.Errorf("%s allocs = %f want %d", test.desc, n, int(limit)) - } - } -} - -func TestSimultaneousCancels(t *testing.T) { - root, cancel := WithCancel(Background()) - m := map[Context]CancelFunc{root: cancel} - q := []Context{root} - // Create a tree of contexts. - for len(q) != 0 && len(m) < 100 { - parent := q[0] - q = q[1:] - for i := 0; i < 4; i++ { - ctx, cancel := WithCancel(parent) - m[ctx] = cancel - q = append(q, ctx) - } - } - // Start all the cancels in a random order. - var wg sync.WaitGroup - wg.Add(len(m)) - for _, cancel := range m { - go func(cancel CancelFunc) { - cancel() - wg.Done() - }(cancel) - } - // Wait on all the contexts in a random order. - for ctx := range m { - select { - case <-ctx.Done(): - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for <-ctx.Done(); stacks:\n%s", buf[:n]) - } - } - // Wait for all the cancel functions to return. - done := make(chan struct{}) - go func() { - wg.Wait() - close(done) - }() - select { - case <-done: - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for cancel functions; stacks:\n%s", buf[:n]) - } -} - -func TestInterlockedCancels(t *testing.T) { - parent, cancelParent := WithCancel(Background()) - child, cancelChild := WithCancel(parent) - go func() { - parent.Done() - cancelChild() - }() - cancelParent() - select { - case <-child.Done(): - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for child.Done(); stacks:\n%s", buf[:n]) - } -} - -func TestLayersCancel(t *testing.T) { - testLayers(t, time.Now().UnixNano(), false) -} - -func TestLayersTimeout(t *testing.T) { - testLayers(t, time.Now().UnixNano(), true) -} - -func testLayers(t *testing.T, seed int64, testTimeout bool) { - rand.Seed(seed) - errorf := func(format string, a ...interface{}) { - t.Errorf(fmt.Sprintf("seed=%d: %s", seed, format), a...) - } - const ( - timeout = 200 * time.Millisecond - minLayers = 30 - ) - type value int - var ( - vals []*value - cancels []CancelFunc - numTimers int - ctx = Background() - ) - for i := 0; i < minLayers || numTimers == 0 || len(cancels) == 0 || len(vals) == 0; i++ { - switch rand.Intn(3) { - case 0: - v := new(value) - ctx = WithValue(ctx, v, v) - vals = append(vals, v) - case 1: - var cancel CancelFunc - ctx, cancel = WithCancel(ctx) - cancels = append(cancels, cancel) - case 2: - var cancel CancelFunc - ctx, cancel = WithTimeout(ctx, timeout) - cancels = append(cancels, cancel) - numTimers++ - } - } - checkValues := func(when string) { - for _, key := range vals { - if val := ctx.Value(key).(*value); key != val { - errorf("%s: ctx.Value(%p) = %p want %p", when, key, val, key) - } - } - } - select { - case <-ctx.Done(): - errorf("ctx should not be canceled yet") - default: - } - if s, prefix := fmt.Sprint(ctx), "context.Background."; !strings.HasPrefix(s, prefix) { - t.Errorf("ctx.String() = %q want prefix %q", s, prefix) - } - t.Log(ctx) - checkValues("before cancel") - if testTimeout { - select { - case <-ctx.Done(): - case <-time.After(timeout + 100*time.Millisecond): - errorf("ctx should have timed out") - } - checkValues("after timeout") - } else { - cancel := cancels[rand.Intn(len(cancels))] - cancel() - select { - case <-ctx.Done(): - default: - errorf("ctx should be canceled") - } - checkValues("after cancel") - } -} - -func TestCancelRemoves(t *testing.T) { - checkChildren := func(when string, ctx Context, want int) { - if got := len(ctx.(*cancelCtx).children); got != want { - t.Errorf("%s: context has %d children, want %d", when, got, want) - } - } - - ctx, _ := WithCancel(Background()) - checkChildren("after creation", ctx, 0) - _, cancel := WithCancel(ctx) - checkChildren("with WithCancel child ", ctx, 1) - cancel() - checkChildren("after cancelling WithCancel child", ctx, 0) - - ctx, _ = WithCancel(Background()) - checkChildren("after creation", ctx, 0) - _, cancel = WithTimeout(ctx, 60*time.Minute) - checkChildren("with WithTimeout child ", ctx, 1) - cancel() - checkChildren("after cancelling WithTimeout child", ctx, 0) -} diff --git a/vendor/golang.org/x/net/context/withtimeout_test.go b/vendor/golang.org/x/net/context/withtimeout_test.go deleted file mode 100644 index a6754dc36892..000000000000 --- a/vendor/golang.org/x/net/context/withtimeout_test.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package context_test - -import ( - "fmt" - "time" - - "golang.org/x/net/context" -) - -func ExampleWithTimeout() { - // Pass a context with a timeout to tell a blocking function that it - // should abandon its work after the timeout elapses. - ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond) - select { - case <-time.After(200 * time.Millisecond): - fmt.Println("overslept") - case <-ctx.Done(): - fmt.Println(ctx.Err()) // prints "context deadline exceeded" - } - // Output: - // context deadline exceeded -} diff --git a/vendor/golang.org/x/oauth2/BUILD b/vendor/golang.org/x/oauth2/BUILD index e647ada9db13..e556af7fd5cd 100644 --- a/vendor/golang.org/x/oauth2/BUILD +++ b/vendor/golang.org/x/oauth2/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -15,25 +15,6 @@ go_library( ], ) -go_test( - name = "go_default_test", - srcs = [ - "oauth2_test.go", - "token_test.go", - "transport_test.go", - ], - importpath = "golang.org/x/oauth2", - library = ":go_default_library", - deps = ["//vendor/golang.org/x/net/context:go_default_library"], -) - -go_test( - name = "go_default_xtest", - srcs = ["example_test.go"], - importpath = "golang.org/x/oauth2_test", - deps = [":go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/golang.org/x/oauth2/example_test.go b/vendor/golang.org/x/oauth2/example_test.go deleted file mode 100644 index d861fe7e3536..000000000000 --- a/vendor/golang.org/x/oauth2/example_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package oauth2_test - -import ( - "context" - "fmt" - "log" - - "golang.org/x/oauth2" -) - -func ExampleConfig() { - ctx := context.Background() - conf := &oauth2.Config{ - ClientID: "YOUR_CLIENT_ID", - ClientSecret: "YOUR_CLIENT_SECRET", - Scopes: []string{"SCOPE1", "SCOPE2"}, - Endpoint: oauth2.Endpoint{ - AuthURL: "https://provider.com/o/oauth2/auth", - TokenURL: "https://provider.com/o/oauth2/token", - }, - } - - // Redirect user to consent page to ask for permission - // for the scopes specified above. - url := conf.AuthCodeURL("state", oauth2.AccessTypeOffline) - fmt.Printf("Visit the URL for the auth dialog: %v", url) - - // Use the authorization code that is pushed to the redirect - // URL. Exchange will do the handshake to retrieve the - // initial access token. The HTTP Client returned by - // conf.Client will refresh the token as necessary. - var code string - if _, err := fmt.Scan(&code); err != nil { - log.Fatal(err) - } - tok, err := conf.Exchange(ctx, code) - if err != nil { - log.Fatal(err) - } - - client := conf.Client(ctx, tok) - client.Get("...") -} diff --git a/vendor/golang.org/x/oauth2/internal/BUILD b/vendor/golang.org/x/oauth2/internal/BUILD index 8af2f598a814..85213d11630c 100644 --- a/vendor/golang.org/x/oauth2/internal/BUILD +++ b/vendor/golang.org/x/oauth2/internal/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -12,18 +12,6 @@ go_library( deps = ["//vendor/golang.org/x/net/context:go_default_library"], ) -go_test( - name = "go_default_test", - srcs = [ - "oauth2_test.go", - "token_test.go", - "transport_test.go", - ], - importpath = "golang.org/x/oauth2/internal", - library = ":go_default_library", - deps = ["//vendor/golang.org/x/net/context:go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/golang.org/x/oauth2/internal/oauth2_test.go b/vendor/golang.org/x/oauth2/internal/oauth2_test.go deleted file mode 100644 index c61585542d1b..000000000000 --- a/vendor/golang.org/x/oauth2/internal/oauth2_test.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package internal contains support packages for oauth2 package. -package internal - -import ( - "reflect" - "strings" - "testing" -) - -func TestParseINI(t *testing.T) { - tests := []struct { - ini string - want map[string]map[string]string - }{ - { - `root = toor -[foo] -bar = hop -ini = nin -`, - map[string]map[string]string{ - "": map[string]string{"root": "toor"}, - "foo": map[string]string{"bar": "hop", "ini": "nin"}, - }, - }, - { - `[empty] -[section] -empty= -`, - map[string]map[string]string{ - "": map[string]string{}, - "empty": map[string]string{}, - "section": map[string]string{"empty": ""}, - }, - }, - { - `ignore -[invalid -=stuff -;comment=true -`, - map[string]map[string]string{ - "": map[string]string{}, - }, - }, - } - for _, tt := range tests { - result, err := ParseINI(strings.NewReader(tt.ini)) - if err != nil { - t.Errorf("ParseINI(%q) error %v, want: no error", tt.ini, err) - continue - } - if !reflect.DeepEqual(result, tt.want) { - t.Errorf("ParseINI(%q) = %#v, want: %#v", tt.ini, result, tt.want) - } - } -} diff --git a/vendor/golang.org/x/oauth2/internal/token_test.go b/vendor/golang.org/x/oauth2/internal/token_test.go deleted file mode 100644 index 5ed0b15d5f44..000000000000 --- a/vendor/golang.org/x/oauth2/internal/token_test.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package internal contains support packages for oauth2 package. -package internal - -import ( - "fmt" - "testing" -) - -func TestRegisterBrokenAuthHeaderProvider(t *testing.T) { - RegisterBrokenAuthHeaderProvider("https://aaa.com/") - tokenURL := "https://aaa.com/token" - if providerAuthHeaderWorks(tokenURL) { - t.Errorf("got %q as unbroken; want broken", tokenURL) - } -} - -func Test_providerAuthHeaderWorks(t *testing.T) { - for _, p := range brokenAuthHeaderProviders { - if providerAuthHeaderWorks(p) { - t.Errorf("got %q as unbroken; want broken", p) - } - p := fmt.Sprintf("%ssomesuffix", p) - if providerAuthHeaderWorks(p) { - t.Errorf("got %q as unbroken; want broken", p) - } - } - p := "https://api.not-in-the-list-example.com/" - if !providerAuthHeaderWorks(p) { - t.Errorf("got %q as unbroken; want broken", p) - } -} diff --git a/vendor/golang.org/x/oauth2/internal/transport_test.go b/vendor/golang.org/x/oauth2/internal/transport_test.go deleted file mode 100644 index 8772ec5c4585..000000000000 --- a/vendor/golang.org/x/oauth2/internal/transport_test.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package internal - -import ( - "net/http" - "testing" - - "golang.org/x/net/context" -) - -func TestContextClient(t *testing.T) { - rc := &http.Client{} - RegisterContextClientFunc(func(context.Context) (*http.Client, error) { - return rc, nil - }) - - c := &http.Client{} - ctx := context.WithValue(context.Background(), HTTPClient, c) - - hc, err := ContextClient(ctx) - if err != nil { - t.Fatalf("want valid client; got err = %v", err) - } - if hc != c { - t.Fatalf("want context client = %p; got = %p", c, hc) - } - - hc, err = ContextClient(context.TODO()) - if err != nil { - t.Fatalf("want valid client; got err = %v", err) - } - if hc != rc { - t.Fatalf("want registered client = %p; got = %p", c, hc) - } -} diff --git a/vendor/golang.org/x/oauth2/oauth2_test.go b/vendor/golang.org/x/oauth2/oauth2_test.go deleted file mode 100644 index 982ea99e94c1..000000000000 --- a/vendor/golang.org/x/oauth2/oauth2_test.go +++ /dev/null @@ -1,456 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package oauth2 - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "net/url" - "reflect" - "strconv" - "testing" - "time" - - "golang.org/x/net/context" -) - -type mockTransport struct { - rt func(req *http.Request) (resp *http.Response, err error) -} - -func (t *mockTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) { - return t.rt(req) -} - -func newConf(url string) *Config { - return &Config{ - ClientID: "CLIENT_ID", - ClientSecret: "CLIENT_SECRET", - RedirectURL: "REDIRECT_URL", - Scopes: []string{"scope1", "scope2"}, - Endpoint: Endpoint{ - AuthURL: url + "/auth", - TokenURL: url + "/token", - }, - } -} - -func TestAuthCodeURL(t *testing.T) { - conf := newConf("server") - url := conf.AuthCodeURL("foo", AccessTypeOffline, ApprovalForce) - const want = "server/auth?access_type=offline&approval_prompt=force&client_id=CLIENT_ID&redirect_uri=REDIRECT_URL&response_type=code&scope=scope1+scope2&state=foo" - if got := url; got != want { - t.Errorf("got auth code URL = %q; want %q", got, want) - } -} - -func TestAuthCodeURL_CustomParam(t *testing.T) { - conf := newConf("server") - param := SetAuthURLParam("foo", "bar") - url := conf.AuthCodeURL("baz", param) - const want = "server/auth?client_id=CLIENT_ID&foo=bar&redirect_uri=REDIRECT_URL&response_type=code&scope=scope1+scope2&state=baz" - if got := url; got != want { - t.Errorf("got auth code = %q; want %q", got, want) - } -} - -func TestAuthCodeURL_Optional(t *testing.T) { - conf := &Config{ - ClientID: "CLIENT_ID", - Endpoint: Endpoint{ - AuthURL: "/auth-url", - TokenURL: "/token-url", - }, - } - url := conf.AuthCodeURL("") - const want = "/auth-url?client_id=CLIENT_ID&response_type=code" - if got := url; got != want { - t.Fatalf("got auth code = %q; want %q", got, want) - } -} - -func TestExchangeRequest(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() != "/token" { - t.Errorf("Unexpected exchange request URL, %v is found.", r.URL) - } - headerAuth := r.Header.Get("Authorization") - if headerAuth != "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" { - t.Errorf("Unexpected authorization header, %v is found.", headerAuth) - } - headerContentType := r.Header.Get("Content-Type") - if headerContentType != "application/x-www-form-urlencoded" { - t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) - } - body, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Errorf("Failed reading request body: %s.", err) - } - if string(body) != "client_id=CLIENT_ID&code=exchange-code&grant_type=authorization_code&redirect_uri=REDIRECT_URL&scope=scope1+scope2" { - t.Errorf("Unexpected exchange payload, %v is found.", string(body)) - } - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&scope=user&token_type=bearer")) - })) - defer ts.Close() - conf := newConf(ts.URL) - tok, err := conf.Exchange(context.Background(), "exchange-code") - if err != nil { - t.Error(err) - } - if !tok.Valid() { - t.Fatalf("Token invalid. Got: %#v", tok) - } - if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" { - t.Errorf("Unexpected access token, %#v.", tok.AccessToken) - } - if tok.TokenType != "bearer" { - t.Errorf("Unexpected token type, %#v.", tok.TokenType) - } - scope := tok.Extra("scope") - if scope != "user" { - t.Errorf("Unexpected value for scope: %v", scope) - } -} - -func TestExchangeRequest_JSONResponse(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() != "/token" { - t.Errorf("Unexpected exchange request URL, %v is found.", r.URL) - } - headerAuth := r.Header.Get("Authorization") - if headerAuth != "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" { - t.Errorf("Unexpected authorization header, %v is found.", headerAuth) - } - headerContentType := r.Header.Get("Content-Type") - if headerContentType != "application/x-www-form-urlencoded" { - t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) - } - body, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Errorf("Failed reading request body: %s.", err) - } - if string(body) != "client_id=CLIENT_ID&code=exchange-code&grant_type=authorization_code&redirect_uri=REDIRECT_URL&scope=scope1+scope2" { - t.Errorf("Unexpected exchange payload, %v is found.", string(body)) - } - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"access_token": "90d64460d14870c08c81352a05dedd3465940a7c", "scope": "user", "token_type": "bearer", "expires_in": 86400}`)) - })) - defer ts.Close() - conf := newConf(ts.URL) - tok, err := conf.Exchange(context.Background(), "exchange-code") - if err != nil { - t.Error(err) - } - if !tok.Valid() { - t.Fatalf("Token invalid. Got: %#v", tok) - } - if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" { - t.Errorf("Unexpected access token, %#v.", tok.AccessToken) - } - if tok.TokenType != "bearer" { - t.Errorf("Unexpected token type, %#v.", tok.TokenType) - } - scope := tok.Extra("scope") - if scope != "user" { - t.Errorf("Unexpected value for scope: %v", scope) - } - expiresIn := tok.Extra("expires_in") - if expiresIn != float64(86400) { - t.Errorf("Unexpected non-numeric value for expires_in: %v", expiresIn) - } -} - -func TestExtraValueRetrieval(t *testing.T) { - values := url.Values{} - kvmap := map[string]string{ - "scope": "user", "token_type": "bearer", "expires_in": "86400.92", - "server_time": "1443571905.5606415", "referer_ip": "10.0.0.1", - "etag": "\"afZYj912P4alikMz_P11982\"", "request_id": "86400", - "untrimmed": " untrimmed ", - } - for key, value := range kvmap { - values.Set(key, value) - } - - tok := Token{raw: values} - scope := tok.Extra("scope") - if got, want := scope, "user"; got != want { - t.Errorf("got scope = %q; want %q", got, want) - } - serverTime := tok.Extra("server_time") - if got, want := serverTime, 1443571905.5606415; got != want { - t.Errorf("got server_time value = %v; want %v", got, want) - } - refererIP := tok.Extra("referer_ip") - if got, want := refererIP, "10.0.0.1"; got != want { - t.Errorf("got referer_ip value = %v, want %v", got, want) - } - expiresIn := tok.Extra("expires_in") - if got, want := expiresIn, 86400.92; got != want { - t.Errorf("got expires_in value = %v, want %v", got, want) - } - requestID := tok.Extra("request_id") - if got, want := requestID, int64(86400); got != want { - t.Errorf("got request_id value = %v, want %v", got, want) - } - untrimmed := tok.Extra("untrimmed") - if got, want := untrimmed, " untrimmed "; got != want { - t.Errorf("got untrimmed = %q; want %q", got, want) - } -} - -const day = 24 * time.Hour - -func TestExchangeRequest_JSONResponse_Expiry(t *testing.T) { - seconds := int32(day.Seconds()) - jsonNumberType := reflect.TypeOf(json.Number("0")) - for _, c := range []struct { - expires string - expect error - }{ - {fmt.Sprintf(`"expires_in": %d`, seconds), nil}, - {fmt.Sprintf(`"expires_in": "%d"`, seconds), nil}, // PayPal case - {fmt.Sprintf(`"expires": %d`, seconds), nil}, // Facebook case - {`"expires": false`, &json.UnmarshalTypeError{Value: "bool", Type: jsonNumberType}}, // wrong type - {`"expires": {}`, &json.UnmarshalTypeError{Value: "object", Type: jsonNumberType}}, // wrong type - {`"expires": "zzz"`, &strconv.NumError{Func: "ParseInt", Num: "zzz", Err: strconv.ErrSyntax}}, // wrong value - } { - testExchangeRequest_JSONResponse_expiry(t, c.expires, c.expect) - } -} - -func testExchangeRequest_JSONResponse_expiry(t *testing.T, exp string, expect error) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(fmt.Sprintf(`{"access_token": "90d", "scope": "user", "token_type": "bearer", %s}`, exp))) - })) - defer ts.Close() - conf := newConf(ts.URL) - t1 := time.Now().Add(day) - tok, err := conf.Exchange(context.Background(), "exchange-code") - t2 := time.Now().Add(day) - // Do a fmt.Sprint comparison so either side can be - // nil. fmt.Sprint just stringifies them to "", and no - // non-nil expected error ever stringifies as "", so this - // isn't terribly disgusting. We do this because Go 1.4 and - // Go 1.5 return a different deep value for - // json.UnmarshalTypeError. In Go 1.5, the - // json.UnmarshalTypeError contains a new field with a new - // non-zero value. Rather than ignore it here with reflect or - // add new files and +build tags, just look at the strings. - if fmt.Sprint(err) != fmt.Sprint(expect) { - t.Errorf("Error = %v; want %v", err, expect) - } - if err != nil { - return - } - if !tok.Valid() { - t.Fatalf("Token invalid. Got: %#v", tok) - } - expiry := tok.Expiry - if expiry.Before(t1) || expiry.After(t2) { - t.Errorf("Unexpected value for Expiry: %v (shold be between %v and %v)", expiry, t1, t2) - } -} - -func TestExchangeRequest_BadResponse(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"scope": "user", "token_type": "bearer"}`)) - })) - defer ts.Close() - conf := newConf(ts.URL) - tok, err := conf.Exchange(context.Background(), "code") - if err != nil { - t.Fatal(err) - } - if tok.AccessToken != "" { - t.Errorf("Unexpected access token, %#v.", tok.AccessToken) - } -} - -func TestExchangeRequest_BadResponseType(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"access_token":123, "scope": "user", "token_type": "bearer"}`)) - })) - defer ts.Close() - conf := newConf(ts.URL) - _, err := conf.Exchange(context.Background(), "exchange-code") - if err == nil { - t.Error("expected error from invalid access_token type") - } -} - -func TestExchangeRequest_NonBasicAuth(t *testing.T) { - tr := &mockTransport{ - rt: func(r *http.Request) (w *http.Response, err error) { - headerAuth := r.Header.Get("Authorization") - if headerAuth != "" { - t.Errorf("Unexpected authorization header, %v is found.", headerAuth) - } - return nil, errors.New("no response") - }, - } - c := &http.Client{Transport: tr} - conf := &Config{ - ClientID: "CLIENT_ID", - Endpoint: Endpoint{ - AuthURL: "https://accounts.google.com/auth", - TokenURL: "https://accounts.google.com/token", - }, - } - - ctx := context.WithValue(context.Background(), HTTPClient, c) - conf.Exchange(ctx, "code") -} - -func TestPasswordCredentialsTokenRequest(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - defer r.Body.Close() - expected := "/token" - if r.URL.String() != expected { - t.Errorf("URL = %q; want %q", r.URL, expected) - } - headerAuth := r.Header.Get("Authorization") - expected = "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" - if headerAuth != expected { - t.Errorf("Authorization header = %q; want %q", headerAuth, expected) - } - headerContentType := r.Header.Get("Content-Type") - expected = "application/x-www-form-urlencoded" - if headerContentType != expected { - t.Errorf("Content-Type header = %q; want %q", headerContentType, expected) - } - body, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Errorf("Failed reading request body: %s.", err) - } - expected = "client_id=CLIENT_ID&grant_type=password&password=password1&scope=scope1+scope2&username=user1" - if string(body) != expected { - t.Errorf("res.Body = %q; want %q", string(body), expected) - } - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&scope=user&token_type=bearer")) - })) - defer ts.Close() - conf := newConf(ts.URL) - tok, err := conf.PasswordCredentialsToken(context.Background(), "user1", "password1") - if err != nil { - t.Error(err) - } - if !tok.Valid() { - t.Fatalf("Token invalid. Got: %#v", tok) - } - expected := "90d64460d14870c08c81352a05dedd3465940a7c" - if tok.AccessToken != expected { - t.Errorf("AccessToken = %q; want %q", tok.AccessToken, expected) - } - expected = "bearer" - if tok.TokenType != expected { - t.Errorf("TokenType = %q; want %q", tok.TokenType, expected) - } -} - -func TestTokenRefreshRequest(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() == "/somethingelse" { - return - } - if r.URL.String() != "/token" { - t.Errorf("Unexpected token refresh request URL, %v is found.", r.URL) - } - headerContentType := r.Header.Get("Content-Type") - if headerContentType != "application/x-www-form-urlencoded" { - t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) - } - body, _ := ioutil.ReadAll(r.Body) - if string(body) != "client_id=CLIENT_ID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN" { - t.Errorf("Unexpected refresh token payload, %v is found.", string(body)) - } - })) - defer ts.Close() - conf := newConf(ts.URL) - c := conf.Client(context.Background(), &Token{RefreshToken: "REFRESH_TOKEN"}) - c.Get(ts.URL + "/somethingelse") -} - -func TestFetchWithNoRefreshToken(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() == "/somethingelse" { - return - } - if r.URL.String() != "/token" { - t.Errorf("Unexpected token refresh request URL, %v is found.", r.URL) - } - headerContentType := r.Header.Get("Content-Type") - if headerContentType != "application/x-www-form-urlencoded" { - t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) - } - body, _ := ioutil.ReadAll(r.Body) - if string(body) != "client_id=CLIENT_ID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN" { - t.Errorf("Unexpected refresh token payload, %v is found.", string(body)) - } - })) - defer ts.Close() - conf := newConf(ts.URL) - c := conf.Client(context.Background(), nil) - _, err := c.Get(ts.URL + "/somethingelse") - if err == nil { - t.Errorf("Fetch should return an error if no refresh token is set") - } -} - -func TestRefreshToken_RefreshTokenReplacement(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"access_token":"ACCESS TOKEN", "scope": "user", "token_type": "bearer", "refresh_token": "NEW REFRESH TOKEN"}`)) - return - })) - defer ts.Close() - conf := newConf(ts.URL) - tkr := tokenRefresher{ - conf: conf, - ctx: context.Background(), - refreshToken: "OLD REFRESH TOKEN", - } - tk, err := tkr.Token() - if err != nil { - t.Errorf("got err = %v; want none", err) - return - } - if tk.RefreshToken != tkr.refreshToken { - t.Errorf("tokenRefresher.refresh_token = %q; want %q", tkr.refreshToken, tk.RefreshToken) - } -} - -func TestConfigClientWithToken(t *testing.T) { - tok := &Token{ - AccessToken: "abc123", - } - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if got, want := r.Header.Get("Authorization"), fmt.Sprintf("Bearer %s", tok.AccessToken); got != want { - t.Errorf("Authorization header = %q; want %q", got, want) - } - return - })) - defer ts.Close() - conf := newConf(ts.URL) - - c := conf.Client(context.Background(), tok) - req, err := http.NewRequest("GET", ts.URL, nil) - if err != nil { - t.Error(err) - } - _, err = c.Do(req) - if err != nil { - t.Error(err) - } -} diff --git a/vendor/golang.org/x/oauth2/token_test.go b/vendor/golang.org/x/oauth2/token_test.go deleted file mode 100644 index 80db83c29cd8..000000000000 --- a/vendor/golang.org/x/oauth2/token_test.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package oauth2 - -import ( - "testing" - "time" -) - -func TestTokenExtra(t *testing.T) { - type testCase struct { - key string - val interface{} - want interface{} - } - const key = "extra-key" - cases := []testCase{ - {key: key, val: "abc", want: "abc"}, - {key: key, val: 123, want: 123}, - {key: key, val: "", want: ""}, - {key: "other-key", val: "def", want: nil}, - } - for _, tc := range cases { - extra := make(map[string]interface{}) - extra[tc.key] = tc.val - tok := &Token{raw: extra} - if got, want := tok.Extra(key), tc.want; got != want { - t.Errorf("Extra(%q) = %q; want %q", key, got, want) - } - } -} - -func TestTokenExpiry(t *testing.T) { - now := time.Now() - cases := []struct { - name string - tok *Token - want bool - }{ - {name: "12 seconds", tok: &Token{Expiry: now.Add(12 * time.Second)}, want: false}, - {name: "10 seconds", tok: &Token{Expiry: now.Add(expiryDelta)}, want: true}, - {name: "-1 hour", tok: &Token{Expiry: now.Add(-1 * time.Hour)}, want: true}, - } - for _, tc := range cases { - if got, want := tc.tok.expired(), tc.want; got != want { - t.Errorf("expired (%q) = %v; want %v", tc.name, got, want) - } - } -} - -func TestTokenTypeMethod(t *testing.T) { - cases := []struct { - name string - tok *Token - want string - }{ - {name: "bearer-mixed_case", tok: &Token{TokenType: "beAREr"}, want: "Bearer"}, - {name: "default-bearer", tok: &Token{}, want: "Bearer"}, - {name: "basic", tok: &Token{TokenType: "basic"}, want: "Basic"}, - {name: "basic-capitalized", tok: &Token{TokenType: "Basic"}, want: "Basic"}, - {name: "mac", tok: &Token{TokenType: "mac"}, want: "MAC"}, - {name: "mac-caps", tok: &Token{TokenType: "MAC"}, want: "MAC"}, - {name: "mac-mixed_case", tok: &Token{TokenType: "mAc"}, want: "MAC"}, - } - for _, tc := range cases { - if got, want := tc.tok.Type(), tc.want; got != want { - t.Errorf("TokenType(%q) = %v; want %v", tc.name, got, want) - } - } -} diff --git a/vendor/golang.org/x/oauth2/transport_test.go b/vendor/golang.org/x/oauth2/transport_test.go deleted file mode 100644 index d6e8087d6e4f..000000000000 --- a/vendor/golang.org/x/oauth2/transport_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package oauth2 - -import ( - "net/http" - "net/http/httptest" - "testing" - "time" -) - -type tokenSource struct{ token *Token } - -func (t *tokenSource) Token() (*Token, error) { - return t.token, nil -} - -func TestTransportNilTokenSource(t *testing.T) { - tr := &Transport{} - server := newMockServer(func(w http.ResponseWriter, r *http.Request) {}) - defer server.Close() - client := &http.Client{Transport: tr} - resp, err := client.Get(server.URL) - if err == nil { - t.Errorf("got no errors, want an error with nil token source") - } - if resp != nil { - t.Errorf("Response = %v; want nil", resp) - } -} - -func TestTransportTokenSource(t *testing.T) { - ts := &tokenSource{ - token: &Token{ - AccessToken: "abc", - }, - } - tr := &Transport{ - Source: ts, - } - server := newMockServer(func(w http.ResponseWriter, r *http.Request) { - if got, want := r.Header.Get("Authorization"), "Bearer abc"; got != want { - t.Errorf("Authorization header = %q; want %q", got, want) - } - }) - defer server.Close() - client := &http.Client{Transport: tr} - res, err := client.Get(server.URL) - if err != nil { - t.Fatal(err) - } - res.Body.Close() -} - -// Test for case-sensitive token types, per https://github.com/golang/oauth2/issues/113 -func TestTransportTokenSourceTypes(t *testing.T) { - const val = "abc" - tests := []struct { - key string - val string - want string - }{ - {key: "bearer", val: val, want: "Bearer abc"}, - {key: "mac", val: val, want: "MAC abc"}, - {key: "basic", val: val, want: "Basic abc"}, - } - for _, tc := range tests { - ts := &tokenSource{ - token: &Token{ - AccessToken: tc.val, - TokenType: tc.key, - }, - } - tr := &Transport{ - Source: ts, - } - server := newMockServer(func(w http.ResponseWriter, r *http.Request) { - if got, want := r.Header.Get("Authorization"), tc.want; got != want { - t.Errorf("Authorization header (%q) = %q; want %q", val, got, want) - } - }) - defer server.Close() - client := &http.Client{Transport: tr} - res, err := client.Get(server.URL) - if err != nil { - t.Fatal(err) - } - res.Body.Close() - } -} - -func TestTokenValidNoAccessToken(t *testing.T) { - token := &Token{} - if token.Valid() { - t.Errorf("got valid with no access token; want invalid") - } -} - -func TestExpiredWithExpiry(t *testing.T) { - token := &Token{ - Expiry: time.Now().Add(-5 * time.Hour), - } - if token.Valid() { - t.Errorf("got valid with expired token; want invalid") - } -} - -func newMockServer(handler func(w http.ResponseWriter, r *http.Request)) *httptest.Server { - return httptest.NewServer(http.HandlerFunc(handler)) -} diff --git a/vendor/golang.org/x/sys/unix/BUILD b/vendor/golang.org/x/sys/unix/BUILD index eea4a9450744..153d424c6573 100644 --- a/vendor/golang.org/x/sys/unix/BUILD +++ b/vendor/golang.org/x/sys/unix/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -50,51 +50,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = select({ - "@io_bazel_rules_go//go/platform:darwin_amd64": [ - "export_test.go", - ], - "@io_bazel_rules_go//go/platform:linux_amd64": [ - "export_test.go", - ], - "//conditions:default": [], - }), - importpath = "golang.org/x/sys/unix", - library = ":go_default_library", -) - -go_test( - name = "go_default_xtest", - srcs = select({ - "@io_bazel_rules_go//go/platform:darwin_amd64": [ - "mmap_unix_test.go", - "syscall_bsd_test.go", - "syscall_test.go", - "syscall_unix_test.go", - ], - "@io_bazel_rules_go//go/platform:linux_amd64": [ - "creds_test.go", - "mmap_unix_test.go", - "syscall_linux_test.go", - "syscall_test.go", - "syscall_unix_test.go", - ], - "//conditions:default": [], - }), - importpath = "golang.org/x/sys/unix_test", - deps = select({ - "@io_bazel_rules_go//go/platform:darwin_amd64": [ - ":go_default_library", - ], - "@io_bazel_rules_go//go/platform:linux_amd64": [ - ":go_default_library", - ], - "//conditions:default": [], - }), -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/golang.org/x/sys/unix/creds_test.go b/vendor/golang.org/x/sys/unix/creds_test.go deleted file mode 100644 index eaae7c367faf..000000000000 --- a/vendor/golang.org/x/sys/unix/creds_test.go +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build linux - -package unix_test - -import ( - "bytes" - "net" - "os" - "syscall" - "testing" - - "golang.org/x/sys/unix" -) - -// TestSCMCredentials tests the sending and receiving of credentials -// (PID, UID, GID) in an ancillary message between two UNIX -// sockets. The SO_PASSCRED socket option is enabled on the sending -// socket for this to work. -func TestSCMCredentials(t *testing.T) { - fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0) - if err != nil { - t.Fatalf("Socketpair: %v", err) - } - defer unix.Close(fds[0]) - defer unix.Close(fds[1]) - - err = unix.SetsockoptInt(fds[0], unix.SOL_SOCKET, unix.SO_PASSCRED, 1) - if err != nil { - t.Fatalf("SetsockoptInt: %v", err) - } - - srvFile := os.NewFile(uintptr(fds[0]), "server") - defer srvFile.Close() - srv, err := net.FileConn(srvFile) - if err != nil { - t.Errorf("FileConn: %v", err) - return - } - defer srv.Close() - - cliFile := os.NewFile(uintptr(fds[1]), "client") - defer cliFile.Close() - cli, err := net.FileConn(cliFile) - if err != nil { - t.Errorf("FileConn: %v", err) - return - } - defer cli.Close() - - var ucred unix.Ucred - if os.Getuid() != 0 { - ucred.Pid = int32(os.Getpid()) - ucred.Uid = 0 - ucred.Gid = 0 - oob := unix.UnixCredentials(&ucred) - _, _, err := cli.(*net.UnixConn).WriteMsgUnix(nil, oob, nil) - if op, ok := err.(*net.OpError); ok { - err = op.Err - } - if sys, ok := err.(*os.SyscallError); ok { - err = sys.Err - } - if err != syscall.EPERM { - t.Fatalf("WriteMsgUnix failed with %v, want EPERM", err) - } - } - - ucred.Pid = int32(os.Getpid()) - ucred.Uid = uint32(os.Getuid()) - ucred.Gid = uint32(os.Getgid()) - oob := unix.UnixCredentials(&ucred) - - // this is going to send a dummy byte - n, oobn, err := cli.(*net.UnixConn).WriteMsgUnix(nil, oob, nil) - if err != nil { - t.Fatalf("WriteMsgUnix: %v", err) - } - if n != 0 { - t.Fatalf("WriteMsgUnix n = %d, want 0", n) - } - if oobn != len(oob) { - t.Fatalf("WriteMsgUnix oobn = %d, want %d", oobn, len(oob)) - } - - oob2 := make([]byte, 10*len(oob)) - n, oobn2, flags, _, err := srv.(*net.UnixConn).ReadMsgUnix(nil, oob2) - if err != nil { - t.Fatalf("ReadMsgUnix: %v", err) - } - if flags != 0 { - t.Fatalf("ReadMsgUnix flags = 0x%x, want 0", flags) - } - if n != 1 { - t.Fatalf("ReadMsgUnix n = %d, want 1 (dummy byte)", n) - } - if oobn2 != oobn { - // without SO_PASSCRED set on the socket, ReadMsgUnix will - // return zero oob bytes - t.Fatalf("ReadMsgUnix oobn = %d, want %d", oobn2, oobn) - } - oob2 = oob2[:oobn2] - if !bytes.Equal(oob, oob2) { - t.Fatal("ReadMsgUnix oob bytes don't match") - } - - scm, err := unix.ParseSocketControlMessage(oob2) - if err != nil { - t.Fatalf("ParseSocketControlMessage: %v", err) - } - newUcred, err := unix.ParseUnixCredentials(&scm[0]) - if err != nil { - t.Fatalf("ParseUnixCredentials: %v", err) - } - if *newUcred != ucred { - t.Fatalf("ParseUnixCredentials = %+v, want %+v", newUcred, ucred) - } -} diff --git a/vendor/golang.org/x/sys/unix/export_test.go b/vendor/golang.org/x/sys/unix/export_test.go deleted file mode 100644 index b4fdd970b6cf..000000000000 --- a/vendor/golang.org/x/sys/unix/export_test.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -package unix - -var Itoa = itoa diff --git a/vendor/golang.org/x/sys/unix/mmap_unix_test.go b/vendor/golang.org/x/sys/unix/mmap_unix_test.go deleted file mode 100644 index 18ccec05f13f..000000000000 --- a/vendor/golang.org/x/sys/unix/mmap_unix_test.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -package unix_test - -import ( - "testing" - - "golang.org/x/sys/unix" -) - -func TestMmap(t *testing.T) { - b, err := unix.Mmap(-1, 0, unix.Getpagesize(), unix.PROT_NONE, unix.MAP_ANON|unix.MAP_PRIVATE) - if err != nil { - t.Fatalf("Mmap: %v", err) - } - if err := unix.Munmap(b); err != nil { - t.Fatalf("Munmap: %v", err) - } -} diff --git a/vendor/golang.org/x/sys/unix/syscall_bsd_test.go b/vendor/golang.org/x/sys/unix/syscall_bsd_test.go deleted file mode 100644 index 2ad51290ccac..000000000000 --- a/vendor/golang.org/x/sys/unix/syscall_bsd_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd openbsd - -package unix_test - -import ( - "runtime" - "testing" - - "golang.org/x/sys/unix" -) - -const MNT_WAIT = 1 - -func TestGetfsstat(t *testing.T) { - n, err := unix.Getfsstat(nil, MNT_WAIT) - if err != nil { - t.Fatal(err) - } - - data := make([]unix.Statfs_t, n) - n, err = unix.Getfsstat(data, MNT_WAIT) - if err != nil { - t.Fatal(err) - } - - empty := unix.Statfs_t{} - for _, stat := range data { - if stat == empty { - t.Fatal("an empty Statfs_t struct was returned") - } - } -} - -func TestSysctlRaw(t *testing.T) { - if runtime.GOOS == "openbsd" { - t.Skip("kern.proc.pid does not exist on OpenBSD") - } - - _, err := unix.SysctlRaw("kern.proc.pid", unix.Getpid()) - if err != nil { - t.Fatal(err) - } -} diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd_test.go b/vendor/golang.org/x/sys/unix/syscall_freebsd_test.go deleted file mode 100644 index cd13080ad77f..000000000000 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd_test.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build freebsd - -package unix_test - -import ( - "os" - "testing" - - "golang.org/x/sys/unix" -) - -func TestSysctUint64(t *testing.T) { - _, err := unix.SysctlUint64("vm.max_kernel_address") - if err != nil { - if os.Getenv("GO_BUILDER_NAME") == "freebsd-386-gce101" { - t.Skipf("Ignoring known failing test (golang.org/issue/15186). Failed with: %v", err) - } - t.Fatal(err) - } -} diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_test.go b/vendor/golang.org/x/sys/unix/syscall_linux_test.go deleted file mode 100644 index 91184cae0696..000000000000 --- a/vendor/golang.org/x/sys/unix/syscall_linux_test.go +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build linux - -package unix_test - -import ( - "io/ioutil" - "os" - "testing" - "time" - - "golang.org/x/sys/unix" -) - -func TestPoll(t *testing.T) { - f, cleanup := mktmpfifo(t) - defer cleanup() - - const timeout = 100 - - ok := make(chan bool, 1) - go func() { - select { - case <-time.After(10 * timeout * time.Millisecond): - t.Errorf("Poll: failed to timeout after %d milliseconds", 10*timeout) - case <-ok: - } - }() - - fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}} - n, err := unix.Poll(fds, timeout) - ok <- true - if err != nil { - t.Errorf("Poll: unexpected error: %v", err) - return - } - if n != 0 { - t.Errorf("Poll: wrong number of events: got %v, expected %v", n, 0) - return - } -} - -func TestPpoll(t *testing.T) { - f, cleanup := mktmpfifo(t) - defer cleanup() - - const timeout = 100 * time.Millisecond - - ok := make(chan bool, 1) - go func() { - select { - case <-time.After(10 * timeout): - t.Errorf("Ppoll: failed to timeout after %d", 10*timeout) - case <-ok: - } - }() - - fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}} - timeoutTs := unix.NsecToTimespec(int64(timeout)) - n, err := unix.Ppoll(fds, &timeoutTs, nil) - ok <- true - if err != nil { - t.Errorf("Ppoll: unexpected error: %v", err) - return - } - if n != 0 { - t.Errorf("Ppoll: wrong number of events: got %v, expected %v", n, 0) - return - } -} - -// mktmpfifo creates a temporary FIFO and provides a cleanup function. -func mktmpfifo(t *testing.T) (*os.File, func()) { - err := unix.Mkfifo("fifo", 0666) - if err != nil { - t.Fatalf("mktmpfifo: failed to create FIFO: %v", err) - } - - f, err := os.OpenFile("fifo", os.O_RDWR, 0666) - if err != nil { - os.Remove("fifo") - t.Fatalf("mktmpfifo: failed to open FIFO: %v", err) - } - - return f, func() { - f.Close() - os.Remove("fifo") - } -} - -func TestTime(t *testing.T) { - var ut unix.Time_t - ut2, err := unix.Time(&ut) - if err != nil { - t.Fatalf("Time: %v", err) - } - if ut != ut2 { - t.Errorf("Time: return value %v should be equal to argument %v", ut2, ut) - } - - var now time.Time - - for i := 0; i < 10; i++ { - ut, err = unix.Time(nil) - if err != nil { - t.Fatalf("Time: %v", err) - } - - now = time.Now() - - if int64(ut) == now.Unix() { - return - } - } - - t.Errorf("Time: return value %v should be nearly equal to time.Now().Unix() %v", ut, now.Unix()) -} - -func TestUtime(t *testing.T) { - defer chtmpdir(t)() - - touch(t, "file1") - - buf := &unix.Utimbuf{ - Modtime: 12345, - } - - err := unix.Utime("file1", buf) - if err != nil { - t.Fatalf("Utime: %v", err) - } - - fi, err := os.Stat("file1") - if err != nil { - t.Fatal(err) - } - - if fi.ModTime().Unix() != 12345 { - t.Errorf("Utime: failed to change modtime: expected %v, got %v", 12345, fi.ModTime().Unix()) - } -} - -func TestGetrlimit(t *testing.T) { - var rlim unix.Rlimit - err := unix.Getrlimit(unix.RLIMIT_AS, &rlim) - if err != nil { - t.Fatalf("Getrlimit: %v", err) - } -} - -// utilities taken from os/os_test.go - -func touch(t *testing.T, name string) { - f, err := os.Create(name) - if err != nil { - t.Fatal(err) - } - if err := f.Close(); err != nil { - t.Fatal(err) - } -} - -// chtmpdir changes the working directory to a new temporary directory and -// provides a cleanup function. Used when PWD is read-only. -func chtmpdir(t *testing.T) func() { - oldwd, err := os.Getwd() - if err != nil { - t.Fatalf("chtmpdir: %v", err) - } - d, err := ioutil.TempDir("", "test") - if err != nil { - t.Fatalf("chtmpdir: %v", err) - } - if err := os.Chdir(d); err != nil { - t.Fatalf("chtmpdir: %v", err) - } - return func() { - if err := os.Chdir(oldwd); err != nil { - t.Fatalf("chtmpdir: %v", err) - } - os.RemoveAll(d) - } -} diff --git a/vendor/golang.org/x/sys/unix/syscall_test.go b/vendor/golang.org/x/sys/unix/syscall_test.go deleted file mode 100644 index 95eac92acadb..000000000000 --- a/vendor/golang.org/x/sys/unix/syscall_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -package unix_test - -import ( - "fmt" - "testing" - - "golang.org/x/sys/unix" -) - -func testSetGetenv(t *testing.T, key, value string) { - err := unix.Setenv(key, value) - if err != nil { - t.Fatalf("Setenv failed to set %q: %v", value, err) - } - newvalue, found := unix.Getenv(key) - if !found { - t.Fatalf("Getenv failed to find %v variable (want value %q)", key, value) - } - if newvalue != value { - t.Fatalf("Getenv(%v) = %q; want %q", key, newvalue, value) - } -} - -func TestEnv(t *testing.T) { - testSetGetenv(t, "TESTENV", "AVALUE") - // make sure TESTENV gets set to "", not deleted - testSetGetenv(t, "TESTENV", "") -} - -func TestItoa(t *testing.T) { - // Make most negative integer: 0x8000... - i := 1 - for i<<1 != 0 { - i <<= 1 - } - if i >= 0 { - t.Fatal("bad math") - } - s := unix.Itoa(i) - f := fmt.Sprint(i) - if s != f { - t.Fatalf("itoa(%d) = %s, want %s", i, s, f) - } -} diff --git a/vendor/golang.org/x/sys/unix/syscall_unix_test.go b/vendor/golang.org/x/sys/unix/syscall_unix_test.go deleted file mode 100644 index 49208a000daf..000000000000 --- a/vendor/golang.org/x/sys/unix/syscall_unix_test.go +++ /dev/null @@ -1,353 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -package unix_test - -import ( - "flag" - "fmt" - "io/ioutil" - "net" - "os" - "os/exec" - "path/filepath" - "runtime" - "testing" - "time" - - "golang.org/x/sys/unix" -) - -// Tests that below functions, structures and constants are consistent -// on all Unix-like systems. -func _() { - // program scheduling priority functions and constants - var ( - _ func(int, int, int) error = unix.Setpriority - _ func(int, int) (int, error) = unix.Getpriority - ) - const ( - _ int = unix.PRIO_USER - _ int = unix.PRIO_PROCESS - _ int = unix.PRIO_PGRP - ) - - // termios constants - const ( - _ int = unix.TCIFLUSH - _ int = unix.TCIOFLUSH - _ int = unix.TCOFLUSH - ) - - // fcntl file locking structure and constants - var ( - _ = unix.Flock_t{ - Type: int16(0), - Whence: int16(0), - Start: int64(0), - Len: int64(0), - Pid: int32(0), - } - ) - const ( - _ = unix.F_GETLK - _ = unix.F_SETLK - _ = unix.F_SETLKW - ) -} - -// TestFcntlFlock tests whether the file locking structure matches -// the calling convention of each kernel. -func TestFcntlFlock(t *testing.T) { - name := filepath.Join(os.TempDir(), "TestFcntlFlock") - fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0) - if err != nil { - t.Fatalf("Open failed: %v", err) - } - defer unix.Unlink(name) - defer unix.Close(fd) - flock := unix.Flock_t{ - Type: unix.F_RDLCK, - Start: 0, Len: 0, Whence: 1, - } - if err := unix.FcntlFlock(uintptr(fd), unix.F_GETLK, &flock); err != nil { - t.Fatalf("FcntlFlock failed: %v", err) - } -} - -// TestPassFD tests passing a file descriptor over a Unix socket. -// -// This test involved both a parent and child process. The parent -// process is invoked as a normal test, with "go test", which then -// runs the child process by running the current test binary with args -// "-test.run=^TestPassFD$" and an environment variable used to signal -// that the test should become the child process instead. -func TestPassFD(t *testing.T) { - switch runtime.GOOS { - case "dragonfly": - // TODO(jsing): Figure out why sendmsg is returning EINVAL. - t.Skip("skipping test on dragonfly") - case "solaris": - // TODO(aram): Figure out why ReadMsgUnix is returning empty message. - t.Skip("skipping test on solaris, see issue 7402") - } - if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" { - passFDChild() - return - } - - tempDir, err := ioutil.TempDir("", "TestPassFD") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tempDir) - - fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0) - if err != nil { - t.Fatalf("Socketpair: %v", err) - } - defer unix.Close(fds[0]) - defer unix.Close(fds[1]) - writeFile := os.NewFile(uintptr(fds[0]), "child-writes") - readFile := os.NewFile(uintptr(fds[1]), "parent-reads") - defer writeFile.Close() - defer readFile.Close() - - cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir) - cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} - if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" { - cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp) - } - cmd.ExtraFiles = []*os.File{writeFile} - - out, err := cmd.CombinedOutput() - if len(out) > 0 || err != nil { - t.Fatalf("child process: %q, %v", out, err) - } - - c, err := net.FileConn(readFile) - if err != nil { - t.Fatalf("FileConn: %v", err) - } - defer c.Close() - - uc, ok := c.(*net.UnixConn) - if !ok { - t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c) - } - - buf := make([]byte, 32) // expect 1 byte - oob := make([]byte, 32) // expect 24 bytes - closeUnix := time.AfterFunc(5*time.Second, func() { - t.Logf("timeout reading from unix socket") - uc.Close() - }) - _, oobn, _, _, err := uc.ReadMsgUnix(buf, oob) - closeUnix.Stop() - - scms, err := unix.ParseSocketControlMessage(oob[:oobn]) - if err != nil { - t.Fatalf("ParseSocketControlMessage: %v", err) - } - if len(scms) != 1 { - t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms) - } - scm := scms[0] - gotFds, err := unix.ParseUnixRights(&scm) - if err != nil { - t.Fatalf("unix.ParseUnixRights: %v", err) - } - if len(gotFds) != 1 { - t.Fatalf("wanted 1 fd; got %#v", gotFds) - } - - f := os.NewFile(uintptr(gotFds[0]), "fd-from-child") - defer f.Close() - - got, err := ioutil.ReadAll(f) - want := "Hello from child process!\n" - if string(got) != want { - t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want) - } -} - -// passFDChild is the child process used by TestPassFD. -func passFDChild() { - defer os.Exit(0) - - // Look for our fd. It should be fd 3, but we work around an fd leak - // bug here (http://golang.org/issue/2603) to let it be elsewhere. - var uc *net.UnixConn - for fd := uintptr(3); fd <= 10; fd++ { - f := os.NewFile(fd, "unix-conn") - var ok bool - netc, _ := net.FileConn(f) - uc, ok = netc.(*net.UnixConn) - if ok { - break - } - } - if uc == nil { - fmt.Println("failed to find unix fd") - return - } - - // Make a file f to send to our parent process on uc. - // We make it in tempDir, which our parent will clean up. - flag.Parse() - tempDir := flag.Arg(0) - f, err := ioutil.TempFile(tempDir, "") - if err != nil { - fmt.Printf("TempFile: %v", err) - return - } - - f.Write([]byte("Hello from child process!\n")) - f.Seek(0, 0) - - rights := unix.UnixRights(int(f.Fd())) - dummyByte := []byte("x") - n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil) - if err != nil { - fmt.Printf("WriteMsgUnix: %v", err) - return - } - if n != 1 || oobn != len(rights) { - fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights)) - return - } -} - -// TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage, -// and ParseUnixRights are able to successfully round-trip lists of file descriptors. -func TestUnixRightsRoundtrip(t *testing.T) { - testCases := [...][][]int{ - {{42}}, - {{1, 2}}, - {{3, 4, 5}}, - {{}}, - {{1, 2}, {3, 4, 5}, {}, {7}}, - } - for _, testCase := range testCases { - b := []byte{} - var n int - for _, fds := range testCase { - // Last assignment to n wins - n = len(b) + unix.CmsgLen(4*len(fds)) - b = append(b, unix.UnixRights(fds...)...) - } - // Truncate b - b = b[:n] - - scms, err := unix.ParseSocketControlMessage(b) - if err != nil { - t.Fatalf("ParseSocketControlMessage: %v", err) - } - if len(scms) != len(testCase) { - t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms) - } - for i, scm := range scms { - gotFds, err := unix.ParseUnixRights(&scm) - if err != nil { - t.Fatalf("ParseUnixRights: %v", err) - } - wantFds := testCase[i] - if len(gotFds) != len(wantFds) { - t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds) - } - for j, fd := range gotFds { - if fd != wantFds[j] { - t.Fatalf("expected fd %v, got %v", wantFds[j], fd) - } - } - } - } -} - -func TestRlimit(t *testing.T) { - var rlimit, zero unix.Rlimit - err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit) - if err != nil { - t.Fatalf("Getrlimit: save failed: %v", err) - } - if zero == rlimit { - t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit) - } - set := rlimit - set.Cur = set.Max - 1 - err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set) - if err != nil { - t.Fatalf("Setrlimit: set failed: %#v %v", set, err) - } - var get unix.Rlimit - err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get) - if err != nil { - t.Fatalf("Getrlimit: get failed: %v", err) - } - set = rlimit - set.Cur = set.Max - 1 - if set != get { - // Seems like Darwin requires some privilege to - // increase the soft limit of rlimit sandbox, though - // Setrlimit never reports an error. - switch runtime.GOOS { - case "darwin": - default: - t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get) - } - } - err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit) - if err != nil { - t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err) - } -} - -func TestSeekFailure(t *testing.T) { - _, err := unix.Seek(-1, 0, 0) - if err == nil { - t.Fatalf("Seek(-1, 0, 0) did not fail") - } - str := err.Error() // used to crash on Linux - t.Logf("Seek: %v", str) - if str == "" { - t.Fatalf("Seek(-1, 0, 0) return error with empty message") - } -} - -func TestDup(t *testing.T) { - file, err := ioutil.TempFile("", "TestDup") - if err != nil { - t.Fatalf("Tempfile failed: %v", err) - } - defer os.Remove(file.Name()) - defer file.Close() - f := int(file.Fd()) - - newFd, err := unix.Dup(f) - if err != nil { - t.Fatalf("Dup: %v", err) - } - - err = unix.Dup2(newFd, newFd+1) - if err != nil { - t.Fatalf("Dup2: %v", err) - } - - b1 := []byte("Test123") - b2 := make([]byte, 7) - _, err = unix.Write(newFd+1, b1) - if err != nil { - t.Fatalf("Write to dup2 fd failed: %v", err) - } - _, err = unix.Seek(f, 0, 0) - _, err = unix.Read(f, b2) - if err != nil { - t.Fatalf("Read back failed: %v", err) - } - if string(b1) != string(b2) { - t.Errorf("Dup: stdout write not in file, expected %v, got %v", string(b1), string(b2)) - } -} diff --git a/vendor/golang.org/x/tools/go/gcexportdata/BUILD b/vendor/golang.org/x/tools/go/gcexportdata/BUILD index 704fdf8b6007..113bcde514a1 100644 --- a/vendor/golang.org/x/tools/go/gcexportdata/BUILD +++ b/vendor/golang.org/x/tools/go/gcexportdata/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -11,16 +11,6 @@ go_library( deps = ["//vendor/golang.org/x/tools/go/gcimporter15:go_default_library"], ) -go_test( - name = "go_default_xtest", - srcs = [ - "example_test.go", - "gcexportdata_test.go", - ], - importpath = "golang.org/x/tools/go/gcexportdata_test", - deps = [":go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/golang.org/x/tools/go/gcexportdata/example_test.go b/vendor/golang.org/x/tools/go/gcexportdata/example_test.go deleted file mode 100644 index 1d7f47279872..000000000000 --- a/vendor/golang.org/x/tools/go/gcexportdata/example_test.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.7 - -package gcexportdata_test - -import ( - "fmt" - "go/ast" - "go/parser" - "go/token" - "go/types" - "log" - "os" - "path/filepath" - - "golang.org/x/tools/go/gcexportdata" -) - -// ExampleRead uses gcexportdata.Read to load type information for the -// "fmt" package from the fmt.a file produced by the gc compiler. -func ExampleRead() { - // Find the export data file. - filename, path := gcexportdata.Find("fmt", "") - if filename == "" { - log.Fatalf("can't find export data for fmt") - } - fmt.Printf("Package path: %s\n", path) - fmt.Printf("Export data: %s\n", filepath.Base(filename)) - - // Open and read the file. - f, err := os.Open(filename) - if err != nil { - log.Fatal(err) - } - defer f.Close() - r, err := gcexportdata.NewReader(f) - if err != nil { - log.Fatalf("reading export data %s: %v", filename, err) - } - - // Decode the export data. - fset := token.NewFileSet() - imports := make(map[string]*types.Package) - pkg, err := gcexportdata.Read(r, fset, imports, path) - if err != nil { - log.Fatal(err) - } - - // Print package information. - fmt.Printf("Package members: %s...\n", pkg.Scope().Names()[:5]) - println := pkg.Scope().Lookup("Println") - posn := fset.Position(println.Pos()) - posn.Line = 123 // make example deterministic - fmt.Printf("Println type: %s\n", println.Type()) - fmt.Printf("Println location: %s\n", slashify(posn)) - - // Output: - // - // Package path: fmt - // Export data: fmt.a - // Package members: [Errorf Formatter Fprint Fprintf Fprintln]... - // Println type: func(a ...interface{}) (n int, err error) - // Println location: $GOROOT/src/fmt/print.go:123:1 -} - -// ExampleNewImporter demonstrates usage of NewImporter to provide type -// information for dependencies when type-checking Go source code. -func ExampleNewImporter() { - const src = `package twopi - -import "math" - -const TwoPi = 2 * math.Pi -` - fset := token.NewFileSet() - f, err := parser.ParseFile(fset, "twopi.go", src, 0) - if err != nil { - log.Fatal(err) - } - - packages := make(map[string]*types.Package) - imp := gcexportdata.NewImporter(fset, packages) - conf := types.Config{Importer: imp} - pkg, err := conf.Check("twopi", fset, []*ast.File{f}, nil) - if err != nil { - log.Fatal(err) - } - - // object from imported package - pi := packages["math"].Scope().Lookup("Pi") - fmt.Printf("const %s.%s %s = %s // %s\n", - pi.Pkg().Path(), - pi.Name(), - pi.Type(), - pi.(*types.Const).Val(), - slashify(fset.Position(pi.Pos()))) - - // object in source package - twopi := pkg.Scope().Lookup("TwoPi") - fmt.Printf("const %s %s = %s // %s\n", - twopi.Name(), - twopi.Type(), - twopi.(*types.Const).Val(), - slashify(fset.Position(twopi.Pos()))) - - // Output: - // - // const math.Pi untyped float = 3.14159 // $GOROOT/src/math/const.go:11:1 - // const TwoPi untyped float = 6.28319 // twopi.go:5:7 -} - -func slashify(posn token.Position) token.Position { - posn.Filename = filepath.ToSlash(posn.Filename) // for MS Windows portability - return posn -} diff --git a/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata_test.go b/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata_test.go deleted file mode 100644 index 69133db9752b..000000000000 --- a/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package gcexportdata_test - -import ( - "go/token" - "go/types" - "log" - "os" - "testing" - - "golang.org/x/tools/go/gcexportdata" -) - -// Test to ensure that gcexportdata can read files produced by App -// Engine Go runtime v1.6. -func TestAppEngine16(t *testing.T) { - // Open and read the file. - f, err := os.Open("testdata/errors-ae16.a") - if err != nil { - t.Fatal(err) - } - defer f.Close() - r, err := gcexportdata.NewReader(f) - if err != nil { - log.Fatalf("reading export data: %v", err) - } - - // Decode the export data. - fset := token.NewFileSet() - imports := make(map[string]*types.Package) - pkg, err := gcexportdata.Read(r, fset, imports, "errors") - if err != nil { - log.Fatal(err) - } - - // Print package information. - got := pkg.Scope().Lookup("New").Type().String() - want := "func(text string) error" - if got != want { - t.Errorf("New.Type = %s, want %s", got, want) - } -} diff --git a/vendor/golang.org/x/tools/go/gcimporter15/BUILD b/vendor/golang.org/x/tools/go/gcimporter15/BUILD index 9dde591760f2..3543d9e800d5 100644 --- a/vendor/golang.org/x/tools/go/gcimporter15/BUILD +++ b/vendor/golang.org/x/tools/go/gcimporter15/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -14,27 +14,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = ["gcimporter_test.go"], - importpath = "golang.org/x/tools/go/gcimporter15", - library = ":go_default_library", -) - -go_test( - name = "go_default_xtest", - srcs = [ - "bexport19_test.go", - "bexport_test.go", - ], - importpath = "golang.org/x/tools/go/gcimporter15_test", - deps = [ - ":go_default_library", - "//vendor/golang.org/x/tools/go/buildutil:go_default_library", - "//vendor/golang.org/x/tools/go/loader:go_default_library", - ], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/golang.org/x/tools/go/gcimporter15/bexport19_test.go b/vendor/golang.org/x/tools/go/gcimporter15/bexport19_test.go deleted file mode 100644 index f6e9733b13fd..000000000000 --- a/vendor/golang.org/x/tools/go/gcimporter15/bexport19_test.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.9 - -package gcimporter_test - -import ( - "go/ast" - "go/parser" - "go/token" - "go/types" - "testing" - - gcimporter "golang.org/x/tools/go/gcimporter15" -) - -const src = ` -package p - -type ( - T0 = int32 - T1 = struct{} - T2 = struct{ T1 } - Invalid = foo // foo is undeclared -) -` - -func checkPkg(t *testing.T, pkg *types.Package, label string) { - T1 := types.NewStruct(nil, nil) - T2 := types.NewStruct([]*types.Var{types.NewField(0, pkg, "T1", T1, true)}, nil) - - for _, test := range []struct { - name string - typ types.Type - }{ - {"T0", types.Typ[types.Int32]}, - {"T1", T1}, - {"T2", T2}, - {"Invalid", types.Typ[types.Invalid]}, - } { - obj := pkg.Scope().Lookup(test.name) - if obj == nil { - t.Errorf("%s: %s not found", label, test.name) - continue - } - tname, _ := obj.(*types.TypeName) - if tname == nil { - t.Errorf("%s: %v not a type name", label, obj) - continue - } - if !tname.IsAlias() { - t.Errorf("%s: %v: not marked as alias", label, tname) - continue - } - if got := tname.Type(); !types.Identical(got, test.typ) { - t.Errorf("%s: %v: got %v; want %v", label, tname, got, test.typ) - } - } -} - -func TestTypeAliases(t *testing.T) { - // parse and typecheck - fset1 := token.NewFileSet() - f, err := parser.ParseFile(fset1, "p.go", src, 0) - if err != nil { - t.Fatal(err) - } - var conf types.Config - pkg1, err := conf.Check("p", fset1, []*ast.File{f}, nil) - if err == nil { - // foo in undeclared in src; we should see an error - t.Fatal("invalid source type-checked without error") - } - if pkg1 == nil { - // despite incorrect src we should see a (partially) type-checked package - t.Fatal("nil package returned") - } - checkPkg(t, pkg1, "export") - - // export - exportdata := gcimporter.BExportData(fset1, pkg1) - - // import - imports := make(map[string]*types.Package) - fset2 := token.NewFileSet() - _, pkg2, err := gcimporter.BImportData(fset2, imports, exportdata, pkg1.Path()) - if err != nil { - t.Fatalf("BImportData(%s): %v", pkg1.Path(), err) - } - checkPkg(t, pkg2, "import") -} diff --git a/vendor/golang.org/x/tools/go/gcimporter15/bexport_test.go b/vendor/golang.org/x/tools/go/gcimporter15/bexport_test.go deleted file mode 100644 index 6ab3bcb1020b..000000000000 --- a/vendor/golang.org/x/tools/go/gcimporter15/bexport_test.go +++ /dev/null @@ -1,326 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gcimporter_test - -import ( - "fmt" - "go/ast" - "go/build" - "go/constant" - "go/parser" - "go/token" - "go/types" - "reflect" - "runtime" - "strings" - "testing" - - "golang.org/x/tools/go/buildutil" - gcimporter "golang.org/x/tools/go/gcimporter15" - "golang.org/x/tools/go/loader" -) - -func TestBExportData_stdlib(t *testing.T) { - if runtime.GOOS == "android" { - t.Skipf("incomplete std lib on %s", runtime.GOOS) - } - - // Load, parse and type-check the program. - ctxt := build.Default // copy - ctxt.GOPATH = "" // disable GOPATH - conf := loader.Config{ - Build: &ctxt, - AllowErrors: true, - } - for _, path := range buildutil.AllPackages(conf.Build) { - conf.Import(path) - } - - // Create a package containing type and value errors to ensure - // they are properly encoded/decoded. - f, err := conf.ParseFile("haserrors/haserrors.go", `package haserrors -const UnknownValue = "" + 0 -type UnknownType undefined -`) - if err != nil { - t.Fatal(err) - } - conf.CreateFromFiles("haserrors", f) - - prog, err := conf.Load() - if err != nil { - t.Fatalf("Load failed: %v", err) - } - - numPkgs := len(prog.AllPackages) - if want := 248; numPkgs < want { - t.Errorf("Loaded only %d packages, want at least %d", numPkgs, want) - } - - for pkg, info := range prog.AllPackages { - if info.Files == nil { - continue // empty directory - } - exportdata := gcimporter.BExportData(conf.Fset, pkg) - - imports := make(map[string]*types.Package) - fset2 := token.NewFileSet() - n, pkg2, err := gcimporter.BImportData(fset2, imports, exportdata, pkg.Path()) - if err != nil { - t.Errorf("BImportData(%s): %v", pkg.Path(), err) - continue - } - if n != len(exportdata) { - t.Errorf("BImportData(%s) decoded %d bytes, want %d", - pkg.Path(), n, len(exportdata)) - } - - // Compare the packages' corresponding members. - for _, name := range pkg.Scope().Names() { - if !ast.IsExported(name) { - continue - } - obj1 := pkg.Scope().Lookup(name) - obj2 := pkg2.Scope().Lookup(name) - if obj2 == nil { - t.Errorf("%s.%s not found, want %s", pkg.Path(), name, obj1) - continue - } - - fl1 := fileLine(conf.Fset, obj1) - fl2 := fileLine(fset2, obj2) - if fl1 != fl2 { - t.Errorf("%s.%s: got posn %s, want %s", - pkg.Path(), name, fl2, fl1) - } - - if err := equalObj(obj1, obj2); err != nil { - t.Errorf("%s.%s: %s\ngot: %s\nwant: %s", - pkg.Path(), name, err, obj2, obj1) - } - } - } -} - -func fileLine(fset *token.FileSet, obj types.Object) string { - posn := fset.Position(obj.Pos()) - return fmt.Sprintf("%s:%d", posn.Filename, posn.Line) -} - -// equalObj reports how x and y differ. They are assumed to belong to -// different universes so cannot be compared directly. -func equalObj(x, y types.Object) error { - if reflect.TypeOf(x) != reflect.TypeOf(y) { - return fmt.Errorf("%T vs %T", x, y) - } - xt := x.Type() - yt := y.Type() - switch x.(type) { - case *types.Var, *types.Func: - // ok - case *types.Const: - xval := x.(*types.Const).Val() - yval := y.(*types.Const).Val() - // Use string comparison for floating-point values since rounding is permitted. - if constant.Compare(xval, token.NEQ, yval) && - !(xval.Kind() == constant.Float && xval.String() == yval.String()) { - return fmt.Errorf("unequal constants %s vs %s", xval, yval) - } - case *types.TypeName: - xt = xt.Underlying() - yt = yt.Underlying() - default: - return fmt.Errorf("unexpected %T", x) - } - return equalType(xt, yt) -} - -func equalType(x, y types.Type) error { - if reflect.TypeOf(x) != reflect.TypeOf(y) { - return fmt.Errorf("unequal kinds: %T vs %T", x, y) - } - switch x := x.(type) { - case *types.Interface: - y := y.(*types.Interface) - // TODO(gri): enable separate emission of Embedded interfaces - // and ExplicitMethods then use this logic. - // if x.NumEmbeddeds() != y.NumEmbeddeds() { - // return fmt.Errorf("unequal number of embedded interfaces: %d vs %d", - // x.NumEmbeddeds(), y.NumEmbeddeds()) - // } - // for i := 0; i < x.NumEmbeddeds(); i++ { - // xi := x.Embedded(i) - // yi := y.Embedded(i) - // if xi.String() != yi.String() { - // return fmt.Errorf("mismatched %th embedded interface: %s vs %s", - // i, xi, yi) - // } - // } - // if x.NumExplicitMethods() != y.NumExplicitMethods() { - // return fmt.Errorf("unequal methods: %d vs %d", - // x.NumExplicitMethods(), y.NumExplicitMethods()) - // } - // for i := 0; i < x.NumExplicitMethods(); i++ { - // xm := x.ExplicitMethod(i) - // ym := y.ExplicitMethod(i) - // if xm.Name() != ym.Name() { - // return fmt.Errorf("mismatched %th method: %s vs %s", i, xm, ym) - // } - // if err := equalType(xm.Type(), ym.Type()); err != nil { - // return fmt.Errorf("mismatched %s method: %s", xm.Name(), err) - // } - // } - if x.NumMethods() != y.NumMethods() { - return fmt.Errorf("unequal methods: %d vs %d", - x.NumMethods(), y.NumMethods()) - } - for i := 0; i < x.NumMethods(); i++ { - xm := x.Method(i) - ym := y.Method(i) - if xm.Name() != ym.Name() { - return fmt.Errorf("mismatched %dth method: %s vs %s", i, xm, ym) - } - if err := equalType(xm.Type(), ym.Type()); err != nil { - return fmt.Errorf("mismatched %s method: %s", xm.Name(), err) - } - } - case *types.Array: - y := y.(*types.Array) - if x.Len() != y.Len() { - return fmt.Errorf("unequal array lengths: %d vs %d", x.Len(), y.Len()) - } - if err := equalType(x.Elem(), y.Elem()); err != nil { - return fmt.Errorf("array elements: %s", err) - } - case *types.Basic: - y := y.(*types.Basic) - if x.Kind() != y.Kind() { - return fmt.Errorf("unequal basic types: %s vs %s", x, y) - } - case *types.Chan: - y := y.(*types.Chan) - if x.Dir() != y.Dir() { - return fmt.Errorf("unequal channel directions: %d vs %d", x.Dir(), y.Dir()) - } - if err := equalType(x.Elem(), y.Elem()); err != nil { - return fmt.Errorf("channel elements: %s", err) - } - case *types.Map: - y := y.(*types.Map) - if err := equalType(x.Key(), y.Key()); err != nil { - return fmt.Errorf("map keys: %s", err) - } - if err := equalType(x.Elem(), y.Elem()); err != nil { - return fmt.Errorf("map values: %s", err) - } - case *types.Named: - y := y.(*types.Named) - if x.String() != y.String() { - return fmt.Errorf("unequal named types: %s vs %s", x, y) - } - case *types.Pointer: - y := y.(*types.Pointer) - if err := equalType(x.Elem(), y.Elem()); err != nil { - return fmt.Errorf("pointer elements: %s", err) - } - case *types.Signature: - y := y.(*types.Signature) - if err := equalType(x.Params(), y.Params()); err != nil { - return fmt.Errorf("parameters: %s", err) - } - if err := equalType(x.Results(), y.Results()); err != nil { - return fmt.Errorf("results: %s", err) - } - if x.Variadic() != y.Variadic() { - return fmt.Errorf("unequal varidicity: %t vs %t", - x.Variadic(), y.Variadic()) - } - if (x.Recv() != nil) != (y.Recv() != nil) { - return fmt.Errorf("unequal receivers: %s vs %s", x.Recv(), y.Recv()) - } - if x.Recv() != nil { - // TODO(adonovan): fix: this assertion fires for interface methods. - // The type of the receiver of an interface method is a named type - // if the Package was loaded from export data, or an unnamed (interface) - // type if the Package was produced by type-checking ASTs. - // if err := equalType(x.Recv().Type(), y.Recv().Type()); err != nil { - // return fmt.Errorf("receiver: %s", err) - // } - } - case *types.Slice: - y := y.(*types.Slice) - if err := equalType(x.Elem(), y.Elem()); err != nil { - return fmt.Errorf("slice elements: %s", err) - } - case *types.Struct: - y := y.(*types.Struct) - if x.NumFields() != y.NumFields() { - return fmt.Errorf("unequal struct fields: %d vs %d", - x.NumFields(), y.NumFields()) - } - for i := 0; i < x.NumFields(); i++ { - xf := x.Field(i) - yf := y.Field(i) - if xf.Name() != yf.Name() { - return fmt.Errorf("mismatched fields: %s vs %s", xf, yf) - } - if err := equalType(xf.Type(), yf.Type()); err != nil { - return fmt.Errorf("struct field %s: %s", xf.Name(), err) - } - if x.Tag(i) != y.Tag(i) { - return fmt.Errorf("struct field %s has unequal tags: %q vs %q", - xf.Name(), x.Tag(i), y.Tag(i)) - } - } - case *types.Tuple: - y := y.(*types.Tuple) - if x.Len() != y.Len() { - return fmt.Errorf("unequal tuple lengths: %d vs %d", x.Len(), y.Len()) - } - for i := 0; i < x.Len(); i++ { - if err := equalType(x.At(i).Type(), y.At(i).Type()); err != nil { - return fmt.Errorf("tuple element %d: %s", i, err) - } - } - } - return nil -} - -// TestVeryLongFile tests the position of an import object declared in -// a very long input file. Line numbers greater than maxlines are -// reported as line 1, not garbage or token.NoPos. -func TestVeryLongFile(t *testing.T) { - // parse and typecheck - longFile := "package foo" + strings.Repeat("\n", 123456) + "var X int" - fset1 := token.NewFileSet() - f, err := parser.ParseFile(fset1, "foo.go", longFile, 0) - if err != nil { - t.Fatal(err) - } - var conf types.Config - pkg, err := conf.Check("foo", fset1, []*ast.File{f}, nil) - if err != nil { - t.Fatal(err) - } - - // export - exportdata := gcimporter.BExportData(fset1, pkg) - - // import - imports := make(map[string]*types.Package) - fset2 := token.NewFileSet() - _, pkg2, err := gcimporter.BImportData(fset2, imports, exportdata, pkg.Path()) - if err != nil { - t.Fatalf("BImportData(%s): %v", pkg.Path(), err) - } - - // compare - posn1 := fset1.Position(pkg.Scope().Lookup("X").Pos()) - posn2 := fset2.Position(pkg2.Scope().Lookup("X").Pos()) - if want := "foo.go:1:1"; posn2.String() != want { - t.Errorf("X position = %s, want %s (orig was %s)", - posn2, want, posn1) - } -} diff --git a/vendor/golang.org/x/tools/go/gcimporter15/gcimporter_test.go b/vendor/golang.org/x/tools/go/gcimporter15/gcimporter_test.go deleted file mode 100644 index d63f11220c12..000000000000 --- a/vendor/golang.org/x/tools/go/gcimporter15/gcimporter_test.go +++ /dev/null @@ -1,501 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file is a copy of $GOROOT/src/go/internal/gcimporter/gcimporter_test.go, -// adjusted to make it build with code from (std lib) internal/testenv copied. - -package gcimporter - -import ( - "bytes" - "fmt" - "go/types" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" - "testing" - "time" -) - -// ---------------------------------------------------------------------------- -// The following three functions (Builder, HasGoBuild, MustHaveGoBuild) were -// copied from $GOROOT/src/internal/testenv since that package is not available -// in x/tools. - -// Builder reports the name of the builder running this test -// (for example, "linux-amd64" or "windows-386-gce"). -// If the test is not running on the build infrastructure, -// Builder returns the empty string. -func Builder() string { - return os.Getenv("GO_BUILDER_NAME") -} - -// HasGoBuild reports whether the current system can build programs with ``go build'' -// and then run them with os.StartProcess or exec.Command. -func HasGoBuild() bool { - switch runtime.GOOS { - case "android", "nacl": - return false - case "darwin": - if strings.HasPrefix(runtime.GOARCH, "arm") { - return false - } - } - return true -} - -// MustHaveGoBuild checks that the current system can build programs with ``go build'' -// and then run them with os.StartProcess or exec.Command. -// If not, MustHaveGoBuild calls t.Skip with an explanation. -func MustHaveGoBuild(t *testing.T) { - if !HasGoBuild() { - t.Skipf("skipping test: 'go build' not available on %s/%s", runtime.GOOS, runtime.GOARCH) - } -} - -// ---------------------------------------------------------------------------- - -// skipSpecialPlatforms causes the test to be skipped for platforms where -// builders (build.golang.org) don't have access to compiled packages for -// import. -func skipSpecialPlatforms(t *testing.T) { - switch platform := runtime.GOOS + "-" + runtime.GOARCH; platform { - case "nacl-amd64p32", - "nacl-386", - "nacl-arm", - "darwin-arm", - "darwin-arm64": - t.Skipf("no compiled packages available for import on %s", platform) - } -} - -func compile(t *testing.T, dirname, filename string) string { - /* testenv. */ MustHaveGoBuild(t) - cmd := exec.Command("go", "tool", "compile", filename) - cmd.Dir = dirname - out, err := cmd.CombinedOutput() - if err != nil { - t.Logf("%s", out) - t.Fatalf("go tool compile %s failed: %s", filename, err) - } - // filename should end with ".go" - return filepath.Join(dirname, filename[:len(filename)-2]+"o") -} - -func testPath(t *testing.T, path, srcDir string) *types.Package { - t0 := time.Now() - pkg, err := Import(make(map[string]*types.Package), path, srcDir) - if err != nil { - t.Errorf("testPath(%s): %s", path, err) - return nil - } - t.Logf("testPath(%s): %v", path, time.Since(t0)) - return pkg -} - -const maxTime = 30 * time.Second - -func testDir(t *testing.T, dir string, endTime time.Time) (nimports int) { - dirname := filepath.Join(runtime.GOROOT(), "pkg", runtime.GOOS+"_"+runtime.GOARCH, dir) - list, err := ioutil.ReadDir(dirname) - if err != nil { - t.Fatalf("testDir(%s): %s", dirname, err) - } - for _, f := range list { - if time.Now().After(endTime) { - t.Log("testing time used up") - return - } - switch { - case !f.IsDir(): - // try extensions - for _, ext := range pkgExts { - if strings.HasSuffix(f.Name(), ext) { - name := f.Name()[0 : len(f.Name())-len(ext)] // remove extension - if testPath(t, filepath.Join(dir, name), dir) != nil { - nimports++ - } - } - } - case f.IsDir(): - nimports += testDir(t, filepath.Join(dir, f.Name()), endTime) - } - } - return -} - -const testfile = "exports.go" - -func TestImportTestdata(t *testing.T) { - // This package only handles gc export data. - if runtime.Compiler != "gc" { - t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) - return - } - - if outFn := compile(t, "testdata", testfile); outFn != "" { - defer os.Remove(outFn) - } - - // filename should end with ".go" - filename := testfile[:len(testfile)-3] - if pkg := testPath(t, "./testdata/"+filename, "."); pkg != nil { - // The package's Imports list must include all packages - // explicitly imported by testfile, plus all packages - // referenced indirectly via exported objects in testfile. - // With the textual export format (when run against Go1.6), - // the list may also include additional packages that are - // not strictly required for import processing alone (they - // are exported to err "on the safe side"). - // For now, we just test the presence of a few packages - // that we know are there for sure. - got := fmt.Sprint(pkg.Imports()) - for _, want := range []string{"go/ast", "go/token"} { - if !strings.Contains(got, want) { - t.Errorf(`Package("exports").Imports() = %s, does not contain %s`, got, want) - } - } - } -} - -func TestVersionHandling(t *testing.T) { - skipSpecialPlatforms(t) // we really only need to exclude nacl platforms, but this is fine - - // This package only handles gc export data. - if runtime.Compiler != "gc" { - t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) - return - } - - const dir = "./testdata/versions" - list, err := ioutil.ReadDir(dir) - if err != nil { - t.Fatal(err) - } - - for _, f := range list { - name := f.Name() - if !strings.HasSuffix(name, ".a") { - continue // not a package file - } - if strings.Contains(name, "corrupted") { - continue // don't process a leftover corrupted file - } - pkgpath := "./" + name[:len(name)-2] - - // test that export data can be imported - _, err := Import(make(map[string]*types.Package), pkgpath, dir) - if err != nil { - t.Errorf("import %q failed: %v", pkgpath, err) - continue - } - - // create file with corrupted export data - // 1) read file - data, err := ioutil.ReadFile(filepath.Join(dir, name)) - if err != nil { - t.Fatal(err) - } - // 2) find export data - i := bytes.Index(data, []byte("\n$$B\n")) + 5 - j := bytes.Index(data[i:], []byte("\n$$\n")) + i - if i < 0 || j < 0 || i > j { - t.Fatalf("export data section not found (i = %d, j = %d)", i, j) - } - // 3) corrupt the data (increment every 7th byte) - for k := j - 13; k >= i; k -= 7 { - data[k]++ - } - // 4) write the file - pkgpath += "_corrupted" - filename := filepath.Join(dir, pkgpath) + ".a" - ioutil.WriteFile(filename, data, 0666) - defer os.Remove(filename) - - // test that importing the corrupted file results in an error - _, err = Import(make(map[string]*types.Package), pkgpath, dir) - if err == nil { - t.Errorf("import corrupted %q succeeded", pkgpath) - } else if msg := err.Error(); !strings.Contains(msg, "version skew") { - t.Errorf("import %q error incorrect (%s)", pkgpath, msg) - } - } -} - -func TestImportStdLib(t *testing.T) { - skipSpecialPlatforms(t) - - // This package only handles gc export data. - if runtime.Compiler != "gc" { - t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) - return - } - - dt := maxTime - if testing.Short() && /* testenv. */ Builder() == "" { - dt = 10 * time.Millisecond - } - nimports := testDir(t, "", time.Now().Add(dt)) // installed packages - t.Logf("tested %d imports", nimports) -} - -var importedObjectTests = []struct { - name string - want string -}{ - {"math.Pi", "const Pi untyped float"}, - {"io.Reader", "type Reader interface{Read(p []byte) (n int, err error)}"}, - // Go 1.7 and 1.8 don't know about embedded interfaces. Leave this - // test out for now - the code is tested in the std library anyway. - // TODO(gri) enable again once we're off 1.7 and 1.8. - // {"io.ReadWriter", "type ReadWriter interface{Reader; Writer}"}, - {"math.Sin", "func Sin(x float64) float64"}, - // TODO(gri) add more tests -} - -func TestImportedTypes(t *testing.T) { - skipSpecialPlatforms(t) - - // This package only handles gc export data. - if runtime.Compiler != "gc" { - t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) - return - } - - for _, test := range importedObjectTests { - s := strings.Split(test.name, ".") - if len(s) != 2 { - t.Fatal("inconsistent test data") - } - importPath := s[0] - objName := s[1] - - pkg, err := Import(make(map[string]*types.Package), importPath, ".") - if err != nil { - t.Error(err) - continue - } - - obj := pkg.Scope().Lookup(objName) - if obj == nil { - t.Errorf("%s: object not found", test.name) - continue - } - - got := types.ObjectString(obj, types.RelativeTo(pkg)) - if got != test.want { - t.Errorf("%s: got %q; want %q", test.name, got, test.want) - } - } -} - -func TestIssue5815(t *testing.T) { - skipSpecialPlatforms(t) - - // This package only handles gc export data. - if runtime.Compiler != "gc" { - t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) - return - } - - pkg, err := Import(make(map[string]*types.Package), "strings", ".") - if err != nil { - t.Fatal(err) - } - - scope := pkg.Scope() - for _, name := range scope.Names() { - obj := scope.Lookup(name) - if obj.Pkg() == nil { - t.Errorf("no pkg for %s", obj) - } - if tname, _ := obj.(*types.TypeName); tname != nil { - named := tname.Type().(*types.Named) - for i := 0; i < named.NumMethods(); i++ { - m := named.Method(i) - if m.Pkg() == nil { - t.Errorf("no pkg for %s", m) - } - } - } - } -} - -// Smoke test to ensure that imported methods get the correct package. -func TestCorrectMethodPackage(t *testing.T) { - skipSpecialPlatforms(t) - - // This package only handles gc export data. - if runtime.Compiler != "gc" { - t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) - return - } - - imports := make(map[string]*types.Package) - _, err := Import(imports, "net/http", ".") - if err != nil { - t.Fatal(err) - } - - mutex := imports["sync"].Scope().Lookup("Mutex").(*types.TypeName).Type() - mset := types.NewMethodSet(types.NewPointer(mutex)) // methods of *sync.Mutex - sel := mset.Lookup(nil, "Lock") - lock := sel.Obj().(*types.Func) - if got, want := lock.Pkg().Path(), "sync"; got != want { - t.Errorf("got package path %q; want %q", got, want) - } -} - -func TestIssue13566(t *testing.T) { - skipSpecialPlatforms(t) - - // This package only handles gc export data. - if runtime.Compiler != "gc" { - t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) - return - } - - // On windows, we have to set the -D option for the compiler to avoid having a drive - // letter and an illegal ':' in the import path - just skip it (see also issue #3483). - if runtime.GOOS == "windows" { - t.Skip("avoid dealing with relative paths/drive letters on windows") - } - - if f := compile(t, "testdata", "a.go"); f != "" { - defer os.Remove(f) - } - if f := compile(t, "testdata", "b.go"); f != "" { - defer os.Remove(f) - } - - // import must succeed (test for issue at hand) - pkg, err := Import(make(map[string]*types.Package), "./testdata/b", ".") - if err != nil { - t.Fatal(err) - } - - // make sure all indirectly imported packages have names - for _, imp := range pkg.Imports() { - if imp.Name() == "" { - t.Errorf("no name for %s package", imp.Path()) - } - } -} - -func TestIssue13898(t *testing.T) { - skipSpecialPlatforms(t) - - // This package only handles gc export data. - if runtime.Compiler != "gc" { - t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) - return - } - - // import go/internal/gcimporter which imports go/types partially - imports := make(map[string]*types.Package) - _, err := Import(imports, "go/internal/gcimporter", ".") - if err != nil { - t.Fatal(err) - } - - // look for go/types package - var goTypesPkg *types.Package - for path, pkg := range imports { - if path == "go/types" { - goTypesPkg = pkg - break - } - } - if goTypesPkg == nil { - t.Fatal("go/types not found") - } - - // look for go/types.Object type - obj := goTypesPkg.Scope().Lookup("Object") - if obj == nil { - t.Fatal("go/types.Object not found") - } - typ, ok := obj.Type().(*types.Named) - if !ok { - t.Fatalf("go/types.Object type is %v; wanted named type", typ) - } - - // lookup go/types.Object.Pkg method - m, index, indirect := types.LookupFieldOrMethod(typ, false, nil, "Pkg") - if m == nil { - t.Fatalf("go/types.Object.Pkg not found (index = %v, indirect = %v)", index, indirect) - } - - // the method must belong to go/types - if m.Pkg().Path() != "go/types" { - t.Fatalf("found %v; want go/types", m.Pkg()) - } -} - -func TestIssue15517(t *testing.T) { - skipSpecialPlatforms(t) - - // This package only handles gc export data. - if runtime.Compiler != "gc" { - t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) - return - } - - // On windows, we have to set the -D option for the compiler to avoid having a drive - // letter and an illegal ':' in the import path - just skip it (see also issue #3483). - if runtime.GOOS == "windows" { - t.Skip("avoid dealing with relative paths/drive letters on windows") - } - - if f := compile(t, "testdata", "p.go"); f != "" { - defer os.Remove(f) - } - - // Multiple imports of p must succeed without redeclaration errors. - // We use an import path that's not cleaned up so that the eventual - // file path for the package is different from the package path; this - // will expose the error if it is present. - // - // (Issue: Both the textual and the binary importer used the file path - // of the package to be imported as key into the shared packages map. - // However, the binary importer then used the package path to identify - // the imported package to mark it as complete; effectively marking the - // wrong package as complete. By using an "unclean" package path, the - // file and package path are different, exposing the problem if present. - // The same issue occurs with vendoring.) - imports := make(map[string]*types.Package) - for i := 0; i < 3; i++ { - if _, err := Import(imports, "./././testdata/p", "."); err != nil { - t.Fatal(err) - } - } -} - -func TestIssue15920(t *testing.T) { - skipSpecialPlatforms(t) - - // This package only handles gc export data. - if runtime.Compiler != "gc" { - t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) - return - } - - // On windows, we have to set the -D option for the compiler to avoid having a drive - // letter and an illegal ':' in the import path - just skip it (see also issue #3483). - if runtime.GOOS == "windows" { - t.Skip("avoid dealing with relative paths/drive letters on windows") - } - - if f := compile(t, "testdata", "issue15920.go"); f != "" { - defer os.Remove(f) - } - - imports := make(map[string]*types.Package) - if _, err := Import(imports, "./testdata/issue15920", "."); err != nil { - t.Fatal(err) - } -} diff --git a/vendor/google.golang.org/appengine/BUILD b/vendor/google.golang.org/appengine/BUILD index 74f983d873e8..973fd4faa3d1 100644 --- a/vendor/google.golang.org/appengine/BUILD +++ b/vendor/google.golang.org/appengine/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -21,17 +21,6 @@ go_library( ], ) -go_test( - name = "go_default_test", - srcs = [ - "appengine_test.go", - "namespace_test.go", - ], - importpath = "google.golang.org/appengine", - library = ":go_default_library", - deps = ["//vendor/golang.org/x/net/context:go_default_library"], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/google.golang.org/appengine/appengine_test.go b/vendor/google.golang.org/appengine/appengine_test.go deleted file mode 100644 index f1cf0a1b9688..000000000000 --- a/vendor/google.golang.org/appengine/appengine_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -package appengine - -import ( - "testing" -) - -func TestValidGeoPoint(t *testing.T) { - testCases := []struct { - desc string - pt GeoPoint - want bool - }{ - { - "valid", - GeoPoint{67.21, 13.37}, - true, - }, - { - "high lat", - GeoPoint{-90.01, 13.37}, - false, - }, - { - "low lat", - GeoPoint{90.01, 13.37}, - false, - }, - { - "high lng", - GeoPoint{67.21, 182}, - false, - }, - { - "low lng", - GeoPoint{67.21, -181}, - false, - }, - } - - for _, tc := range testCases { - if got := tc.pt.Valid(); got != tc.want { - t.Errorf("%s: got %v, want %v", tc.desc, got, tc.want) - } - } -} diff --git a/vendor/google.golang.org/appengine/internal/BUILD b/vendor/google.golang.org/appengine/internal/BUILD index 86f957617df0..e7e902084149 100644 --- a/vendor/google.golang.org/appengine/internal/BUILD +++ b/vendor/google.golang.org/appengine/internal/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -26,24 +26,6 @@ go_library( ], ) -go_test( - name = "go_default_test", - srcs = [ - "api_test.go", - "app_id_test.go", - "internal_vm_test.go", - "net_test.go", - ], - importpath = "google.golang.org/appengine/internal", - library = ":go_default_library", - deps = [ - "//vendor/github.com/golang/protobuf/proto:go_default_library", - "//vendor/golang.org/x/net/context:go_default_library", - "//vendor/google.golang.org/appengine/internal/base:go_default_library", - "//vendor/google.golang.org/appengine/internal/remote_api:go_default_library", - ], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/google.golang.org/appengine/internal/api_race_test.go b/vendor/google.golang.org/appengine/internal/api_race_test.go deleted file mode 100644 index 6cfe90649c7b..000000000000 --- a/vendor/google.golang.org/appengine/internal/api_race_test.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// +build race - -package internal - -func init() { raceDetector = true } diff --git a/vendor/google.golang.org/appengine/internal/api_test.go b/vendor/google.golang.org/appengine/internal/api_test.go deleted file mode 100644 index 386d7f6cf490..000000000000 --- a/vendor/google.golang.org/appengine/internal/api_test.go +++ /dev/null @@ -1,467 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// +build !appengine - -package internal - -import ( - "bufio" - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "net/url" - "os" - "os/exec" - "strings" - "sync/atomic" - "testing" - "time" - - "github.com/golang/protobuf/proto" - netcontext "golang.org/x/net/context" - - basepb "google.golang.org/appengine/internal/base" - remotepb "google.golang.org/appengine/internal/remote_api" -) - -const testTicketHeader = "X-Magic-Ticket-Header" - -func init() { - ticketHeader = testTicketHeader -} - -type fakeAPIHandler struct { - hang chan int // used for RunSlowly RPC - - LogFlushes int32 // atomic -} - -func (f *fakeAPIHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - writeResponse := func(res *remotepb.Response) { - hresBody, err := proto.Marshal(res) - if err != nil { - http.Error(w, fmt.Sprintf("Failed encoding API response: %v", err), 500) - return - } - w.Write(hresBody) - } - - if r.URL.Path != "/rpc_http" { - http.NotFound(w, r) - return - } - hreqBody, err := ioutil.ReadAll(r.Body) - if err != nil { - http.Error(w, fmt.Sprintf("Bad body: %v", err), 500) - return - } - apiReq := &remotepb.Request{} - if err := proto.Unmarshal(hreqBody, apiReq); err != nil { - http.Error(w, fmt.Sprintf("Bad encoded API request: %v", err), 500) - return - } - if *apiReq.RequestId != "s3cr3t" { - writeResponse(&remotepb.Response{ - RpcError: &remotepb.RpcError{ - Code: proto.Int32(int32(remotepb.RpcError_SECURITY_VIOLATION)), - Detail: proto.String("bad security ticket"), - }, - }) - return - } - if got, want := r.Header.Get(dapperHeader), "trace-001"; got != want { - writeResponse(&remotepb.Response{ - RpcError: &remotepb.RpcError{ - Code: proto.Int32(int32(remotepb.RpcError_BAD_REQUEST)), - Detail: proto.String(fmt.Sprintf("trace info = %q, want %q", got, want)), - }, - }) - return - } - - service, method := *apiReq.ServiceName, *apiReq.Method - var resOut proto.Message - if service == "actordb" && method == "LookupActor" { - req := &basepb.StringProto{} - res := &basepb.StringProto{} - if err := proto.Unmarshal(apiReq.Request, req); err != nil { - http.Error(w, fmt.Sprintf("Bad encoded request: %v", err), 500) - return - } - if *req.Value == "Doctor Who" { - res.Value = proto.String("David Tennant") - } - resOut = res - } - if service == "errors" { - switch method { - case "Non200": - http.Error(w, "I'm a little teapot.", 418) - return - case "ShortResponse": - w.Header().Set("Content-Length", "100") - w.Write([]byte("way too short")) - return - case "OverQuota": - writeResponse(&remotepb.Response{ - RpcError: &remotepb.RpcError{ - Code: proto.Int32(int32(remotepb.RpcError_OVER_QUOTA)), - Detail: proto.String("you are hogging the resources!"), - }, - }) - return - case "RunSlowly": - // TestAPICallRPCFailure creates f.hang, but does not strobe it - // until Call returns with remotepb.RpcError_CANCELLED. - // This is here to force a happens-before relationship between - // the httptest server handler and shutdown. - <-f.hang - resOut = &basepb.VoidProto{} - } - } - if service == "logservice" && method == "Flush" { - // Pretend log flushing is slow. - time.Sleep(50 * time.Millisecond) - atomic.AddInt32(&f.LogFlushes, 1) - resOut = &basepb.VoidProto{} - } - - encOut, err := proto.Marshal(resOut) - if err != nil { - http.Error(w, fmt.Sprintf("Failed encoding response: %v", err), 500) - return - } - writeResponse(&remotepb.Response{ - Response: encOut, - }) -} - -func setup() (f *fakeAPIHandler, c *context, cleanup func()) { - f = &fakeAPIHandler{} - srv := httptest.NewServer(f) - u, err := url.Parse(srv.URL + apiPath) - if err != nil { - panic(fmt.Sprintf("url.Parse(%q): %v", srv.URL+apiPath, err)) - } - return f, &context{ - req: &http.Request{ - Header: http.Header{ - ticketHeader: []string{"s3cr3t"}, - dapperHeader: []string{"trace-001"}, - }, - }, - apiURL: u, - }, srv.Close -} - -func TestAPICall(t *testing.T) { - _, c, cleanup := setup() - defer cleanup() - - req := &basepb.StringProto{ - Value: proto.String("Doctor Who"), - } - res := &basepb.StringProto{} - err := Call(toContext(c), "actordb", "LookupActor", req, res) - if err != nil { - t.Fatalf("API call failed: %v", err) - } - if got, want := *res.Value, "David Tennant"; got != want { - t.Errorf("Response is %q, want %q", got, want) - } -} - -func TestAPICallRPCFailure(t *testing.T) { - f, c, cleanup := setup() - defer cleanup() - - testCases := []struct { - method string - code remotepb.RpcError_ErrorCode - }{ - {"Non200", remotepb.RpcError_UNKNOWN}, - {"ShortResponse", remotepb.RpcError_UNKNOWN}, - {"OverQuota", remotepb.RpcError_OVER_QUOTA}, - {"RunSlowly", remotepb.RpcError_CANCELLED}, - } - f.hang = make(chan int) // only for RunSlowly - for _, tc := range testCases { - ctx, _ := netcontext.WithTimeout(toContext(c), 100*time.Millisecond) - err := Call(ctx, "errors", tc.method, &basepb.VoidProto{}, &basepb.VoidProto{}) - ce, ok := err.(*CallError) - if !ok { - t.Errorf("%s: API call error is %T (%v), want *CallError", tc.method, err, err) - continue - } - if ce.Code != int32(tc.code) { - t.Errorf("%s: ce.Code = %d, want %d", tc.method, ce.Code, tc.code) - } - if tc.method == "RunSlowly" { - f.hang <- 1 // release the HTTP handler - } - } -} - -func TestAPICallDialFailure(t *testing.T) { - // See what happens if the API host is unresponsive. - // This should time out quickly, not hang forever. - _, c, cleanup := setup() - defer cleanup() - // Reset the URL to the production address so that dialing fails. - c.apiURL = apiURL() - - start := time.Now() - err := Call(toContext(c), "foo", "bar", &basepb.VoidProto{}, &basepb.VoidProto{}) - const max = 1 * time.Second - if taken := time.Since(start); taken > max { - t.Errorf("Dial hang took too long: %v > %v", taken, max) - } - if err == nil { - t.Error("Call did not fail") - } -} - -func TestDelayedLogFlushing(t *testing.T) { - f, c, cleanup := setup() - defer cleanup() - - http.HandleFunc("/quick_log", func(w http.ResponseWriter, r *http.Request) { - logC := WithContext(netcontext.Background(), r) - fromContext(logC).apiURL = c.apiURL // Otherwise it will try to use the default URL. - Logf(logC, 1, "It's a lovely day.") - w.WriteHeader(200) - w.Write(make([]byte, 100<<10)) // write 100 KB to force HTTP flush - }) - - r := &http.Request{ - Method: "GET", - URL: &url.URL{ - Scheme: "http", - Path: "/quick_log", - }, - Header: c.req.Header, - Body: ioutil.NopCloser(bytes.NewReader(nil)), - } - w := httptest.NewRecorder() - - // Check that log flushing does not hold up the HTTP response. - start := time.Now() - handleHTTP(w, r) - if d := time.Since(start); d > 10*time.Millisecond { - t.Errorf("handleHTTP took %v, want under 10ms", d) - } - const hdr = "X-AppEngine-Log-Flush-Count" - if h := w.HeaderMap.Get(hdr); h != "1" { - t.Errorf("%s header = %q, want %q", hdr, h, "1") - } - if f := atomic.LoadInt32(&f.LogFlushes); f != 0 { - t.Errorf("After HTTP response: f.LogFlushes = %d, want 0", f) - } - - // Check that the log flush eventually comes in. - time.Sleep(100 * time.Millisecond) - if f := atomic.LoadInt32(&f.LogFlushes); f != 1 { - t.Errorf("After 100ms: f.LogFlushes = %d, want 1", f) - } -} - -func TestRemoteAddr(t *testing.T) { - var addr string - http.HandleFunc("/remote_addr", func(w http.ResponseWriter, r *http.Request) { - addr = r.RemoteAddr - }) - - testCases := []struct { - headers http.Header - addr string - }{ - {http.Header{"X-Appengine-User-Ip": []string{"10.5.2.1"}}, "10.5.2.1:80"}, - {http.Header{"X-Appengine-Remote-Addr": []string{"1.2.3.4"}}, "1.2.3.4:80"}, - {http.Header{"X-Appengine-Remote-Addr": []string{"1.2.3.4:8080"}}, "1.2.3.4:8080"}, - { - http.Header{"X-Appengine-Remote-Addr": []string{"2401:fa00:9:1:7646:a0ff:fe90:ca66"}}, - "[2401:fa00:9:1:7646:a0ff:fe90:ca66]:80", - }, - { - http.Header{"X-Appengine-Remote-Addr": []string{"[::1]:http"}}, - "[::1]:http", - }, - {http.Header{}, "127.0.0.1:80"}, - } - - for _, tc := range testCases { - r := &http.Request{ - Method: "GET", - URL: &url.URL{Scheme: "http", Path: "/remote_addr"}, - Header: tc.headers, - Body: ioutil.NopCloser(bytes.NewReader(nil)), - } - handleHTTP(httptest.NewRecorder(), r) - if addr != tc.addr { - t.Errorf("Header %v, got %q, want %q", tc.headers, addr, tc.addr) - } - } -} - -func TestPanickingHandler(t *testing.T) { - http.HandleFunc("/panic", func(http.ResponseWriter, *http.Request) { - panic("whoops!") - }) - r := &http.Request{ - Method: "GET", - URL: &url.URL{Scheme: "http", Path: "/panic"}, - Body: ioutil.NopCloser(bytes.NewReader(nil)), - } - rec := httptest.NewRecorder() - handleHTTP(rec, r) - if rec.Code != 500 { - t.Errorf("Panicking handler returned HTTP %d, want HTTP %d", rec.Code, 500) - } -} - -var raceDetector = false - -func TestAPICallAllocations(t *testing.T) { - if raceDetector { - t.Skip("not running under race detector") - } - - // Run the test API server in a subprocess so we aren't counting its allocations. - u, cleanup := launchHelperProcess(t) - defer cleanup() - c := &context{ - req: &http.Request{ - Header: http.Header{ - ticketHeader: []string{"s3cr3t"}, - dapperHeader: []string{"trace-001"}, - }, - }, - apiURL: u, - } - - req := &basepb.StringProto{ - Value: proto.String("Doctor Who"), - } - res := &basepb.StringProto{} - var apiErr error - avg := testing.AllocsPerRun(100, func() { - ctx, _ := netcontext.WithTimeout(toContext(c), 100*time.Millisecond) - if err := Call(ctx, "actordb", "LookupActor", req, res); err != nil && apiErr == nil { - apiErr = err // get the first error only - } - }) - if apiErr != nil { - t.Errorf("API call failed: %v", apiErr) - } - - // Lots of room for improvement... - // TODO(djd): Reduce maximum to 85 once the App Engine SDK is based on 1.6. - const min, max float64 = 70, 90 - if avg < min || max < avg { - t.Errorf("Allocations per API call = %g, want in [%g,%g]", avg, min, max) - } -} - -func launchHelperProcess(t *testing.T) (apiURL *url.URL, cleanup func()) { - cmd := exec.Command(os.Args[0], "-test.run=TestHelperProcess") - cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} - stdin, err := cmd.StdinPipe() - if err != nil { - t.Fatalf("StdinPipe: %v", err) - } - stdout, err := cmd.StdoutPipe() - if err != nil { - t.Fatalf("StdoutPipe: %v", err) - } - if err := cmd.Start(); err != nil { - t.Fatalf("Starting helper process: %v", err) - } - - scan := bufio.NewScanner(stdout) - var u *url.URL - for scan.Scan() { - line := scan.Text() - if hp := strings.TrimPrefix(line, helperProcessMagic); hp != line { - var err error - u, err = url.Parse(hp) - if err != nil { - t.Fatalf("Failed to parse %q: %v", hp, err) - } - break - } - } - if err := scan.Err(); err != nil { - t.Fatalf("Scanning helper process stdout: %v", err) - } - if u == nil { - t.Fatal("Helper process never reported") - } - - return u, func() { - stdin.Close() - if err := cmd.Wait(); err != nil { - t.Errorf("Helper process did not exit cleanly: %v", err) - } - } -} - -const helperProcessMagic = "A lovely helper process is listening at " - -// This isn't a real test. It's used as a helper process. -func TestHelperProcess(*testing.T) { - if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" { - return - } - defer os.Exit(0) - - f := &fakeAPIHandler{} - srv := httptest.NewServer(f) - defer srv.Close() - fmt.Println(helperProcessMagic + srv.URL + apiPath) - - // Wait for stdin to be closed. - io.Copy(ioutil.Discard, os.Stdin) -} - -func TestBackgroundContext(t *testing.T) { - environ := []struct { - key, value string - }{ - {"GAE_LONG_APP_ID", "my-app-id"}, - {"GAE_MINOR_VERSION", "067924799508853122"}, - {"GAE_MODULE_INSTANCE", "0"}, - {"GAE_MODULE_NAME", "default"}, - {"GAE_MODULE_VERSION", "20150612t184001"}, - } - for _, v := range environ { - old := os.Getenv(v.key) - os.Setenv(v.key, v.value) - v.value = old - } - defer func() { // Restore old environment after the test completes. - for _, v := range environ { - if v.value == "" { - os.Unsetenv(v.key) - continue - } - os.Setenv(v.key, v.value) - } - }() - - ctx, key := fromContext(BackgroundContext()), "X-Magic-Ticket-Header" - if g, w := ctx.req.Header.Get(key), "my-app-id/default.20150612t184001.0"; g != w { - t.Errorf("%v = %q, want %q", key, g, w) - } - - // Check that using the background context doesn't panic. - req := &basepb.StringProto{ - Value: proto.String("Doctor Who"), - } - res := &basepb.StringProto{} - Call(BackgroundContext(), "actordb", "LookupActor", req, res) // expected to fail -} diff --git a/vendor/google.golang.org/appengine/internal/app_id_test.go b/vendor/google.golang.org/appengine/internal/app_id_test.go deleted file mode 100644 index e69195cd4055..000000000000 --- a/vendor/google.golang.org/appengine/internal/app_id_test.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2011 Google Inc. All Rights Reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -package internal - -import ( - "testing" -) - -func TestAppIDParsing(t *testing.T) { - testCases := []struct { - in string - partition, domain, displayID string - }{ - {"simple-app-id", "", "", "simple-app-id"}, - {"domain.com:domain-app-id", "", "domain.com", "domain-app-id"}, - {"part~partition-app-id", "part", "", "partition-app-id"}, - {"part~domain.com:display", "part", "domain.com", "display"}, - } - - for _, tc := range testCases { - part, dom, dis := parseFullAppID(tc.in) - if part != tc.partition { - t.Errorf("partition of %q: got %q, want %q", tc.in, part, tc.partition) - } - if dom != tc.domain { - t.Errorf("domain of %q: got %q, want %q", tc.in, dom, tc.domain) - } - if dis != tc.displayID { - t.Errorf("displayID of %q: got %q, want %q", tc.in, dis, tc.displayID) - } - } -} diff --git a/vendor/google.golang.org/appengine/internal/internal_vm_test.go b/vendor/google.golang.org/appengine/internal/internal_vm_test.go deleted file mode 100644 index f8097616b923..000000000000 --- a/vendor/google.golang.org/appengine/internal/internal_vm_test.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// +build !appengine - -package internal - -import ( - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" -) - -func TestInstallingHealthChecker(t *testing.T) { - try := func(desc string, mux *http.ServeMux, wantCode int, wantBody string) { - installHealthChecker(mux) - srv := httptest.NewServer(mux) - defer srv.Close() - - resp, err := http.Get(srv.URL + "/_ah/health") - if err != nil { - t.Errorf("%s: http.Get: %v", desc, err) - return - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("%s: reading body: %v", desc, err) - return - } - - if resp.StatusCode != wantCode { - t.Errorf("%s: got HTTP %d, want %d", desc, resp.StatusCode, wantCode) - return - } - if wantBody != "" && string(body) != wantBody { - t.Errorf("%s: got HTTP body %q, want %q", desc, body, wantBody) - return - } - } - - // If there's no handlers, or only a root handler, a health checker should be installed. - try("empty mux", http.NewServeMux(), 200, "ok") - mux := http.NewServeMux() - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, "root handler") - }) - try("mux with root handler", mux, 200, "ok") - - // If there's a custom health check handler, one should not be installed. - mux = http.NewServeMux() - mux.HandleFunc("/_ah/health", func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(418) - io.WriteString(w, "I'm short and stout!") - }) - try("mux with custom health checker", mux, 418, "I'm short and stout!") -} diff --git a/vendor/google.golang.org/appengine/internal/net_test.go b/vendor/google.golang.org/appengine/internal/net_test.go deleted file mode 100644 index 24da8bb2b15b..000000000000 --- a/vendor/google.golang.org/appengine/internal/net_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// +build !appengine - -package internal - -import ( - "sync" - "testing" - "time" - - netcontext "golang.org/x/net/context" - - basepb "google.golang.org/appengine/internal/base" -) - -func TestDialLimit(t *testing.T) { - // Fill up semaphore with false acquisitions to permit only two TCP connections at a time. - // We don't replace limitSem because that results in a data race when net/http lazily closes connections. - nFake := cap(limitSem) - 2 - for i := 0; i < nFake; i++ { - limitSem <- 1 - } - defer func() { - for i := 0; i < nFake; i++ { - <-limitSem - } - }() - - f, c, cleanup := setup() // setup is in api_test.go - defer cleanup() - f.hang = make(chan int) - - // If we make two RunSlowly RPCs (which will wait for f.hang to be strobed), - // then the simple Non200 RPC should hang. - var wg sync.WaitGroup - wg.Add(2) - for i := 0; i < 2; i++ { - go func() { - defer wg.Done() - Call(toContext(c), "errors", "RunSlowly", &basepb.VoidProto{}, &basepb.VoidProto{}) - }() - } - time.Sleep(50 * time.Millisecond) // let those two RPCs start - - ctx, _ := netcontext.WithTimeout(toContext(c), 50*time.Millisecond) - err := Call(ctx, "errors", "Non200", &basepb.VoidProto{}, &basepb.VoidProto{}) - if err != errTimeout { - t.Errorf("Non200 RPC returned with err %v, want errTimeout", err) - } - - // Drain the two RunSlowly calls. - f.hang <- 1 - f.hang <- 1 - wg.Wait() -} diff --git a/vendor/google.golang.org/appengine/namespace_test.go b/vendor/google.golang.org/appengine/namespace_test.go deleted file mode 100644 index 847f640bd0b2..000000000000 --- a/vendor/google.golang.org/appengine/namespace_test.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -package appengine - -import ( - "testing" - - "golang.org/x/net/context" -) - -func TestNamespaceValidity(t *testing.T) { - testCases := []struct { - namespace string - ok bool - }{ - // data from Python's namespace_manager_test.py - {"", true}, - {"__a.namespace.123__", true}, - {"-_A....NAMESPACE-_", true}, - {"-", true}, - {".", true}, - {".-", true}, - - {"?", false}, - {"+", false}, - {"!", false}, - {" ", false}, - } - for _, tc := range testCases { - _, err := Namespace(context.Background(), tc.namespace) - if err == nil && !tc.ok { - t.Errorf("Namespace %q should be rejected, but wasn't", tc.namespace) - } else if err != nil && tc.ok { - t.Errorf("Namespace %q should be accepted, but wasn't", tc.namespace) - } - } -} diff --git a/vendor/gopkg.in/yaml.v2/BUILD b/vendor/gopkg.in/yaml.v2/BUILD index 084a3980a705..297cfb89d14f 100644 --- a/vendor/gopkg.in/yaml.v2/BUILD +++ b/vendor/gopkg.in/yaml.v2/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -21,20 +21,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_xtest", - srcs = [ - "decode_test.go", - "encode_test.go", - "suite_test.go", - ], - importpath = "gopkg.in/yaml.v2_test", - deps = [ - ":go_default_library", - "//vendor/gopkg.in/check.v1:go_default_library", - ], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/gopkg.in/yaml.v2/decode_test.go b/vendor/gopkg.in/yaml.v2/decode_test.go deleted file mode 100644 index c159760b64f9..000000000000 --- a/vendor/gopkg.in/yaml.v2/decode_test.go +++ /dev/null @@ -1,988 +0,0 @@ -package yaml_test - -import ( - "errors" - . "gopkg.in/check.v1" - "gopkg.in/yaml.v2" - "math" - "net" - "reflect" - "strings" - "time" -) - -var unmarshalIntTest = 123 - -var unmarshalTests = []struct { - data string - value interface{} -}{ - { - "", - &struct{}{}, - }, { - "{}", &struct{}{}, - }, { - "v: hi", - map[string]string{"v": "hi"}, - }, { - "v: hi", map[string]interface{}{"v": "hi"}, - }, { - "v: true", - map[string]string{"v": "true"}, - }, { - "v: true", - map[string]interface{}{"v": true}, - }, { - "v: 10", - map[string]interface{}{"v": 10}, - }, { - "v: 0b10", - map[string]interface{}{"v": 2}, - }, { - "v: 0xA", - map[string]interface{}{"v": 10}, - }, { - "v: 4294967296", - map[string]int64{"v": 4294967296}, - }, { - "v: 0.1", - map[string]interface{}{"v": 0.1}, - }, { - "v: .1", - map[string]interface{}{"v": 0.1}, - }, { - "v: .Inf", - map[string]interface{}{"v": math.Inf(+1)}, - }, { - "v: -.Inf", - map[string]interface{}{"v": math.Inf(-1)}, - }, { - "v: -10", - map[string]interface{}{"v": -10}, - }, { - "v: -.1", - map[string]interface{}{"v": -0.1}, - }, - - // Simple values. - { - "123", - &unmarshalIntTest, - }, - - // Floats from spec - { - "canonical: 6.8523e+5", - map[string]interface{}{"canonical": 6.8523e+5}, - }, { - "expo: 685.230_15e+03", - map[string]interface{}{"expo": 685.23015e+03}, - }, { - "fixed: 685_230.15", - map[string]interface{}{"fixed": 685230.15}, - }, { - "neginf: -.inf", - map[string]interface{}{"neginf": math.Inf(-1)}, - }, { - "fixed: 685_230.15", - map[string]float64{"fixed": 685230.15}, - }, - //{"sexa: 190:20:30.15", map[string]interface{}{"sexa": 0}}, // Unsupported - //{"notanum: .NaN", map[string]interface{}{"notanum": math.NaN()}}, // Equality of NaN fails. - - // Bools from spec - { - "canonical: y", - map[string]interface{}{"canonical": true}, - }, { - "answer: NO", - map[string]interface{}{"answer": false}, - }, { - "logical: True", - map[string]interface{}{"logical": true}, - }, { - "option: on", - map[string]interface{}{"option": true}, - }, { - "option: on", - map[string]bool{"option": true}, - }, - // Ints from spec - { - "canonical: 685230", - map[string]interface{}{"canonical": 685230}, - }, { - "decimal: +685_230", - map[string]interface{}{"decimal": 685230}, - }, { - "octal: 02472256", - map[string]interface{}{"octal": 685230}, - }, { - "hexa: 0x_0A_74_AE", - map[string]interface{}{"hexa": 685230}, - }, { - "bin: 0b1010_0111_0100_1010_1110", - map[string]interface{}{"bin": 685230}, - }, { - "bin: -0b101010", - map[string]interface{}{"bin": -42}, - }, { - "decimal: +685_230", - map[string]int{"decimal": 685230}, - }, - - //{"sexa: 190:20:30", map[string]interface{}{"sexa": 0}}, // Unsupported - - // Nulls from spec - { - "empty:", - map[string]interface{}{"empty": nil}, - }, { - "canonical: ~", - map[string]interface{}{"canonical": nil}, - }, { - "english: null", - map[string]interface{}{"english": nil}, - }, { - "~: null key", - map[interface{}]string{nil: "null key"}, - }, { - "empty:", - map[string]*bool{"empty": nil}, - }, - - // Flow sequence - { - "seq: [A,B]", - map[string]interface{}{"seq": []interface{}{"A", "B"}}, - }, { - "seq: [A,B,C,]", - map[string][]string{"seq": []string{"A", "B", "C"}}, - }, { - "seq: [A,1,C]", - map[string][]string{"seq": []string{"A", "1", "C"}}, - }, { - "seq: [A,1,C]", - map[string][]int{"seq": []int{1}}, - }, { - "seq: [A,1,C]", - map[string]interface{}{"seq": []interface{}{"A", 1, "C"}}, - }, - // Block sequence - { - "seq:\n - A\n - B", - map[string]interface{}{"seq": []interface{}{"A", "B"}}, - }, { - "seq:\n - A\n - B\n - C", - map[string][]string{"seq": []string{"A", "B", "C"}}, - }, { - "seq:\n - A\n - 1\n - C", - map[string][]string{"seq": []string{"A", "1", "C"}}, - }, { - "seq:\n - A\n - 1\n - C", - map[string][]int{"seq": []int{1}}, - }, { - "seq:\n - A\n - 1\n - C", - map[string]interface{}{"seq": []interface{}{"A", 1, "C"}}, - }, - - // Literal block scalar - { - "scalar: | # Comment\n\n literal\n\n \ttext\n\n", - map[string]string{"scalar": "\nliteral\n\n\ttext\n"}, - }, - - // Folded block scalar - { - "scalar: > # Comment\n\n folded\n line\n \n next\n line\n * one\n * two\n\n last\n line\n\n", - map[string]string{"scalar": "\nfolded line\nnext line\n * one\n * two\n\nlast line\n"}, - }, - - // Map inside interface with no type hints. - { - "a: {b: c}", - map[interface{}]interface{}{"a": map[interface{}]interface{}{"b": "c"}}, - }, - - // Structs and type conversions. - { - "hello: world", - &struct{ Hello string }{"world"}, - }, { - "a: {b: c}", - &struct{ A struct{ B string } }{struct{ B string }{"c"}}, - }, { - "a: {b: c}", - &struct{ A *struct{ B string } }{&struct{ B string }{"c"}}, - }, { - "a: {b: c}", - &struct{ A map[string]string }{map[string]string{"b": "c"}}, - }, { - "a: {b: c}", - &struct{ A *map[string]string }{&map[string]string{"b": "c"}}, - }, { - "a:", - &struct{ A map[string]string }{}, - }, { - "a: 1", - &struct{ A int }{1}, - }, { - "a: 1", - &struct{ A float64 }{1}, - }, { - "a: 1.0", - &struct{ A int }{1}, - }, { - "a: 1.0", - &struct{ A uint }{1}, - }, { - "a: [1, 2]", - &struct{ A []int }{[]int{1, 2}}, - }, { - "a: 1", - &struct{ B int }{0}, - }, { - "a: 1", - &struct { - B int "a" - }{1}, - }, { - "a: y", - &struct{ A bool }{true}, - }, - - // Some cross type conversions - { - "v: 42", - map[string]uint{"v": 42}, - }, { - "v: -42", - map[string]uint{}, - }, { - "v: 4294967296", - map[string]uint64{"v": 4294967296}, - }, { - "v: -4294967296", - map[string]uint64{}, - }, - - // int - { - "int_max: 2147483647", - map[string]int{"int_max": math.MaxInt32}, - }, - { - "int_min: -2147483648", - map[string]int{"int_min": math.MinInt32}, - }, - { - "int_overflow: 9223372036854775808", // math.MaxInt64 + 1 - map[string]int{}, - }, - - // int64 - { - "int64_max: 9223372036854775807", - map[string]int64{"int64_max": math.MaxInt64}, - }, - { - "int64_max_base2: 0b111111111111111111111111111111111111111111111111111111111111111", - map[string]int64{"int64_max_base2": math.MaxInt64}, - }, - { - "int64_min: -9223372036854775808", - map[string]int64{"int64_min": math.MinInt64}, - }, - { - "int64_neg_base2: -0b111111111111111111111111111111111111111111111111111111111111111", - map[string]int64{"int64_neg_base2": -math.MaxInt64}, - }, - { - "int64_overflow: 9223372036854775808", // math.MaxInt64 + 1 - map[string]int64{}, - }, - - // uint - { - "uint_min: 0", - map[string]uint{"uint_min": 0}, - }, - { - "uint_max: 4294967295", - map[string]uint{"uint_max": math.MaxUint32}, - }, - { - "uint_underflow: -1", - map[string]uint{}, - }, - - // uint64 - { - "uint64_min: 0", - map[string]uint{"uint64_min": 0}, - }, - { - "uint64_max: 18446744073709551615", - map[string]uint64{"uint64_max": math.MaxUint64}, - }, - { - "uint64_max_base2: 0b1111111111111111111111111111111111111111111111111111111111111111", - map[string]uint64{"uint64_max_base2": math.MaxUint64}, - }, - { - "uint64_maxint64: 9223372036854775807", - map[string]uint64{"uint64_maxint64": math.MaxInt64}, - }, - { - "uint64_underflow: -1", - map[string]uint64{}, - }, - - // float32 - { - "float32_max: 3.40282346638528859811704183484516925440e+38", - map[string]float32{"float32_max": math.MaxFloat32}, - }, - { - "float32_nonzero: 1.401298464324817070923729583289916131280e-45", - map[string]float32{"float32_nonzero": math.SmallestNonzeroFloat32}, - }, - { - "float32_maxuint64: 18446744073709551615", - map[string]float32{"float32_maxuint64": float32(math.MaxUint64)}, - }, - { - "float32_maxuint64+1: 18446744073709551616", - map[string]float32{"float32_maxuint64+1": float32(math.MaxUint64 + 1)}, - }, - - // float64 - { - "float64_max: 1.797693134862315708145274237317043567981e+308", - map[string]float64{"float64_max": math.MaxFloat64}, - }, - { - "float64_nonzero: 4.940656458412465441765687928682213723651e-324", - map[string]float64{"float64_nonzero": math.SmallestNonzeroFloat64}, - }, - { - "float64_maxuint64: 18446744073709551615", - map[string]float64{"float64_maxuint64": float64(math.MaxUint64)}, - }, - { - "float64_maxuint64+1: 18446744073709551616", - map[string]float64{"float64_maxuint64+1": float64(math.MaxUint64 + 1)}, - }, - - // Overflow cases. - { - "v: 4294967297", - map[string]int32{}, - }, { - "v: 128", - map[string]int8{}, - }, - - // Quoted values. - { - "'1': '\"2\"'", - map[interface{}]interface{}{"1": "\"2\""}, - }, { - "v:\n- A\n- 'B\n\n C'\n", - map[string][]string{"v": []string{"A", "B\nC"}}, - }, - - // Explicit tags. - { - "v: !!float '1.1'", - map[string]interface{}{"v": 1.1}, - }, { - "v: !!null ''", - map[string]interface{}{"v": nil}, - }, { - "%TAG !y! tag:yaml.org,2002:\n---\nv: !y!int '1'", - map[string]interface{}{"v": 1}, - }, - - // Anchors and aliases. - { - "a: &x 1\nb: &y 2\nc: *x\nd: *y\n", - &struct{ A, B, C, D int }{1, 2, 1, 2}, - }, { - "a: &a {c: 1}\nb: *a", - &struct { - A, B struct { - C int - } - }{struct{ C int }{1}, struct{ C int }{1}}, - }, { - "a: &a [1, 2]\nb: *a", - &struct{ B []int }{[]int{1, 2}}, - }, { - "b: *a\na: &a {c: 1}", - &struct { - A, B struct { - C int - } - }{struct{ C int }{1}, struct{ C int }{1}}, - }, - - // Bug #1133337 - { - "foo: ''", - map[string]*string{"foo": new(string)}, - }, { - "foo: null", - map[string]string{"foo": ""}, - }, { - "foo: null", - map[string]interface{}{"foo": nil}, - }, - - // Ignored field - { - "a: 1\nb: 2\n", - &struct { - A int - B int "-" - }{1, 0}, - }, - - // Bug #1191981 - { - "" + - "%YAML 1.1\n" + - "--- !!str\n" + - `"Generic line break (no glyph)\n\` + "\n" + - ` Generic line break (glyphed)\n\` + "\n" + - ` Line separator\u2028\` + "\n" + - ` Paragraph separator\u2029"` + "\n", - "" + - "Generic line break (no glyph)\n" + - "Generic line break (glyphed)\n" + - "Line separator\u2028Paragraph separator\u2029", - }, - - // Struct inlining - { - "a: 1\nb: 2\nc: 3\n", - &struct { - A int - C inlineB `yaml:",inline"` - }{1, inlineB{2, inlineC{3}}}, - }, - - // Map inlining - { - "a: 1\nb: 2\nc: 3\n", - &struct { - A int - C map[string]int `yaml:",inline"` - }{1, map[string]int{"b": 2, "c": 3}}, - }, - - // bug 1243827 - { - "a: -b_c", - map[string]interface{}{"a": "-b_c"}, - }, - { - "a: +b_c", - map[string]interface{}{"a": "+b_c"}, - }, - { - "a: 50cent_of_dollar", - map[string]interface{}{"a": "50cent_of_dollar"}, - }, - - // Duration - { - "a: 3s", - map[string]time.Duration{"a": 3 * time.Second}, - }, - - // Issue #24. - { - "a: ", - map[string]string{"a": ""}, - }, - - // Base 60 floats are obsolete and unsupported. - { - "a: 1:1\n", - map[string]string{"a": "1:1"}, - }, - - // Binary data. - { - "a: !!binary gIGC\n", - map[string]string{"a": "\x80\x81\x82"}, - }, { - "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n", - map[string]string{"a": strings.Repeat("\x90", 54)}, - }, { - "a: !!binary |\n " + strings.Repeat("A", 70) + "\n ==\n", - map[string]string{"a": strings.Repeat("\x00", 52)}, - }, - - // Ordered maps. - { - "{b: 2, a: 1, d: 4, c: 3, sub: {e: 5}}", - &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}}, - }, - - // Issue #39. - { - "a:\n b:\n c: d\n", - map[string]struct{ B interface{} }{"a": {map[interface{}]interface{}{"c": "d"}}}, - }, - - // Custom map type. - { - "a: {b: c}", - M{"a": M{"b": "c"}}, - }, - - // Support encoding.TextUnmarshaler. - { - "a: 1.2.3.4\n", - map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)}, - }, - { - "a: 2015-02-24T18:19:39Z\n", - map[string]time.Time{"a": time.Unix(1424801979, 0)}, - }, - - // Encode empty lists as zero-length slices. - { - "a: []", - &struct{ A []int }{[]int{}}, - }, - - // UTF-16-LE - { - "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n\x00", - M{"ñoño": "very yes"}, - }, - // UTF-16-LE with surrogate. - { - "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \x00=\xd8\xd4\xdf\n\x00", - M{"ñoño": "very yes 🟔"}, - }, - - // UTF-16-BE - { - "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n", - M{"ñoño": "very yes"}, - }, - // UTF-16-BE with surrogate. - { - "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \xd8=\xdf\xd4\x00\n", - M{"ñoño": "very yes 🟔"}, - }, -} - -type M map[interface{}]interface{} - -type inlineB struct { - B int - inlineC `yaml:",inline"` -} - -type inlineC struct { - C int -} - -func (s *S) TestUnmarshal(c *C) { - for _, item := range unmarshalTests { - t := reflect.ValueOf(item.value).Type() - var value interface{} - switch t.Kind() { - case reflect.Map: - value = reflect.MakeMap(t).Interface() - case reflect.String: - value = reflect.New(t).Interface() - case reflect.Ptr: - value = reflect.New(t.Elem()).Interface() - default: - c.Fatalf("missing case for %s", t) - } - err := yaml.Unmarshal([]byte(item.data), value) - if _, ok := err.(*yaml.TypeError); !ok { - c.Assert(err, IsNil) - } - if t.Kind() == reflect.String { - c.Assert(*value.(*string), Equals, item.value) - } else { - c.Assert(value, DeepEquals, item.value) - } - } -} - -func (s *S) TestUnmarshalNaN(c *C) { - value := map[string]interface{}{} - err := yaml.Unmarshal([]byte("notanum: .NaN"), &value) - c.Assert(err, IsNil) - c.Assert(math.IsNaN(value["notanum"].(float64)), Equals, true) -} - -var unmarshalErrorTests = []struct { - data, error string -}{ - {"v: !!float 'error'", "yaml: cannot decode !!str `error` as a !!float"}, - {"v: [A,", "yaml: line 1: did not find expected node content"}, - {"v:\n- [A,", "yaml: line 2: did not find expected node content"}, - {"a: *b\n", "yaml: unknown anchor 'b' referenced"}, - {"a: &a\n b: *a\n", "yaml: anchor 'a' value contains itself"}, - {"value: -", "yaml: block sequence entries are not allowed in this context"}, - {"a: !!binary ==", "yaml: !!binary value contains invalid base64 data"}, - {"{[.]}", `yaml: invalid map key: \[\]interface \{\}\{"\."\}`}, - {"{{.}}", `yaml: invalid map key: map\[interface\ \{\}\]interface \{\}\{".":interface \{\}\(nil\)\}`}, -} - -func (s *S) TestUnmarshalErrors(c *C) { - for _, item := range unmarshalErrorTests { - var value interface{} - err := yaml.Unmarshal([]byte(item.data), &value) - c.Assert(err, ErrorMatches, item.error, Commentf("Partial unmarshal: %#v", value)) - } -} - -var unmarshalerTests = []struct { - data, tag string - value interface{} -}{ - {"_: {hi: there}", "!!map", map[interface{}]interface{}{"hi": "there"}}, - {"_: [1,A]", "!!seq", []interface{}{1, "A"}}, - {"_: 10", "!!int", 10}, - {"_: null", "!!null", nil}, - {`_: BAR!`, "!!str", "BAR!"}, - {`_: "BAR!"`, "!!str", "BAR!"}, - {"_: !!foo 'BAR!'", "!!foo", "BAR!"}, -} - -var unmarshalerResult = map[int]error{} - -type unmarshalerType struct { - value interface{} -} - -func (o *unmarshalerType) UnmarshalYAML(unmarshal func(v interface{}) error) error { - if err := unmarshal(&o.value); err != nil { - return err - } - if i, ok := o.value.(int); ok { - if result, ok := unmarshalerResult[i]; ok { - return result - } - } - return nil -} - -type unmarshalerPointer struct { - Field *unmarshalerType "_" -} - -type unmarshalerValue struct { - Field unmarshalerType "_" -} - -func (s *S) TestUnmarshalerPointerField(c *C) { - for _, item := range unmarshalerTests { - obj := &unmarshalerPointer{} - err := yaml.Unmarshal([]byte(item.data), obj) - c.Assert(err, IsNil) - if item.value == nil { - c.Assert(obj.Field, IsNil) - } else { - c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value)) - c.Assert(obj.Field.value, DeepEquals, item.value) - } - } -} - -func (s *S) TestUnmarshalerValueField(c *C) { - for _, item := range unmarshalerTests { - obj := &unmarshalerValue{} - err := yaml.Unmarshal([]byte(item.data), obj) - c.Assert(err, IsNil) - c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value)) - c.Assert(obj.Field.value, DeepEquals, item.value) - } -} - -func (s *S) TestUnmarshalerWholeDocument(c *C) { - obj := &unmarshalerType{} - err := yaml.Unmarshal([]byte(unmarshalerTests[0].data), obj) - c.Assert(err, IsNil) - value, ok := obj.value.(map[interface{}]interface{}) - c.Assert(ok, Equals, true, Commentf("value: %#v", obj.value)) - c.Assert(value["_"], DeepEquals, unmarshalerTests[0].value) -} - -func (s *S) TestUnmarshalerTypeError(c *C) { - unmarshalerResult[2] = &yaml.TypeError{[]string{"foo"}} - unmarshalerResult[4] = &yaml.TypeError{[]string{"bar"}} - defer func() { - delete(unmarshalerResult, 2) - delete(unmarshalerResult, 4) - }() - - type T struct { - Before int - After int - M map[string]*unmarshalerType - } - var v T - data := `{before: A, m: {abc: 1, def: 2, ghi: 3, jkl: 4}, after: B}` - err := yaml.Unmarshal([]byte(data), &v) - c.Assert(err, ErrorMatches, ""+ - "yaml: unmarshal errors:\n"+ - " line 1: cannot unmarshal !!str `A` into int\n"+ - " foo\n"+ - " bar\n"+ - " line 1: cannot unmarshal !!str `B` into int") - c.Assert(v.M["abc"], NotNil) - c.Assert(v.M["def"], IsNil) - c.Assert(v.M["ghi"], NotNil) - c.Assert(v.M["jkl"], IsNil) - - c.Assert(v.M["abc"].value, Equals, 1) - c.Assert(v.M["ghi"].value, Equals, 3) -} - -type proxyTypeError struct{} - -func (v *proxyTypeError) UnmarshalYAML(unmarshal func(interface{}) error) error { - var s string - var a int32 - var b int64 - if err := unmarshal(&s); err != nil { - panic(err) - } - if s == "a" { - if err := unmarshal(&b); err == nil { - panic("should have failed") - } - return unmarshal(&a) - } - if err := unmarshal(&a); err == nil { - panic("should have failed") - } - return unmarshal(&b) -} - -func (s *S) TestUnmarshalerTypeErrorProxying(c *C) { - type T struct { - Before int - After int - M map[string]*proxyTypeError - } - var v T - data := `{before: A, m: {abc: a, def: b}, after: B}` - err := yaml.Unmarshal([]byte(data), &v) - c.Assert(err, ErrorMatches, ""+ - "yaml: unmarshal errors:\n"+ - " line 1: cannot unmarshal !!str `A` into int\n"+ - " line 1: cannot unmarshal !!str `a` into int32\n"+ - " line 1: cannot unmarshal !!str `b` into int64\n"+ - " line 1: cannot unmarshal !!str `B` into int") -} - -type failingUnmarshaler struct{} - -var failingErr = errors.New("failingErr") - -func (ft *failingUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error { - return failingErr -} - -func (s *S) TestUnmarshalerError(c *C) { - err := yaml.Unmarshal([]byte("a: b"), &failingUnmarshaler{}) - c.Assert(err, Equals, failingErr) -} - -type sliceUnmarshaler []int - -func (su *sliceUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error { - var slice []int - err := unmarshal(&slice) - if err == nil { - *su = slice - return nil - } - - var intVal int - err = unmarshal(&intVal) - if err == nil { - *su = []int{intVal} - return nil - } - - return err -} - -func (s *S) TestUnmarshalerRetry(c *C) { - var su sliceUnmarshaler - err := yaml.Unmarshal([]byte("[1, 2, 3]"), &su) - c.Assert(err, IsNil) - c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1, 2, 3})) - - err = yaml.Unmarshal([]byte("1"), &su) - c.Assert(err, IsNil) - c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1})) -} - -// From http://yaml.org/type/merge.html -var mergeTests = ` -anchors: - list: - - &CENTER { "x": 1, "y": 2 } - - &LEFT { "x": 0, "y": 2 } - - &BIG { "r": 10 } - - &SMALL { "r": 1 } - -# All the following maps are equal: - -plain: - # Explicit keys - "x": 1 - "y": 2 - "r": 10 - label: center/big - -mergeOne: - # Merge one map - << : *CENTER - "r": 10 - label: center/big - -mergeMultiple: - # Merge multiple maps - << : [ *CENTER, *BIG ] - label: center/big - -override: - # Override - << : [ *BIG, *LEFT, *SMALL ] - "x": 1 - label: center/big - -shortTag: - # Explicit short merge tag - !!merge "<<" : [ *CENTER, *BIG ] - label: center/big - -longTag: - # Explicit merge long tag - ! "<<" : [ *CENTER, *BIG ] - label: center/big - -inlineMap: - # Inlined map - << : {"x": 1, "y": 2, "r": 10} - label: center/big - -inlineSequenceMap: - # Inlined map in sequence - << : [ *CENTER, {"r": 10} ] - label: center/big -` - -func (s *S) TestMerge(c *C) { - var want = map[interface{}]interface{}{ - "x": 1, - "y": 2, - "r": 10, - "label": "center/big", - } - - var m map[interface{}]interface{} - err := yaml.Unmarshal([]byte(mergeTests), &m) - c.Assert(err, IsNil) - for name, test := range m { - if name == "anchors" { - continue - } - c.Assert(test, DeepEquals, want, Commentf("test %q failed", name)) - } -} - -func (s *S) TestMergeStruct(c *C) { - type Data struct { - X, Y, R int - Label string - } - want := Data{1, 2, 10, "center/big"} - - var m map[string]Data - err := yaml.Unmarshal([]byte(mergeTests), &m) - c.Assert(err, IsNil) - for name, test := range m { - if name == "anchors" { - continue - } - c.Assert(test, Equals, want, Commentf("test %q failed", name)) - } -} - -var unmarshalNullTests = []func() interface{}{ - func() interface{} { var v interface{}; v = "v"; return &v }, - func() interface{} { var s = "s"; return &s }, - func() interface{} { var s = "s"; sptr := &s; return &sptr }, - func() interface{} { var i = 1; return &i }, - func() interface{} { var i = 1; iptr := &i; return &iptr }, - func() interface{} { m := map[string]int{"s": 1}; return &m }, - func() interface{} { m := map[string]int{"s": 1}; return m }, -} - -func (s *S) TestUnmarshalNull(c *C) { - for _, test := range unmarshalNullTests { - item := test() - zero := reflect.Zero(reflect.TypeOf(item).Elem()).Interface() - err := yaml.Unmarshal([]byte("null"), item) - c.Assert(err, IsNil) - if reflect.TypeOf(item).Kind() == reflect.Map { - c.Assert(reflect.ValueOf(item).Interface(), DeepEquals, reflect.MakeMap(reflect.TypeOf(item)).Interface()) - } else { - c.Assert(reflect.ValueOf(item).Elem().Interface(), DeepEquals, zero) - } - } -} - -func (s *S) TestUnmarshalSliceOnPreset(c *C) { - // Issue #48. - v := struct{ A []int }{[]int{1}} - yaml.Unmarshal([]byte("a: [2]"), &v) - c.Assert(v.A, DeepEquals, []int{2}) -} - -//var data []byte -//func init() { -// var err error -// data, err = ioutil.ReadFile("/tmp/file.yaml") -// if err != nil { -// panic(err) -// } -//} -// -//func (s *S) BenchmarkUnmarshal(c *C) { -// var err error -// for i := 0; i < c.N; i++ { -// var v map[string]interface{} -// err = yaml.Unmarshal(data, &v) -// } -// if err != nil { -// panic(err) -// } -//} -// -//func (s *S) BenchmarkMarshal(c *C) { -// var v map[string]interface{} -// yaml.Unmarshal(data, &v) -// c.ResetTimer() -// for i := 0; i < c.N; i++ { -// yaml.Marshal(&v) -// } -//} diff --git a/vendor/gopkg.in/yaml.v2/encode_test.go b/vendor/gopkg.in/yaml.v2/encode_test.go deleted file mode 100644 index 84099bd3850a..000000000000 --- a/vendor/gopkg.in/yaml.v2/encode_test.go +++ /dev/null @@ -1,501 +0,0 @@ -package yaml_test - -import ( - "fmt" - "math" - "strconv" - "strings" - "time" - - . "gopkg.in/check.v1" - "gopkg.in/yaml.v2" - "net" - "os" -) - -var marshalIntTest = 123 - -var marshalTests = []struct { - value interface{} - data string -}{ - { - nil, - "null\n", - }, { - &struct{}{}, - "{}\n", - }, { - map[string]string{"v": "hi"}, - "v: hi\n", - }, { - map[string]interface{}{"v": "hi"}, - "v: hi\n", - }, { - map[string]string{"v": "true"}, - "v: \"true\"\n", - }, { - map[string]string{"v": "false"}, - "v: \"false\"\n", - }, { - map[string]interface{}{"v": true}, - "v: true\n", - }, { - map[string]interface{}{"v": false}, - "v: false\n", - }, { - map[string]interface{}{"v": 10}, - "v: 10\n", - }, { - map[string]interface{}{"v": -10}, - "v: -10\n", - }, { - map[string]uint{"v": 42}, - "v: 42\n", - }, { - map[string]interface{}{"v": int64(4294967296)}, - "v: 4294967296\n", - }, { - map[string]int64{"v": int64(4294967296)}, - "v: 4294967296\n", - }, { - map[string]uint64{"v": 4294967296}, - "v: 4294967296\n", - }, { - map[string]interface{}{"v": "10"}, - "v: \"10\"\n", - }, { - map[string]interface{}{"v": 0.1}, - "v: 0.1\n", - }, { - map[string]interface{}{"v": float64(0.1)}, - "v: 0.1\n", - }, { - map[string]interface{}{"v": -0.1}, - "v: -0.1\n", - }, { - map[string]interface{}{"v": math.Inf(+1)}, - "v: .inf\n", - }, { - map[string]interface{}{"v": math.Inf(-1)}, - "v: -.inf\n", - }, { - map[string]interface{}{"v": math.NaN()}, - "v: .nan\n", - }, { - map[string]interface{}{"v": nil}, - "v: null\n", - }, { - map[string]interface{}{"v": ""}, - "v: \"\"\n", - }, { - map[string][]string{"v": []string{"A", "B"}}, - "v:\n- A\n- B\n", - }, { - map[string][]string{"v": []string{"A", "B\nC"}}, - "v:\n- A\n- |-\n B\n C\n", - }, { - map[string][]interface{}{"v": []interface{}{"A", 1, map[string][]int{"B": []int{2, 3}}}}, - "v:\n- A\n- 1\n- B:\n - 2\n - 3\n", - }, { - map[string]interface{}{"a": map[interface{}]interface{}{"b": "c"}}, - "a:\n b: c\n", - }, { - map[string]interface{}{"a": "-"}, - "a: '-'\n", - }, - - // Simple values. - { - &marshalIntTest, - "123\n", - }, - - // Structures - { - &struct{ Hello string }{"world"}, - "hello: world\n", - }, { - &struct { - A struct { - B string - } - }{struct{ B string }{"c"}}, - "a:\n b: c\n", - }, { - &struct { - A *struct { - B string - } - }{&struct{ B string }{"c"}}, - "a:\n b: c\n", - }, { - &struct { - A *struct { - B string - } - }{}, - "a: null\n", - }, { - &struct{ A int }{1}, - "a: 1\n", - }, { - &struct{ A []int }{[]int{1, 2}}, - "a:\n- 1\n- 2\n", - }, { - &struct { - B int "a" - }{1}, - "a: 1\n", - }, { - &struct{ A bool }{true}, - "a: true\n", - }, - - // Conditional flag - { - &struct { - A int "a,omitempty" - B int "b,omitempty" - }{1, 0}, - "a: 1\n", - }, { - &struct { - A int "a,omitempty" - B int "b,omitempty" - }{0, 0}, - "{}\n", - }, { - &struct { - A *struct{ X, y int } "a,omitempty,flow" - }{&struct{ X, y int }{1, 2}}, - "a: {x: 1}\n", - }, { - &struct { - A *struct{ X, y int } "a,omitempty,flow" - }{nil}, - "{}\n", - }, { - &struct { - A *struct{ X, y int } "a,omitempty,flow" - }{&struct{ X, y int }{}}, - "a: {x: 0}\n", - }, { - &struct { - A struct{ X, y int } "a,omitempty,flow" - }{struct{ X, y int }{1, 2}}, - "a: {x: 1}\n", - }, { - &struct { - A struct{ X, y int } "a,omitempty,flow" - }{struct{ X, y int }{0, 1}}, - "{}\n", - }, { - &struct { - A float64 "a,omitempty" - B float64 "b,omitempty" - }{1, 0}, - "a: 1\n", - }, - - // Flow flag - { - &struct { - A []int "a,flow" - }{[]int{1, 2}}, - "a: [1, 2]\n", - }, { - &struct { - A map[string]string "a,flow" - }{map[string]string{"b": "c", "d": "e"}}, - "a: {b: c, d: e}\n", - }, { - &struct { - A struct { - B, D string - } "a,flow" - }{struct{ B, D string }{"c", "e"}}, - "a: {b: c, d: e}\n", - }, - - // Unexported field - { - &struct { - u int - A int - }{0, 1}, - "a: 1\n", - }, - - // Ignored field - { - &struct { - A int - B int "-" - }{1, 2}, - "a: 1\n", - }, - - // Struct inlining - { - &struct { - A int - C inlineB `yaml:",inline"` - }{1, inlineB{2, inlineC{3}}}, - "a: 1\nb: 2\nc: 3\n", - }, - - // Map inlining - { - &struct { - A int - C map[string]int `yaml:",inline"` - }{1, map[string]int{"b": 2, "c": 3}}, - "a: 1\nb: 2\nc: 3\n", - }, - - // Duration - { - map[string]time.Duration{"a": 3 * time.Second}, - "a: 3s\n", - }, - - // Issue #24: bug in map merging logic. - { - map[string]string{"a": ""}, - "a: \n", - }, - - // Issue #34: marshal unsupported base 60 floats quoted for compatibility - // with old YAML 1.1 parsers. - { - map[string]string{"a": "1:1"}, - "a: \"1:1\"\n", - }, - - // Binary data. - { - map[string]string{"a": "\x00"}, - "a: \"\\0\"\n", - }, { - map[string]string{"a": "\x80\x81\x82"}, - "a: !!binary gIGC\n", - }, { - map[string]string{"a": strings.Repeat("\x90", 54)}, - "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n", - }, - - // Ordered maps. - { - &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}}, - "b: 2\na: 1\nd: 4\nc: 3\nsub:\n e: 5\n", - }, - - // Encode unicode as utf-8 rather than in escaped form. - { - map[string]string{"a": "你好"}, - "a: 你好\n", - }, - - // Support encoding.TextMarshaler. - { - map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)}, - "a: 1.2.3.4\n", - }, - { - map[string]time.Time{"a": time.Unix(1424801979, 0)}, - "a: 2015-02-24T18:19:39Z\n", - }, - - // Ensure strings containing ": " are quoted (reported as PR #43, but not reproducible). - { - map[string]string{"a": "b: c"}, - "a: 'b: c'\n", - }, - - // Containing hash mark ('#') in string should be quoted - { - map[string]string{"a": "Hello #comment"}, - "a: 'Hello #comment'\n", - }, - { - map[string]string{"a": "你好 #comment"}, - "a: '你好 #comment'\n", - }, -} - -func (s *S) TestMarshal(c *C) { - defer os.Setenv("TZ", os.Getenv("TZ")) - os.Setenv("TZ", "UTC") - for _, item := range marshalTests { - data, err := yaml.Marshal(item.value) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, item.data) - } -} - -var marshalErrorTests = []struct { - value interface{} - error string - panic string -}{{ - value: &struct { - B int - inlineB ",inline" - }{1, inlineB{2, inlineC{3}}}, - panic: `Duplicated key 'b' in struct struct \{ B int; .*`, -}, { - value: &struct { - A int - B map[string]int ",inline" - }{1, map[string]int{"a": 2}}, - panic: `Can't have key "a" in inlined map; conflicts with struct field`, -}} - -func (s *S) TestMarshalErrors(c *C) { - for _, item := range marshalErrorTests { - if item.panic != "" { - c.Assert(func() { yaml.Marshal(item.value) }, PanicMatches, item.panic) - } else { - _, err := yaml.Marshal(item.value) - c.Assert(err, ErrorMatches, item.error) - } - } -} - -func (s *S) TestMarshalTypeCache(c *C) { - var data []byte - var err error - func() { - type T struct{ A int } - data, err = yaml.Marshal(&T{}) - c.Assert(err, IsNil) - }() - func() { - type T struct{ B int } - data, err = yaml.Marshal(&T{}) - c.Assert(err, IsNil) - }() - c.Assert(string(data), Equals, "b: 0\n") -} - -var marshalerTests = []struct { - data string - value interface{} -}{ - {"_:\n hi: there\n", map[interface{}]interface{}{"hi": "there"}}, - {"_:\n- 1\n- A\n", []interface{}{1, "A"}}, - {"_: 10\n", 10}, - {"_: null\n", nil}, - {"_: BAR!\n", "BAR!"}, -} - -type marshalerType struct { - value interface{} -} - -func (o marshalerType) MarshalText() ([]byte, error) { - panic("MarshalText called on type with MarshalYAML") -} - -func (o marshalerType) MarshalYAML() (interface{}, error) { - return o.value, nil -} - -type marshalerValue struct { - Field marshalerType "_" -} - -func (s *S) TestMarshaler(c *C) { - for _, item := range marshalerTests { - obj := &marshalerValue{} - obj.Field.value = item.value - data, err := yaml.Marshal(obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, string(item.data)) - } -} - -func (s *S) TestMarshalerWholeDocument(c *C) { - obj := &marshalerType{} - obj.value = map[string]string{"hello": "world!"} - data, err := yaml.Marshal(obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, "hello: world!\n") -} - -type failingMarshaler struct{} - -func (ft *failingMarshaler) MarshalYAML() (interface{}, error) { - return nil, failingErr -} - -func (s *S) TestMarshalerError(c *C) { - _, err := yaml.Marshal(&failingMarshaler{}) - c.Assert(err, Equals, failingErr) -} - -func (s *S) TestSortedOutput(c *C) { - order := []interface{}{ - false, - true, - 1, - uint(1), - 1.0, - 1.1, - 1.2, - 2, - uint(2), - 2.0, - 2.1, - "", - ".1", - ".2", - ".a", - "1", - "2", - "a!10", - "a/2", - "a/10", - "a~10", - "ab/1", - "b/1", - "b/01", - "b/2", - "b/02", - "b/3", - "b/03", - "b1", - "b01", - "b3", - "c2.10", - "c10.2", - "d1", - "d12", - "d12a", - } - m := make(map[interface{}]int) - for _, k := range order { - m[k] = 1 - } - data, err := yaml.Marshal(m) - c.Assert(err, IsNil) - out := "\n" + string(data) - last := 0 - for i, k := range order { - repr := fmt.Sprint(k) - if s, ok := k.(string); ok { - if _, err = strconv.ParseFloat(repr, 32); s == "" || err == nil { - repr = `"` + repr + `"` - } - } - index := strings.Index(out, "\n"+repr+":") - if index == -1 { - c.Fatalf("%#v is not in the output: %#v", k, out) - } - if index < last { - c.Fatalf("%#v was generated before %#v: %q", k, order[i-1], out) - } - last = index - } -} diff --git a/vendor/gopkg.in/yaml.v2/suite_test.go b/vendor/gopkg.in/yaml.v2/suite_test.go deleted file mode 100644 index c5cf1ed4f6e6..000000000000 --- a/vendor/gopkg.in/yaml.v2/suite_test.go +++ /dev/null @@ -1,12 +0,0 @@ -package yaml_test - -import ( - . "gopkg.in/check.v1" - "testing" -) - -func Test(t *testing.T) { TestingT(t) } - -type S struct{} - -var _ = Suite(&S{}) diff --git a/vendor/k8s.io/contrib/test-utils/utils/BUILD b/vendor/k8s.io/contrib/test-utils/utils/BUILD index c5968224bed3..b600913aa5db 100644 --- a/vendor/k8s.io/contrib/test-utils/utils/BUILD +++ b/vendor/k8s.io/contrib/test-utils/utils/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -11,16 +11,6 @@ go_library( deps = ["//vendor/github.com/golang/glog:go_default_library"], ) -go_test( - name = "go_default_test", - srcs = [ - "bucket_test.go", - "utils_test.go", - ], - importpath = "k8s.io/contrib/test-utils/utils", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/k8s.io/contrib/test-utils/utils/bucket_test.go b/vendor/k8s.io/contrib/test-utils/utils/bucket_test.go deleted file mode 100644 index 9072cdf14ca5..000000000000 --- a/vendor/k8s.io/contrib/test-utils/utils/bucket_test.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package utils - -import ( - "testing" -) - -func TestExpandListURL(t *testing.T) { - table := []struct { - bucket string - pathParts []interface{} - expect string - }{ - { - bucket: "kubernetes-jenkins", - pathParts: []interface{}{"logs", "kubernetes-gce-e2e", 1458, "artifacts", "junit"}, - expect: "https://www.googleapis.com/storage/v1/b/kubernetes-jenkins/o?prefix=logs%2Fkubernetes-gce-e2e%2F1458%2Fartifacts%2Fjunit", - }, - } - - for _, tt := range table { - b := NewBucket(tt.bucket) - out := b.ExpandListURL(tt.pathParts...).String() - if out != tt.expect { - t.Errorf("Expected %v but got %v", tt.expect, out) - } - } -} diff --git a/vendor/k8s.io/contrib/test-utils/utils/utils_test.go b/vendor/k8s.io/contrib/test-utils/utils/utils_test.go deleted file mode 100644 index a43d6f3a8275..000000000000 --- a/vendor/k8s.io/contrib/test-utils/utils/utils_test.go +++ /dev/null @@ -1,76 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package utils - -import ( - "fmt" - "net/http" - "net/http/httptest" - "testing" -) - -func TestGetPathToJenkinsGoogleBucket(t *testing.T) { - const ( - bucket = "kubernetes-jenkins" - dir = "logs" - pullDir = "pr-logs" - pullKey = "pull" - ) - table := []struct { - job string - build int - expect string - }{ - { - job: "kubernetes-gce-e2e", - build: 1458, - expect: "/kubernetes-jenkins/logs/kubernetes-gce-e2e/1458/", - }, - { - job: "kubernetes-pull-build-test-e2e-gce", - build: 46924, - expect: "/kubernetes-jenkins/pr-logs/pull/27898/kubernetes-pull-build-test-e2e-gce/46924/", - }, - } - - m := http.NewServeMux() - m.HandleFunc( - "/kubernetes-jenkins/pr-logs/directory/kubernetes-pull-build-test-e2e-gce/46924.txt", - func(w http.ResponseWriter, req *http.Request) { - w.WriteHeader(http.StatusOK) - fmt.Fprint(w, "gs://kubernetes-jenkins/pr-logs/pull/27898/kubernetes-pull-build-test-e2e-gce/46924\n") - }, - ) - m.HandleFunc( - "/", - func(w http.ResponseWriter, req *http.Request) { - t.Errorf("Unexpected request to %v", req.URL.String()) - http.NotFound(w, req) - }, - ) - server := httptest.NewServer(m) - defer server.Close() - - for _, tt := range table { - u := NewWithPresubmitDetection(bucket, dir, pullKey, pullDir) - u.bucket = NewTestBucket(bucket, server.URL) - out := u.GetPathToJenkinsGoogleBucket(tt.job, tt.build) - if out != tt.expect { - t.Errorf("Expected %v but got %v", tt.expect, out) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/util/BUILD b/vendor/k8s.io/kubernetes/pkg/util/BUILD index 1934187ba053..21154e0ae4c4 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/BUILD +++ b/vendor/k8s.io/kubernetes/pkg/util/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -20,20 +20,6 @@ go_library( deps = ["//vendor/github.com/golang/glog:go_default_library"], ) -go_test( - name = "go_default_test", - srcs = [ - "template_test.go", - "util_test.go", - ], - importpath = "k8s.io/kubernetes/pkg/util", - library = ":go_default_library", - deps = [ - "//vendor/github.com/stretchr/testify/assert:go_default_library", - "//vendor/k8s.io/kubernetes/pkg/util/diff:go_default_library", - ], -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/k8s.io/kubernetes/pkg/util/clock/BUILD b/vendor/k8s.io/kubernetes/pkg/util/clock/BUILD index b1d88da97c4c..3aa56726d2c6 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/clock/BUILD +++ b/vendor/k8s.io/kubernetes/pkg/util/clock/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -7,13 +7,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = ["clock_test.go"], - importpath = "k8s.io/kubernetes/pkg/util/clock", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/k8s.io/kubernetes/pkg/util/clock/clock_test.go b/vendor/k8s.io/kubernetes/pkg/util/clock/clock_test.go deleted file mode 100644 index 27d34605f509..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/util/clock/clock_test.go +++ /dev/null @@ -1,184 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package clock - -import ( - "testing" - "time" -) - -func TestFakeClock(t *testing.T) { - startTime := time.Now() - tc := NewFakeClock(startTime) - tc.Step(time.Second) - now := tc.Now() - if now.Sub(startTime) != time.Second { - t.Errorf("input: %s now=%s gap=%s expected=%s", startTime, now, now.Sub(startTime), time.Second) - } - - tt := tc.Now() - tc.SetTime(tt.Add(time.Hour)) - if tc.Now().Sub(tt) != time.Hour { - t.Errorf("input: %s now=%s gap=%s expected=%s", tt, tc.Now(), tc.Now().Sub(tt), time.Hour) - } -} - -func TestFakeClockSleep(t *testing.T) { - startTime := time.Now() - tc := NewFakeClock(startTime) - tc.Sleep(time.Duration(1) * time.Hour) - now := tc.Now() - if now.Sub(startTime) != time.Hour { - t.Errorf("Fake sleep failed, expected time to advance by one hour, instead, its %v", now.Sub(startTime)) - } -} - -func TestFakeAfter(t *testing.T) { - tc := NewFakeClock(time.Now()) - if tc.HasWaiters() { - t.Errorf("unexpected waiter?") - } - oneSec := tc.After(time.Second) - if !tc.HasWaiters() { - t.Errorf("unexpected lack of waiter?") - } - - oneOhOneSec := tc.After(time.Second + time.Millisecond) - twoSec := tc.After(2 * time.Second) - select { - case <-oneSec: - t.Errorf("unexpected channel read") - case <-oneOhOneSec: - t.Errorf("unexpected channel read") - case <-twoSec: - t.Errorf("unexpected channel read") - default: - } - - tc.Step(999 * time.Millisecond) - select { - case <-oneSec: - t.Errorf("unexpected channel read") - case <-oneOhOneSec: - t.Errorf("unexpected channel read") - case <-twoSec: - t.Errorf("unexpected channel read") - default: - } - - tc.Step(time.Millisecond) - select { - case <-oneSec: - // Expected! - case <-oneOhOneSec: - t.Errorf("unexpected channel read") - case <-twoSec: - t.Errorf("unexpected channel read") - default: - t.Errorf("unexpected non-channel read") - } - tc.Step(time.Millisecond) - select { - case <-oneSec: - // should not double-trigger! - t.Errorf("unexpected channel read") - case <-oneOhOneSec: - // Expected! - case <-twoSec: - t.Errorf("unexpected channel read") - default: - t.Errorf("unexpected non-channel read") - } -} - -func TestFakeTick(t *testing.T) { - tc := NewFakeClock(time.Now()) - if tc.HasWaiters() { - t.Errorf("unexpected waiter?") - } - oneSec := tc.Tick(time.Second) - if !tc.HasWaiters() { - t.Errorf("unexpected lack of waiter?") - } - - oneOhOneSec := tc.Tick(time.Second + time.Millisecond) - twoSec := tc.Tick(2 * time.Second) - select { - case <-oneSec: - t.Errorf("unexpected channel read") - case <-oneOhOneSec: - t.Errorf("unexpected channel read") - case <-twoSec: - t.Errorf("unexpected channel read") - default: - } - - tc.Step(999 * time.Millisecond) // t=.999 - select { - case <-oneSec: - t.Errorf("unexpected channel read") - case <-oneOhOneSec: - t.Errorf("unexpected channel read") - case <-twoSec: - t.Errorf("unexpected channel read") - default: - } - - tc.Step(time.Millisecond) // t=1.000 - select { - case <-oneSec: - // Expected! - case <-oneOhOneSec: - t.Errorf("unexpected channel read") - case <-twoSec: - t.Errorf("unexpected channel read") - default: - t.Errorf("unexpected non-channel read") - } - tc.Step(time.Millisecond) // t=1.001 - select { - case <-oneSec: - // should not double-trigger! - t.Errorf("unexpected channel read") - case <-oneOhOneSec: - // Expected! - case <-twoSec: - t.Errorf("unexpected channel read") - default: - t.Errorf("unexpected non-channel read") - } - - tc.Step(time.Second) // t=2.001 - tc.Step(time.Second) // t=3.001 - tc.Step(time.Second) // t=4.001 - tc.Step(time.Second) // t=5.001 - - // The one second ticker should not accumulate ticks - accumulatedTicks := 0 - drained := false - for !drained { - select { - case <-oneSec: - accumulatedTicks++ - default: - drained = true - } - } - if accumulatedTicks != 1 { - t.Errorf("unexpected number of accumulated ticks: %d", accumulatedTicks) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/util/sets/BUILD b/vendor/k8s.io/kubernetes/pkg/util/sets/BUILD index 17870b378f46..8640399be017 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/sets/BUILD +++ b/vendor/k8s.io/kubernetes/pkg/util/sets/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -14,13 +14,6 @@ go_library( visibility = ["//visibility:public"], ) -go_test( - name = "go_default_test", - srcs = ["set_test.go"], - importpath = "k8s.io/kubernetes/pkg/util/sets", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/k8s.io/kubernetes/pkg/util/sets/set_test.go b/vendor/k8s.io/kubernetes/pkg/util/sets/set_test.go deleted file mode 100644 index df722ec27125..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/util/sets/set_test.go +++ /dev/null @@ -1,270 +0,0 @@ -/* -Copyright 2014 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package sets - -import ( - "reflect" - "testing" -) - -func TestStringSet(t *testing.T) { - s := String{} - s2 := String{} - if len(s) != 0 { - t.Errorf("Expected len=0: %d", len(s)) - } - s.Insert("a", "b") - if len(s) != 2 { - t.Errorf("Expected len=2: %d", len(s)) - } - s.Insert("c") - if s.Has("d") { - t.Errorf("Unexpected contents: %#v", s) - } - if !s.Has("a") { - t.Errorf("Missing contents: %#v", s) - } - s.Delete("a") - if s.Has("a") { - t.Errorf("Unexpected contents: %#v", s) - } - s.Insert("a") - if s.HasAll("a", "b", "d") { - t.Errorf("Unexpected contents: %#v", s) - } - if !s.HasAll("a", "b") { - t.Errorf("Missing contents: %#v", s) - } - s2.Insert("a", "b", "d") - if s.IsSuperset(s2) { - t.Errorf("Unexpected contents: %#v", s) - } - s2.Delete("d") - if !s.IsSuperset(s2) { - t.Errorf("Missing contents: %#v", s) - } -} - -func TestStringSetDeleteMultiples(t *testing.T) { - s := String{} - s.Insert("a", "b", "c") - if len(s) != 3 { - t.Errorf("Expected len=3: %d", len(s)) - } - - s.Delete("a", "c") - if len(s) != 1 { - t.Errorf("Expected len=1: %d", len(s)) - } - if s.Has("a") { - t.Errorf("Unexpected contents: %#v", s) - } - if s.Has("c") { - t.Errorf("Unexpected contents: %#v", s) - } - if !s.Has("b") { - t.Errorf("Missing contents: %#v", s) - } - -} - -func TestNewStringSet(t *testing.T) { - s := NewString("a", "b", "c") - if len(s) != 3 { - t.Errorf("Expected len=3: %d", len(s)) - } - if !s.Has("a") || !s.Has("b") || !s.Has("c") { - t.Errorf("Unexpected contents: %#v", s) - } -} - -func TestStringSetList(t *testing.T) { - s := NewString("z", "y", "x", "a") - if !reflect.DeepEqual(s.List(), []string{"a", "x", "y", "z"}) { - t.Errorf("List gave unexpected result: %#v", s.List()) - } -} - -func TestStringSetDifference(t *testing.T) { - a := NewString("1", "2", "3") - b := NewString("1", "2", "4", "5") - c := a.Difference(b) - d := b.Difference(a) - if len(c) != 1 { - t.Errorf("Expected len=1: %d", len(c)) - } - if !c.Has("3") { - t.Errorf("Unexpected contents: %#v", c.List()) - } - if len(d) != 2 { - t.Errorf("Expected len=2: %d", len(d)) - } - if !d.Has("4") || !d.Has("5") { - t.Errorf("Unexpected contents: %#v", d.List()) - } -} - -func TestStringSetHasAny(t *testing.T) { - a := NewString("1", "2", "3") - - if !a.HasAny("1", "4") { - t.Errorf("expected true, got false") - } - - if a.HasAny("0", "4") { - t.Errorf("expected false, got true") - } -} - -func TestStringSetEquals(t *testing.T) { - // Simple case (order doesn't matter) - a := NewString("1", "2") - b := NewString("2", "1") - if !a.Equal(b) { - t.Errorf("Expected to be equal: %v vs %v", a, b) - } - - // It is a set; duplicates are ignored - b = NewString("2", "2", "1") - if !a.Equal(b) { - t.Errorf("Expected to be equal: %v vs %v", a, b) - } - - // Edge cases around empty sets / empty strings - a = NewString() - b = NewString() - if !a.Equal(b) { - t.Errorf("Expected to be equal: %v vs %v", a, b) - } - - b = NewString("1", "2", "3") - if a.Equal(b) { - t.Errorf("Expected to be not-equal: %v vs %v", a, b) - } - - b = NewString("1", "2", "") - if a.Equal(b) { - t.Errorf("Expected to be not-equal: %v vs %v", a, b) - } - - // Check for equality after mutation - a = NewString() - a.Insert("1") - if a.Equal(b) { - t.Errorf("Expected to be not-equal: %v vs %v", a, b) - } - - a.Insert("2") - if a.Equal(b) { - t.Errorf("Expected to be not-equal: %v vs %v", a, b) - } - - a.Insert("") - if !a.Equal(b) { - t.Errorf("Expected to be equal: %v vs %v", a, b) - } - - a.Delete("") - if a.Equal(b) { - t.Errorf("Expected to be not-equal: %v vs %v", a, b) - } -} - -func TestStringUnion(t *testing.T) { - tests := []struct { - s1 String - s2 String - expected String - }{ - { - NewString("1", "2", "3", "4"), - NewString("3", "4", "5", "6"), - NewString("1", "2", "3", "4", "5", "6"), - }, - { - NewString("1", "2", "3", "4"), - NewString(), - NewString("1", "2", "3", "4"), - }, - { - NewString(), - NewString("1", "2", "3", "4"), - NewString("1", "2", "3", "4"), - }, - { - NewString(), - NewString(), - NewString(), - }, - } - - for _, test := range tests { - union := test.s1.Union(test.s2) - if union.Len() != test.expected.Len() { - t.Errorf("Expected union.Len()=%d but got %d", test.expected.Len(), union.Len()) - } - - if !union.Equal(test.expected) { - t.Errorf("Expected union.Equal(expected) but not true. union:%v expected:%v", union.List(), test.expected.List()) - } - } -} - -func TestStringIntersection(t *testing.T) { - tests := []struct { - s1 String - s2 String - expected String - }{ - { - NewString("1", "2", "3", "4"), - NewString("3", "4", "5", "6"), - NewString("3", "4"), - }, - { - NewString("1", "2", "3", "4"), - NewString("1", "2", "3", "4"), - NewString("1", "2", "3", "4"), - }, - { - NewString("1", "2", "3", "4"), - NewString(), - NewString(), - }, - { - NewString(), - NewString("1", "2", "3", "4"), - NewString(), - }, - { - NewString(), - NewString(), - NewString(), - }, - } - - for _, test := range tests { - intersection := test.s1.Intersection(test.s2) - if intersection.Len() != test.expected.Len() { - t.Errorf("Expected intersection.Len()=%d but got %d", test.expected.Len(), intersection.Len()) - } - - if !intersection.Equal(test.expected) { - t.Errorf("Expected intersection.Equal(expected) but not true. intersection:%v expected:%v", intersection.List(), test.expected.List()) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/util/template_test.go b/vendor/k8s.io/kubernetes/pkg/util/template_test.go deleted file mode 100644 index 8f075d1adbd9..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/util/template_test.go +++ /dev/null @@ -1,61 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package util - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestWrap(t *testing.T) { - tt := `before ->{{.Long | wrap "**"}}<- after` - data := struct { - Long string - }{ - `Hodor, hodor; hodor hodor; -hodor hodor... Hodor hodor hodor? Hodor. Hodor hodor hodor hodor... -Hodor hodor hodor; hodor hodor hodor! Hodor, hodor. Hodor. Hodor, -HODOR hodor, hodor hodor; hodor hodor; hodor HODOR hodor, hodor hodor? -Hodor. Hodor hodor - hodor hodor. Hodor hodor HODOR! Hodor hodor - hodor... -Hodor hodor HODOR hodor, hodor hodor hodor! Hodor, hodor... Hodor hodor -hodor hodor hodor hodor! Hodor, hodor; hodor hodor. Hodor.`, - } - output, _ := ExecuteTemplateToString(tt, data) - t.Logf("%q", output) - - assert.Equal(t, `before ->**Hodor, hodor; hodor hodor; hodor hodor... Hodor hodor hodor? Hodor. Hodor -**hodor hodor hodor... Hodor hodor hodor; hodor hodor hodor! Hodor, hodor. -**Hodor. Hodor, HODOR hodor, hodor hodor; hodor hodor; hodor HODOR hodor, hodor -**hodor? Hodor. Hodor hodor - hodor hodor. Hodor hodor HODOR! Hodor hodor - -**hodor... Hodor hodor HODOR hodor, hodor hodor hodor! Hodor, hodor... Hodor -**hodor hodor hodor hodor hodor! Hodor, hodor; hodor hodor. Hodor. -<- after`, output) -} - -func TestTrim(t *testing.T) { - tt := `before ->{{.Messy | trim }}<- after` - data := struct { - Messy string - }{ - "\t stuff\n \r ", - } - output, _ := ExecuteTemplateToString(tt, data) - t.Logf("%q", output) - - assert.Equal(t, `before ->stuff<- after`, output) -} diff --git a/vendor/k8s.io/kubernetes/pkg/util/util_test.go b/vendor/k8s.io/kubernetes/pkg/util/util_test.go deleted file mode 100644 index 36a6641dadb8..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/util/util_test.go +++ /dev/null @@ -1,101 +0,0 @@ -/* -Copyright 2014 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package util - -import ( - "testing" - - "k8s.io/kubernetes/pkg/util/diff" -) - -func TestStringDiff(t *testing.T) { - diff := diff.StringDiff("aaabb", "aaacc") - expect := "aaa\n\nA: bb\n\nB: cc\n\n" - if diff != expect { - t.Errorf("diff returned %v", diff) - } -} - -func TestCompileRegex(t *testing.T) { - uncompiledRegexes := []string{"endsWithMe$", "^startingWithMe"} - regexes, err := CompileRegexps(uncompiledRegexes) - - if err != nil { - t.Errorf("Failed to compile legal regexes: '%v': %v", uncompiledRegexes, err) - } - if len(regexes) != len(uncompiledRegexes) { - t.Errorf("Wrong number of regexes returned: '%v': %v", uncompiledRegexes, regexes) - } - - if !regexes[0].MatchString("Something that endsWithMe") { - t.Errorf("Wrong regex returned: '%v': %v", uncompiledRegexes[0], regexes[0]) - } - if regexes[0].MatchString("Something that doesn't endsWithMe.") { - t.Errorf("Wrong regex returned: '%v': %v", uncompiledRegexes[0], regexes[0]) - } - if !regexes[1].MatchString("startingWithMe is very important") { - t.Errorf("Wrong regex returned: '%v': %v", uncompiledRegexes[1], regexes[1]) - } - if regexes[1].MatchString("not startingWithMe should fail") { - t.Errorf("Wrong regex returned: '%v': %v", uncompiledRegexes[1], regexes[1]) - } -} - -func TestAllPtrFieldsNil(t *testing.T) { - testCases := []struct { - obj interface{} - expected bool - }{ - {struct{}{}, true}, - {struct{ Foo int }{12345}, true}, - {&struct{ Foo int }{12345}, true}, - {struct{ Foo *int }{nil}, true}, - {&struct{ Foo *int }{nil}, true}, - {struct { - Foo int - Bar *int - }{12345, nil}, true}, - {&struct { - Foo int - Bar *int - }{12345, nil}, true}, - {struct { - Foo *int - Bar *int - }{nil, nil}, true}, - {&struct { - Foo *int - Bar *int - }{nil, nil}, true}, - {struct{ Foo *int }{new(int)}, false}, - {&struct{ Foo *int }{new(int)}, false}, - {struct { - Foo *int - Bar *int - }{nil, new(int)}, false}, - {&struct { - Foo *int - Bar *int - }{nil, new(int)}, false}, - {(*struct{})(nil), true}, - } - for i, tc := range testCases { - if AllPtrFieldsNil(tc.obj) != tc.expected { - t.Errorf("case[%d]: expected %t, got %t", i, tc.expected, !tc.expected) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/util/yaml/BUILD b/vendor/k8s.io/kubernetes/pkg/util/yaml/BUILD index 4ddac79d3de5..d1050d8b6b6c 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/yaml/BUILD +++ b/vendor/k8s.io/kubernetes/pkg/util/yaml/BUILD @@ -1,4 +1,4 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") +load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "go_default_library", @@ -11,13 +11,6 @@ go_library( ], ) -go_test( - name = "go_default_test", - srcs = ["decoder_test.go"], - importpath = "k8s.io/kubernetes/pkg/util/yaml", - library = ":go_default_library", -) - filegroup( name = "package-srcs", srcs = glob(["**"]), diff --git a/vendor/k8s.io/kubernetes/pkg/util/yaml/decoder_test.go b/vendor/k8s.io/kubernetes/pkg/util/yaml/decoder_test.go deleted file mode 100644 index 8985907c4566..000000000000 --- a/vendor/k8s.io/kubernetes/pkg/util/yaml/decoder_test.go +++ /dev/null @@ -1,316 +0,0 @@ -/* -Copyright 2014 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package yaml - -import ( - "bufio" - "bytes" - "encoding/json" - "fmt" - "io" - "math/rand" - "reflect" - "strings" - "testing" -) - -func TestSplitYAMLDocument(t *testing.T) { - testCases := []struct { - input string - atEOF bool - expect string - adv int - }{ - {"foo", true, "foo", 3}, - {"fo", false, "", 0}, - - {"---", true, "---", 3}, - {"---\n", true, "---\n", 4}, - {"---\n", false, "", 0}, - - {"\n---\n", false, "", 5}, - {"\n---\n", true, "", 5}, - - {"abc\n---\ndef", true, "abc", 8}, - {"def", true, "def", 3}, - {"", true, "", 0}, - } - for i, testCase := range testCases { - adv, token, err := splitYAMLDocument([]byte(testCase.input), testCase.atEOF) - if err != nil { - t.Errorf("%d: unexpected error: %v", i, err) - continue - } - if adv != testCase.adv { - t.Errorf("%d: advance did not match: %d %d", i, testCase.adv, adv) - } - if testCase.expect != string(token) { - t.Errorf("%d: token did not match: %q %q", i, testCase.expect, string(token)) - } - } -} - -func TestGuessJSON(t *testing.T) { - if r, isJSON := GuessJSONStream(bytes.NewReader([]byte(" \n{}")), 100); !isJSON { - t.Fatalf("expected stream to be JSON") - } else { - b := make([]byte, 30) - n, err := r.Read(b) - if err != nil || n != 4 { - t.Fatalf("unexpected body: %d / %v", n, err) - } - if string(b[:n]) != " \n{}" { - t.Fatalf("unexpected body: %q", string(b[:n])) - } - } -} - -func TestScanYAML(t *testing.T) { - s := bufio.NewScanner(bytes.NewReader([]byte(`--- -stuff: 1 - ---- - `))) - s.Split(splitYAMLDocument) - if !s.Scan() { - t.Fatalf("should have been able to scan") - } - t.Logf("scan: %s", s.Text()) - if !s.Scan() { - t.Fatalf("should have been able to scan") - } - t.Logf("scan: %s", s.Text()) - if s.Scan() { - t.Fatalf("scan should have been done") - } - if s.Err() != nil { - t.Fatalf("err should have been nil: %v", s.Err()) - } -} - -func TestDecodeYAML(t *testing.T) { - s := NewYAMLToJSONDecoder(bytes.NewReader([]byte(`--- -stuff: 1 - ---- - `))) - obj := generic{} - if err := s.Decode(&obj); err != nil { - t.Fatalf("unexpected error: %v", err) - } - if fmt.Sprintf("%#v", obj) != `yaml.generic{"stuff":1}` { - t.Errorf("unexpected object: %#v", obj) - } - obj = generic{} - if err := s.Decode(&obj); err != nil { - t.Fatalf("unexpected error: %v", err) - } - if len(obj) != 0 { - t.Fatalf("unexpected object: %#v", obj) - } - obj = generic{} - if err := s.Decode(&obj); err != io.EOF { - t.Fatalf("unexpected error: %v", err) - } -} - -func TestDecodeBrokenYAML(t *testing.T) { - s := NewYAMLOrJSONDecoder(bytes.NewReader([]byte(`--- -stuff: 1 - test-foo: 1 - ---- - `)), 100) - obj := generic{} - err := s.Decode(&obj) - if err == nil { - t.Fatal("expected error with yaml: prefix, got no error") - } - fmt.Printf("err: %s\n", err.Error()) - if !strings.HasPrefix(err.Error(), "yaml: line 1:") { - t.Fatalf("expected %q to have 'yaml: line 1:' prefix", err.Error()) - } -} - -func TestDecodeBrokenJSON(t *testing.T) { - s := NewYAMLOrJSONDecoder(bytes.NewReader([]byte(`{ - "foo": { - "stuff": 1 - "otherStuff": 2 - } -} - `)), 100) - obj := generic{} - err := s.Decode(&obj) - if err == nil { - t.Fatal("expected error with json: prefix, got no error") - } - if !strings.HasPrefix(err.Error(), "json: line 3:") { - t.Fatalf("expected %q to have 'json: line 3:' prefix", err.Error()) - } -} - -type generic map[string]interface{} - -func TestYAMLOrJSONDecoder(t *testing.T) { - testCases := []struct { - input string - buffer int - isJSON bool - err bool - out []generic - }{ - {` {"1":2}{"3":4}`, 2, true, false, []generic{ - {"1": 2}, - {"3": 4}, - }}, - {" \n{}", 3, true, false, []generic{ - {}, - }}, - {" \na: b", 2, false, false, []generic{ - {"a": "b"}, - }}, - {" \n{\"a\": \"b\"}", 2, false, true, []generic{ - {"a": "b"}, - }}, - {" \n{\"a\": \"b\"}", 3, true, false, []generic{ - {"a": "b"}, - }}, - {` {"a":"b"}`, 100, true, false, []generic{ - {"a": "b"}, - }}, - {"", 1, false, false, []generic{}}, - {"foo: bar\n---\nbaz: biz", 100, false, false, []generic{ - {"foo": "bar"}, - {"baz": "biz"}, - }}, - {"foo: bar\n---\n", 100, false, false, []generic{ - {"foo": "bar"}, - }}, - {"foo: bar\n---", 100, false, false, []generic{ - {"foo": "bar"}, - }}, - {"foo: bar\n--", 100, false, true, []generic{ - {"foo": "bar"}, - }}, - {"foo: bar\n-", 100, false, true, []generic{ - {"foo": "bar"}, - }}, - {"foo: bar\n", 100, false, false, []generic{ - {"foo": "bar"}, - }}, - } - for i, testCase := range testCases { - decoder := NewYAMLOrJSONDecoder(bytes.NewReader([]byte(testCase.input)), testCase.buffer) - objs := []generic{} - - var err error - for { - out := make(generic) - err = decoder.Decode(&out) - if err != nil { - break - } - objs = append(objs, out) - } - if err != io.EOF { - switch { - case testCase.err && err == nil: - t.Errorf("%d: unexpected non-error", i) - continue - case !testCase.err && err != nil: - t.Errorf("%d: unexpected error: %v", i, err) - continue - case err != nil: - continue - } - } - switch decoder.decoder.(type) { - case *YAMLToJSONDecoder: - if testCase.isJSON { - t.Errorf("%d: expected JSON decoder, got YAML", i) - } - case *json.Decoder: - if !testCase.isJSON { - t.Errorf("%d: expected YAML decoder, got JSON", i) - } - } - if fmt.Sprintf("%#v", testCase.out) != fmt.Sprintf("%#v", objs) { - t.Errorf("%d: objects were not equal: \n%#v\n%#v", i, testCase.out, objs) - } - } -} - -func TestReadSingleLongLine(t *testing.T) { - testReadLines(t, []int{128 * 1024}) -} - -func TestReadRandomLineLengths(t *testing.T) { - minLength := 100 - maxLength := 96 * 1024 - maxLines := 100 - - lineLengths := make([]int, maxLines) - for i := 0; i < maxLines; i++ { - lineLengths[i] = rand.Intn(maxLength-minLength) + minLength - } - - testReadLines(t, lineLengths) -} - -func testReadLines(t *testing.T, lineLengths []int) { - var ( - lines [][]byte - inputStream []byte - ) - for _, lineLength := range lineLengths { - inputLine := make([]byte, lineLength+1) - for i := 0; i < lineLength; i++ { - char := rand.Intn('z'-'A') + 'A' - inputLine[i] = byte(char) - } - inputLine[len(inputLine)-1] = '\n' - lines = append(lines, inputLine) - } - for _, line := range lines { - inputStream = append(inputStream, line...) - } - - // init Reader - reader := bufio.NewReader(bytes.NewReader(inputStream)) - lineReader := &LineReader{reader: reader} - - // read lines - var readLines [][]byte - for range lines { - bytes, err := lineReader.Read() - if err != nil && err != io.EOF { - t.Fatalf("failed to read lines: %v", err) - } - readLines = append(readLines, bytes) - } - - // validate - for i := range lines { - if len(lines[i]) != len(readLines[i]) { - t.Fatalf("expected line length: %d, but got %d", len(lines[i]), len(readLines[i])) - } - if !reflect.DeepEqual(lines[i], readLines[i]) { - t.Fatalf("expected line: %v, but got %v", lines[i], readLines[i]) - } - } -}