| 1 | // Copyright 2023 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package upload |
| 6 | |
| 7 | import ( |
| 8 | "net/http" |
| 9 | "reflect" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | ) |
| 13 | |
| 14 | // make sure we can talk to the test server |
| 15 | // In practice this test runs last, so is somewhat superfluous, |
| 16 | // but it also checks that uploads and reads from the channel are matched |
| 17 | func TestSimpleServer(t *testing.T) { |
| 18 | srv, uploaded := CreateTestUploadServer(t) |
| 19 | |
| 20 | url := srv.URL |
| 21 | resp, err := http.Post(url, "text/plain", strings.NewReader("hello")) |
| 22 | if err != nil { |
| 23 | t.Fatal(err) |
| 24 | } |
| 25 | if resp.StatusCode != http.StatusOK { |
| 26 | t.Errorf("%#v", resp.StatusCode) |
| 27 | } |
| 28 | got := uploaded() |
| 29 | want := [][]byte{[]byte("hello")} |
| 30 | if !reflect.DeepEqual(got, want) { |
| 31 | t.Errorf("got %s, want %s", got, want) |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | // make sure computeRandom() gets enough small values |
| 36 | // in case SamplingRate is as small as .001 |
| 37 | func TestRandom(t *testing.T) { |
| 38 | // This test, being statistical, is intrinsically flaky |
| 39 | // It has failed once in its first 3 months at 4.5, |
| 40 | // so change the criterion to 7 sigma. |
| 41 | const N = 102400 // 35msec on an M1 mac |
| 42 | cnt := 0 |
| 43 | for i := 0; i < N; i++ { |
| 44 | if computeRandom() < 1.0/1024 { |
| 45 | cnt++ |
| 46 | } |
| 47 | } |
| 48 | // cnt has a binomial distribution. The normal |
| 49 | // approximation has mu=N*p=100, sigma=sqrt(N*p*(1-p))=10 |
| 50 | // We reject if cnt is off by 45, which happens about 1/300,000 |
| 51 | // if the computeRandom() is truly uniform. That is, the |
| 52 | // test will be flaky about 3 times in a million. |
| 53 | if cnt < 30 || cnt > 170 { |
| 54 | t.Errorf("cnt %d more than 7 sigma(10) from mean(100)", cnt) |
| 55 | } |
| 56 | } |