func TestPrintFileDirectoryIndex(t *testing.T) { testMemFs := &memFS{MemMapFs: new(afero.MemMapFs)} assert.NoError(t, testMemFs.Mkdir("test", 0777)) f, err := testMemFs.Create("test/index.html") if err != nil { t.Fatal(err) } if _, err = f.Write([]byte(`<h1>This is a huge h1 tag!</h1>`)); err != nil { t.Fatal(err) } if err := f.Close(); err != nil { t.Fatal(err) } w := httptest.NewRecorder() r, err := http.NewRequest("GET", "http://coretore.io", nil) assert.NoError(t, err) p := httputil.NewPrinter(w, r) p.FileSystem = testMemFs assert.NoError(t, p.File("/test", "", false)) assert.Equal(t, "text/html; charset=utf-8", w.Header().Get(httputil.ContentType)) assert.Equal(t, "", w.Header().Get(httputil.ContentDisposition)) assert.Exactly(t, "<h1>This is a huge h1 tag!</h1>", w.Body.String()) assert.Exactly(t, 200, w.Code) }
func TestStringCSV(t *testing.T) { t.Parallel() wantPath := scope.StrDefault.FQPathInt64(0, "web/cors/exposed_headers") b := model.NewStringCSV( "web/cors/exposed_headers", model.WithConfigStructure(configStructure), model.WithSourceByString( "Content-Type", "Content Type", "X-CoreStore-ID", "CoreStore Microservice ID", ), ) assert.NotEmpty(t, b.Options()) assert.Exactly(t, []string{"Content-Type", "X-CoreStore-ID"}, b.Get(config.NewMockGetter().NewScoped(0, 0, 0))) assert.Exactly(t, []string{"Content-Application", "X-Gopher"}, b.Get(config.NewMockGetter( config.WithMockValues(config.MockPV{ wantPath: "Content-Application,X-Gopher", }), ).NewScoped(0, 0, 0))) mw := &config.MockWrite{} b.Source.Merge(source.NewByString("a", "a", "b", "b", "c", "c")) assert.NoError(t, b.Write(mw, []string{"a", "b", "c"}, scope.DefaultID, 0)) assert.Exactly(t, wantPath, mw.ArgPath) assert.Exactly(t, "a,b,c", mw.ArgValue.(string)) }
func TestEnableLogger(t *testing.T) { defer cleanupTest() ta := &testAppender{} logger := GetLogger("my/logger") logger.Enable(ta) Disable("my/logger") logger.Debug("some msg") logger.Info("some msg") logger.Warn("some msg") logger.Error("some msg") assert.Exactly(t, 0, ta.count) Enable("my/logger") logger.Debug("some msg") logger.Info("some msg") logger.Warn("some msg") logger.Error("some msg") assert.Exactly(t, 4, ta.count) Enable("some-unknown-name") }
func TestPrintNoContent(t *testing.T) { w := httptest.NewRecorder() p := httputil.NewPrinter(w, nil) assert.NoError(t, p.NoContent(501)) assert.Exactly(t, "", w.Body.String()) assert.Exactly(t, 501, w.Code) }
func TestServeHTTP_ShouldNotValidateEmailAddress(t *testing.T) { h := newTestHandler(t, `mailout`) data := make(url.Values) data.Set("firstname", "Ken") data.Set("lastname", "Thompson") data.Set("email", "kenthompson.email") data.Set("name", "Ken Thompson") req, err := http.NewRequest("POST", "/mailout", nil) if err != nil { t.Fatal(err) } req.PostForm = data w := httptest.NewRecorder() code, err := h.ServeHTTP(w, req) if err != nil { t.Fatal(err) } assert.Exactly(t, StatusEmpty, code) assert.Exactly(t, "{\"code\":422,\"error\":\"Invalid email address: \\\"ken\\\\uf8ffthompson.email\\\"\"}\n", w.Body.String()) assert.Exactly(t, StatusUnprocessableEntity, w.Code) assert.Exactly(t, headerApplicationJSONUTF8, w.HeaderMap.Get(headerContentType)) }
func TestValueLabelSlice(t *testing.T) { tests := []struct { have config.ValueLabelSlice wantValue string wantLabel string order utils.SortDirection }{ { config.ValueLabelSlice{config.ValueLabel{"kb", "l2"}, config.ValueLabel{"ka", "l1"}, config.ValueLabel{"kc", "l3"}, config.ValueLabel{"kY", "l5"}, config.ValueLabel{"k0", "l4"}}, `[{"Value":"k0","Label":"l4"},{"Value":"kY","Label":"l5"},{"Value":"ka","Label":"l1"},{"Value":"kb","Label":"l2"},{"Value":"kc","Label":"l3"}]` + "\n", `[{"Value":"ka","Label":"l1"},{"Value":"kb","Label":"l2"},{"Value":"kc","Label":"l3"},{"Value":"k0","Label":"l4"},{"Value":"kY","Label":"l5"}]` + "\n", utils.SortAsc, }, { config.ValueLabelSlice{config.ValueLabel{"x3", "l2"}, config.ValueLabel{"xg", "l1"}, config.ValueLabel{"xK", "l3"}, config.ValueLabel{"x0", "l5"}, config.ValueLabel{"x-", "l4"}}, `[{"Value":"xg","Label":"l1"},{"Value":"xK","Label":"l3"},{"Value":"x3","Label":"l2"},{"Value":"x0","Label":"l5"},{"Value":"x-","Label":"l4"}]` + "\n", `[{"Value":"x0","Label":"l5"},{"Value":"x-","Label":"l4"},{"Value":"xK","Label":"l3"},{"Value":"x3","Label":"l2"},{"Value":"xg","Label":"l1"}]` + "\n", utils.SortDesc, }, } for i, test := range tests { test.have.SortByValue(test.order) assert.Exactly(t, test.wantValue, test.have.ToJSON(), "SortByValue Index %d", i) test.have.SortByLabel(test.order) assert.Exactly(t, test.wantLabel, test.have.ToJSON(), "SortByLabel Index %d", i) } }
func TestURLCache(t *testing.T) { tests := []struct { haveType config.URLType url string wantError error }{ {config.URLTypeStatic, "", config.ErrURLEmpty}, {config.URLTypeWeb, "http://corestore.io/", nil}, {config.URLTypeStatic, "://corestore.io/", errors.New("parse ://corestore.io/: missing protocol scheme")}, {config.URLType(254), "https://corestore.io/catalog", errors.New("Unknown Index 254")}, } for i, test := range tests { uc := config.NewURLCache() if test.wantError != nil { pu, err := uc.Set(test.haveType, test.url) assert.Nil(t, pu, "Index %d", i) assert.EqualError(t, err, test.wantError.Error(), "Index %d", i) assert.Nil(t, uc.Get(test.haveType)) continue } pu, err := uc.Set(test.haveType, test.url) // pu = parsed URL assert.NoError(t, err, "Index %d", i) assert.Exactly(t, test.url, pu.String(), "Index %d", i) puCache := uc.Get(test.haveType) assert.Exactly(t, test.url, puCache.String(), "Index %d", i) assert.EqualError(t, uc.Clear(), config.ErrURLCacheCleared.Error()) assert.Nil(t, uc.Get(test.haveType), "Index %d", i) } }
func TestGetSubsectionOrCreate(t *testing.T) { versionNum := "HEAD" subsectionName := "Bug Fixes" c := NewChangelog() // Not nil if no version. assert.Nil(t, c.GetVersion(versionNum)) subsection := c.GetSubsectionOrCreate(versionNum, subsectionName) assert.NotNil(t, subsection) assert.Equal(t, subsectionName, subsection.Name) assert.Exactly(t, c.GetVersion(versionNum).Subsections[0], subsection) // Not nil if version but no subsection. c = NewChangelog() version := c.GetVersionOrCreate(versionNum) assert.NotNil(t, c.GetVersion(versionNum)) assert.Exactly(t, version, c.GetVersion(versionNum)) subsection = c.GetSubsectionOrCreate(versionNum, subsectionName) assert.NotNil(t, subsection) assert.Equal(t, subsectionName, subsection.Name) assert.Exactly(t, version.Subsections[0], subsection) // Not nil if version and subsection exist. c = NewChangelog() version = c.GetVersionOrCreate(versionNum) subsection = NewSubsection(subsectionName) version.Subsections = append(version.Subsections, subsection) subsection = c.GetSubsectionOrCreate(versionNum, subsectionName) assert.NotNil(t, subsection) assert.Equal(t, subsectionName, subsection.Name) assert.Exactly(t, version.Subsections[0], subsection) }
func TestConfigRedirectToBase(t *testing.T) { defer debugLogBuf.Reset() t.Parallel() r := backend.NewConfigRedirectToBase( backend.Backend.WebURLRedirectToBase.String(), model.WithConfigStructure(backend.ConfigStructure), ) cr := config.NewMockGetter( config.WithMockValues(config.MockPV{ backend.Backend.WebURLRedirectToBase.FQPathInt64(scope.StrDefault, 0): 2, }), ) code := r.Get(cr.NewScoped(0, 0, 0)) assert.Exactly(t, 2, code) code = r.Get(cr.NewScoped(1, 1, 2)) assert.Exactly(t, 0, code) // that is crap we should return an error assert.Contains(t, debugLogBuf.String(), "Scope permission insufficient: Have 'Store'; Want 'Default'") mw := new(config.MockWrite) assert.EqualError(t, r.Write(mw, 200, scope.DefaultID, 0), "Cannot find 200 in list: [{\"Value\":0,\"Label\":\"No\"},{\"Value\":1,\"Label\":\"Yes (302 Found)\"},{\"Value\":302,\"Label\":\"Yes (302 Found)\"},{\"Value\":301,\"Label\":\"Yes (301 Moved Permanently)\"}]\n", ) // 200 not allowed }
func TestWithAccessLog(t *testing.T) { var buf bytes.Buffer defer buf.Reset() ctx := ctxlog.NewContext(context.Background(), log.NewStdLogger(log.SetStdWriter(&buf))) finalH := ctxhttp.Chain( ctxhttp.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { w.WriteHeader(http.StatusTeapot) _, err := w.Write([]byte{'1', '2', '3'}) time.Sleep(time.Millisecond) return err }), ctxhttp.WithAccessLog(), ) r, _ := http.NewRequest("GET", "/gopherine", nil) r.RemoteAddr = "127.0.0.1" r.Header.Set("User-Agent", "Mozilla") r.Header.Set("Referer", "http://rustlang.org") w := httptest.NewRecorder() if err := finalH.ServeHTTPContext(ctx, w, r); err != nil { t.Fatal(err) } assert.Exactly(t, `123`, w.Body.String()) assert.Exactly(t, http.StatusTeapot, w.Code) want1 := `request error: "" method: "GET" uri: "/gopherine" type: "access" status: "error" status_code: 418 duration:` want2 := `size: 3 remote_addr: "127.0.0.1" user_agent: "Mozilla" referer: "http://rustlang.org"` assert.Contains(t, buf.String(), want1) assert.Contains(t, buf.String(), want2) }
func TestAppSummaryGetSummary(t *testing.T) { ts, handler, repo := createAppSummaryRepo(t, []testnet.TestRequest{ appSummaryRequest, appInstancesRequest, appStatsRequest, }) defer ts.Close() app := cf.Application{Name: "my-cool-app", Guid: "my-cool-app-guid"} summary, err := repo.GetSummary(app) assert.True(t, handler.AllRequestsCalled()) assert.False(t, err.IsNotSuccessful()) assert.Equal(t, summary.App.Name, app.Name) assert.Equal(t, len(summary.Instances), 2) instance0 := summary.Instances[0] instance1 := summary.Instances[1] assert.Equal(t, instance0.State, cf.InstanceRunning) assert.Equal(t, instance1.State, cf.InstanceStarting) time0 := time.Unix(1379522342, 0) assert.Equal(t, instance0.Since, time0) assert.Exactly(t, instance0.DiskQuota, uint64(1073741824)) assert.Exactly(t, instance0.DiskUsage, uint64(56037376)) assert.Exactly(t, instance0.MemQuota, uint64(67108864)) assert.Exactly(t, instance0.MemUsage, uint64(19218432)) assert.Equal(t, instance0.CpuUsage, 3.659571249238058e-05) }
func (s *ParseVcfLineSuite) TestValidLineWithSampleGenotypeFields() { result, err := parseVcfLine("1\t847491\trs28407778\tGTTTA\tG....\t745.77\tPASS\tAC=1;AF=0.500;AN=2;BaseQRankSum=0.842;ClippingRankSum=0.147;DB;DP=41;FS=0.000;MLEAC=1;MLEAF=0.500;MQ=60.00;MQ0=0;MQRankSum=-1.109;QD=18.19;ReadPosRankSum=0.334;VQSLOD=2.70;culprit=FS;set=variant\tGT:AD:DP:GQ:PL\t0/1:16,25:41:99:774,0,434", defaultHeader) assert.NoError(s.T(), err, "Valid VCF line should not return error") assert.NotNil(s.T(), result, "Valid VCF line should not return nil") assert.Exactly(s.T(), len(result), 1, "Valid VCF should return a list with one element") samples := result[0].Samples assert.NotNil(s.T(), samples, "Valid VCF should contain slice of sample maps") assert.Exactly(s.T(), len(samples), 1, "Valid VCF should contain one sample") sampleMap := samples[0] assert.NotNil(s.T(), sampleMap, "Genotype field mapping should not return nil") assert.Exactly(s.T(), len(sampleMap), 5, "Sample map should have as many keys as there are formats") gt, ok := sampleMap["GT"] assert.True(s.T(), ok, "GT key must be found") assert.Equal(s.T(), gt, "0/1", "gt") ad, ok := sampleMap["AD"] assert.True(s.T(), ok, "AD key must be found") assert.Equal(s.T(), ad, "16,25", "ad") dp, ok := sampleMap["DP"] assert.True(s.T(), ok, "AD key must be found") assert.Equal(s.T(), dp, "41", "dp") gq, ok := sampleMap["GQ"] assert.True(s.T(), ok, "GQ key must be found") assert.Equal(s.T(), gq, "99", "gq") pl, ok := sampleMap["PL"] assert.True(s.T(), ok, "PL key must be found") assert.Equal(s.T(), pl, "774,0,434", "pl") }
func TestSplitFQPath(t *testing.T) { t.Parallel() tests := []struct { have string wantScope string wantScopeID int64 wantPath string wantErr error }{ {"groups/1/catalog/frontend/list_allow_all", "groups", 0, "", ErrUnsupportedScope}, {"stores/7475/catalog/frontend/list_allow_all", strStores, 7475, "catalog/frontend/list_allow_all", nil}, {"websites/1/catalog/frontend/list_allow_all", strWebsites, 1, "catalog/frontend/list_allow_all", nil}, {"default/0/catalog/frontend/list_allow_all", strDefault, 0, "catalog/frontend/list_allow_all", nil}, {"default//catalog/frontend/list_allow_all", strDefault, 0, "catalog/frontend/list_allow_all", errors.New("strconv.ParseInt: parsing \"\\uf8ff\": invalid syntax")}, {"stores/123/catalog/index", "", 0, "", errors.New("Incorrect fully qualified path: \"stores/123/catalog/index\"")}, } for _, test := range tests { haveScope, haveScopeID, havePath, haveErr := SplitFQPath(test.have) if test.wantErr != nil { assert.EqualError(t, haveErr, test.wantErr.Error(), "Test %v", test) } else { assert.NoError(t, haveErr, "Test %v", test) } assert.Exactly(t, test.wantScope, haveScope, "Test %v", test) assert.Exactly(t, test.wantScopeID, haveScopeID, "Test %v", test) assert.Exactly(t, test.wantPath, havePath, "Test %v", test) } }
func TestAppInstancesGetInstances(t *testing.T) { ts, handler, repo := createAppInstancesRepo(t, []testnet.TestRequest{ appInstancesRequest, appStatsRequest, }) defer ts.Close() appGuid := "my-cool-app-guid" instances, err := repo.GetInstances(appGuid) assert.True(t, handler.AllRequestsCalled()) assert.False(t, err.IsNotSuccessful()) assert.Equal(t, len(instances), 2) assert.Equal(t, instances[0].State, cf.InstanceRunning) assert.Equal(t, instances[1].State, cf.InstanceStarting) instance0 := instances[0] assert.Equal(t, instance0.Since, time.Unix(1379522342, 0)) assert.Exactly(t, instance0.DiskQuota, uint64(1073741824)) assert.Exactly(t, instance0.DiskUsage, uint64(56037376)) assert.Exactly(t, instance0.MemQuota, uint64(67108864)) assert.Exactly(t, instance0.MemUsage, uint64(19218432)) assert.Equal(t, instance0.CpuUsage, 3.659571249238058e-05) }
func TestTest(t *testing.T) { checker := makeTestChecker(t) checker.Test("GET", "/some") assert.NotNil(t, checker.request) assert.Exactly(t, "GET", checker.request.Method) assert.Exactly(t, "/some", checker.request.URL.Path) }
func TestNew(t *testing.T) { handler := &testHandler{} checker := New(t, handler) assert.NotNil(t, checker) assert.Exactly(t, t, checker.t) assert.Exactly(t, handler, checker.handler) }
func TestPrintHTML(t *testing.T) { w := httptest.NewRecorder() p := httputil.NewPrinter(w, nil) assert.NoError(t, p.HTML(3141, "Hello %s. Wanna have some %.5f?", "Gophers", math.Pi)) assert.Exactly(t, `Hello Gophers. Wanna have some 3.14159?`, w.Body.String()) assert.Exactly(t, 3141, w.Code) assert.Equal(t, httputil.TextHTMLCharsetUTF8, w.Header().Get(httputil.ContentType)) }
func TestPrintJSONIndent(t *testing.T) { w := httptest.NewRecorder() p := httputil.NewPrinter(w, nil) assert.NoError(t, p.JSONIndent(3141, encodeData, " ", "\t")) assert.Exactly(t, "[\n \t{\n \t\t\"Title\": \"Camera\",\n \t\t\"SKU\": \"323423423\",\n \t\t\"Price\": 45.12\n \t},\n \t{\n \t\t\"Title\": \"LCD TV\",\n \t\t\"SKU\": \"8785344\",\n \t\t\"Price\": 145.99\n \t}\n ]", w.Body.String()) assert.Exactly(t, 3141, w.Code) assert.Equal(t, httputil.ApplicationJSONCharsetUTF8, w.Header().Get(httputil.ContentType)) }
func TestPrintJSONPError(t *testing.T) { w := httptest.NewRecorder() p := httputil.NewPrinter(w, nil) assert.EqualError(t, p.JSONP(3141, "awesomeReact", nonMarshallableChannel), "json: unsupported type: chan bool") assert.Exactly(t, "", w.Body.String()) assert.Exactly(t, 200, w.Code) assert.Equal(t, "", w.Header().Get(httputil.ContentType)) }
func TestPrintJSONP(t *testing.T) { w := httptest.NewRecorder() p := httputil.NewPrinter(w, nil) assert.NoError(t, p.JSONP(3141, "awesomeReact", encodeData)) assert.Exactly(t, "awesomeReact([{\"Title\":\"Camera\",\"SKU\":\"323423423\",\"Price\":45.12},{\"Title\":\"LCD TV\",\"SKU\":\"8785344\",\"Price\":145.99}]\n);", w.Body.String()) assert.Exactly(t, 3141, w.Code) assert.Equal(t, httputil.ApplicationJavaScriptCharsetUTF8, w.Header().Get(httputil.ContentType)) }
func TestPrintXMLIndent(t *testing.T) { w := httptest.NewRecorder() p := httputil.NewPrinter(w, nil) assert.NoError(t, p.XMLIndent(3141, encodeData, "\n", "\t")) assert.Exactly(t, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<EncData>\n\n\t<Title>Camera</Title>\n\n\t<SKU>323423423</SKU>\n\n\t<Price>45.12</Price>\n\n</EncData>\n\n<EncData>\n\n\t<Title>LCD TV</Title>\n\n\t<SKU>8785344</SKU>\n\n\t<Price>145.99</Price>\n\n</EncData>", w.Body.String()) assert.Exactly(t, 3141, w.Code) assert.Equal(t, httputil.ApplicationXMLCharsetUTF8, w.Header().Get(httputil.ContentType)) }
func TestPrintXMLIndentError(t *testing.T) { w := httptest.NewRecorder() p := httputil.NewPrinter(w, nil) assert.EqualError(t, p.XMLIndent(3141, nonMarshallableChannel, " ", " "), "xml: unsupported type: chan bool") assert.Exactly(t, "", w.Body.String()) assert.Exactly(t, 200, w.Code) assert.Equal(t, "", w.Header().Get(httputil.ContentType)) }
func TestPrintWriteString(t *testing.T) { w := httptest.NewRecorder() p := httputil.NewPrinter(w, nil) assert.NoError(t, p.WriteString(3141, "Hello %s. Wanna have some %.5f?")) assert.Exactly(t, `Hello %s. Wanna have some %.5f?`, w.Body.String()) assert.Exactly(t, 3141, w.Code) assert.Equal(t, httputil.TextPlain, w.Header().Get(httputil.ContentType)) }
func TestContextMustReader(t *testing.T) { mr := config.NewMockReader() ctx := config.NewContextReader(context.Background(), mr) mrHave := config.FromContextReader(ctx) assert.Exactly(t, mr, mrHave) ctx = config.NewContextReader(context.Background(), nil) mrHave = config.FromContextReader(ctx) assert.Exactly(t, config.DefaultManager, mrHave) }
func TestContextMustGetter(t *testing.T) { mr := config.NewMockGetter() ctx := config.WithContextGetter(context.Background(), mr) mrHave := config.FromContextGetter(ctx) assert.Exactly(t, mr, mrHave) ctx = config.WithContextGetter(context.Background(), nil) mrHave = config.FromContextGetter(ctx) assert.Exactly(t, config.DefaultService, mrHave) }
func TestDefaultAdapterErrFunc(t *testing.T) { anErr := errors.New("This error should be returned") w := httptest.NewRecorder() req, err := http.NewRequest(httputil.MethodGet, "http://example.com/foo?_method=KARATE", nil) assert.NoError(t, err) ctxhttp.DefaultAdapterErrFunc(w, req, anErr) assert.Exactly(t, http.StatusBadRequest, w.Code) assert.Exactly(t, "Bad Request\nApp Error: This error should be returned\n", w.Body.String()) }
func TestPrintHTMLError(t *testing.T) { w := new(errorWriter) w.ResponseRecorder = httptest.NewRecorder() p := httputil.NewPrinter(w, nil) assert.EqualError(t, p.HTML(31415, "Hello %s", "Gophers"), "Not in the mood to write today") assert.Exactly(t, ``, w.Body.String()) assert.Exactly(t, 31415, w.Code) assert.Equal(t, httputil.TextHTMLCharsetUTF8, w.Header().Get(httputil.ContentType)) }
func TestContext(t *testing.T) { l := log.NewStdLogger() ctx := context.Background() ctx = ctxlog.NewContext(ctx, l) haveL := ctxlog.FromContext(ctx) assert.Exactly(t, l, haveL) haveL2 := ctxlog.FromContext(context.TODO()) assert.Exactly(t, log.BlackHole{}, haveL2) }
func finalHandlerFinland(t *testing.T) ctxhttp.HandlerFunc { return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { ipc, err, ok := geoip.FromContextCountry(ctx) assert.NotNil(t, ipc) assert.True(t, ok) assert.NoError(t, err) assert.Exactly(t, "2a02:d200::", ipc.IP.String()) assert.Exactly(t, "FI", ipc.Country.Country.IsoCode) return nil } }
func TestPrintRender(t *testing.T) { w := httptest.NewRecorder() p := httputil.NewPrinter(w, nil) tpl, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`) assert.NoError(t, err) p.Renderer = tpl assert.NoError(t, p.Render(3141, "T", "<script>alert('you have been pwned')</script>")) assert.Exactly(t, `Hello, <script>alert('you have been pwned')</script>!`, w.Body.String()) assert.Exactly(t, 3141, w.Code) assert.Equal(t, httputil.TextHTMLCharsetUTF8, w.Header().Get(httputil.ContentType)) }