func TestOptions_Init(t *testing.T) { a := assert.New(t) o := &Options{Type: "html"} a.Error(o.Init()) // 未指定 dir o.Dir = "./" a.NotError(o.Init()) // 模板不存在 o.Template = "./not_exists" a.Error(o.Init()) // 未指定 template o.Type = "html+" o.Template = "" a.Error(o.Init()) // port 未指定 o.Type = "html+" o.Template = "./static" a.Error(o.Init()) // 修正 port o.Port = "1234" a.NotError(o.Init()) a.Equal(":1234", o.Port) }
func TestResultFields(t *testing.T) { a := assert.New(t) allow := []string{"col1", "col2", "col3"} // //ResultFields(r *http.Request, allow []string) ([]string, bool) r, err := http.NewRequest(http.MethodPut, "/test", nil) a.NotError(err).NotNil(r) // 非 GET 方法 ret, ok := ResultFields(r, allow) a.False(ok).Nil(ret) // 非 GET 方法,即使设置 Method 方法 r.Header.Set("X-Result-Fields", "col1, col2") ret, ok = ResultFields(r, allow) a.False(ok).Nil(ret) // 指定的字段都是允许的字段 r.Method = http.MethodGet ret, ok = ResultFields(r, allow) a.True(ok).Equal([]string{"col1", "col2"}, ret) // 包含不允许的字段 r.Header.Set("X-Result-Fields", "col1,col2, col100 ,col101") ret, ok = ResultFields(r, allow) a.False(ok).Equal([]string{"col100", "col101"}, ret) // 未指定 X-Result-Fields r.Header.Del("X-Result-Fields") ret, ok = ResultFields(r, allow) a.True(ok).Nil(nil) }
func TestMergeNest(t *testing.T) { a := assert.New(t) v1 := &s2{S2: "1", S3: &s1{}} v2 := &s2{S2: "2", S3: &s1{ID: 2, hide: 2}} // deep 为true时,会依次赋值子元素,hide不可导出,所以被忽略 a.NotError(merge(true, reflect.ValueOf(v1).Elem(), reflect.ValueOf(v2).Elem())) a.Equal(v1.ID, 0).Equal(v1.S3.ID, 2).Equal(v1.S3.hide, 0) // deep为false时,会将整个v2.S3赋给给v1.S3 a.NotError(merge(false, reflect.ValueOf(v1).Elem(), reflect.ValueOf(v2).Elem())) a.Equal(v1.ID, 0).Equal(v1.S3.ID, 2).Equal(v1.S3.hide, 2) // 自动初始化v1.S3 v1.S3 = nil a.NotError(merge(true, reflect.ValueOf(v1).Elem(), reflect.ValueOf(v2).Elem())) a.Equal(v1.ID, 0).Equal(v1.S3.ID, 2).Equal(v1.S3.hide, 0) // 不会初始化v1.S3 v1.S3 = nil v2.S3 = nil a.NotError(merge(true, reflect.ValueOf(v1).Elem(), reflect.ValueOf(v2).Elem())) a.Equal(v1.ID, 0).Nil(v1.S3) }
func TestInitFormXMLString(t *testing.T) { a := assert.New(t) // 重新注册以下用到的writer clearInitializer() a.True(Register("debug", logContInitializer), "注册debug时失败") a.True(Register("buffer", bufferInitializer), "注册buffer时失败") a.True(Register("debugW", debugWInit), "注册debugW时失败") xml := ` <?xml version="1.0" encoding="utf-8" ?> <logs> <debug prefix="[DEBUG]"> <buffer size="10"> <debugW /> </buffer> </debug> </logs> ` debugW.Reset() conts.Add(infoW) // 触发initFromXmlString中的重置功能 a.True(conts.Len() == 1) a.NotError(InitFromXMLString(xml)) a.True(critical == nil) // InitFromXMLString会重置所有的日志指向 a.True(CRITICAL() == nil) // InitFromXMLString会重置所有的日志指向 Debug("abc") a.True(debugW.Len() == 0) // 缓存未达10,依然为空 Allf("def\n") a.True(debugW.Len() == 0) // 缓存未达10,依然为空 // 测试Flush Flush() a.True(debugW.Len() > 0) }
func TestConfig_buildHeaders(t *testing.T) { a := assert.New(t) fh := func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("123")) } cfg := &Config{Headers: map[string]string{"Server": "test"}} h := cfg.buildHeader(http.HandlerFunc(fh)) r, err := http.NewRequest("GET", "", nil) a.NotError(err).NotNil(r) w := httptest.NewRecorder() h.ServeHTTP(w, r) a.Equal(w.Header().Get("Server"), "test") // 为空 cfg = &Config{Headers: map[string]string{}} h = cfg.buildHeader(http.HandlerFunc(fh)) r, err = http.NewRequest("GET", "", nil) a.NotError(err).NotNil(r) w = httptest.NewRecorder() h.ServeHTTP(w, r) a.Equal(w.Header().Get("Server"), "") }
func TestExtsIndex(t *testing.T) { a := assert.New(t) a.Equal(extsIndex[".cpp"], "cpp") a.Equal(extsIndex[".php"], "php") a.Equal(extsIndex[".go"], "go") }
func TestLexer_readN(t *testing.T) { a := assert.New(t) l := newLexer([]rune("line1\n @api line2 \n"), 100, "file.go") a.NotNil(l) words, err := l.readN(1, "@api") a.NotError(err).Equal(words, []string{"line1"}) l.match("@api") words, err = l.readN(1, "@api") // 行尾并没有@api,匹配eof a.NotError(err).Equal(words, []string{"line2"}) // 多词匹配 l = newLexer([]rune("word1 word2 word3 word4\n @api word5 word6 \n"), 100, "file.go") words, err = l.readN(2, "\n") a.NotError(err).Equal(words, []string{"word1", "word2 word3 word4"}) l.match("@api") words, err = l.readN(5, "\n") a.Error(err) l = newLexer([]rune("word1 word2 word3 word4\n"), 100, "file.go") words, err = l.readN(1, "\n") a.NotError(err).Equal(words, []string{"word1 word2 word3 word4"}) }
func TestTag_readLine(t *testing.T) { a := assert.New(t) l := &tag{data: []rune(" line1\n line2 \n")} a.Equal(l.readLine(), []rune("line1")) a.Equal(l.readLine(), []rune("line2")) }
func TestTag_readEnd(t *testing.T) { a := assert.New(t) l := &tag{data: []rune(" line1\n line2 \n")} a.Equal(l.readEnd(), "line1\n line2 \n") a.Equal(l.readEnd(), "") }
func TestBlock_endMComment(t *testing.T) { a := assert.New(t) b := &block{ Type: blockTypeSComment, Begin: "/*", End: "*/", } l := &lexer{ data: []byte("comment1\n*/"), } rs, found := b.endMComments(l) a.True(found).Equal(string(rs), "comment1\n") // 多个注释结束符 l = &lexer{ data: []byte("comment1\ncomment2*/*/"), } rs, found = b.endMComments(l) a.True(found).Equal(string(rs), "comment1\ncomment2") // 空格开头 l = &lexer{ data: []byte("\ncomment1\ncomment2*/*/"), } rs, found = b.endMComments(l) a.True(found).Equal(string(rs), "\ncomment1\ncomment2") // 没有注释结束符 l = &lexer{ data: []byte("comment1"), } rs, found = b.endMComments(l) a.False(found).Nil(rs) }
func TestQuery_Int(t *testing.T) { a := assert.New(t) form := url.Values(map[string][]string{ "q1": []string{"1"}, "q2": []string{"21", "22"}, "q4": []string{"four"}, }) r := &http.Request{Form: form} q := &Query{ abortOnError: false, errors: map[string]string{}, values: make(map[string]value, len(form)), request: r, } q1 := q.Int("q1", 12) msgs := q.Parse() a.Equal(len(msgs), 0).Equal(*q1, 1) q2 := q.Int64("q2", 12) msgs = q.Parse() a.Equal(len(msgs), 0).Equal(*q2, 21) q3 := q.Int64("q3", 32) msgs = q.Parse() a.Equal(len(msgs), 0).Equal(*q3, 32) // 出错的情况下,返回默认值 q4 := q.Int64("q4", 32) msgs = q.Parse() a.Equal(len(msgs), 1).Equal(*q4, 32) }
func TestBlock_endSComment(t *testing.T) { a := assert.New(t) b := &block{ Type: blockTypeSComment, Begin: `//`, } l := &lexer{ data: []byte("comment1\n"), } rs, err := b.endSComments(l) a.NotError(err).Equal(string(rs), "comment1\n") // 没有换行符,则自动取到结束符。 l = &lexer{ data: []byte("comment1"), } rs, err = b.endSComments(l) a.NotError(err).Equal(string(rs), "comment1") // 多行连续的单行注释。 l = &lexer{ data: []byte("comment1\n//comment2\n //comment3"), } rs, err = b.endSComments(l) a.NotError(err).Equal(string(rs), "comment1\ncomment2\ncomment3") // 多行不连续的单行注释。 l = &lexer{ data: []byte("comment1\n // comment2\n\n //comment3\n"), } rs, err = b.endSComments(l) a.NotError(err).Equal(string(rs), "comment1\n comment2\n") }
func TestBlock_endString(t *testing.T) { a := assert.New(t) b := &block{ Type: blockTypeString, Begin: `"`, End: `"`, Escape: "\\", } l := &lexer{ data: []byte(`text"`), } rs, ok := b.endString(l) a.True(ok).Nil(rs) // 带转义字符 l = &lexer{ data: []byte(`te\"xt"`), } rs, ok = b.endString(l) a.True(ok). Nil(rs). Equal(l.pos, len(l.data)) // 找不到匹配字符串 l = &lexer{ data: []byte("text"), } rs, ok = b.endString(l) a.False(ok).Nil(rs) }
// bytes func TestBytes1(t *testing.T) { a := assert.New(t) a.NotEqual(bytes(random, 10, []byte("1234123lks;df")), bytes(random, 10, []byte("1234123lks;df"))) a.NotEqual(bytes(random, 10, []byte("1234123lks;df")), bytes(random, 10, []byte("1234123lks;df"))) a.NotEqual(bytes(random, 10, []byte("1234123lks;df")), bytes(random, 10, []byte("1234123lks;df"))) }
func TestLogWriter_Write(t *testing.T) { a := assert.New(t) l := &logWriter{out: os.Stdout, prefix: "[TEST] ", color: colors.Red} _, err := l.Write([]byte("这是一行红色前缀的字")) a.NotError(err) }
func TestLexer_match(t *testing.T) { a := assert.New(t) l := newLexer([]rune("line1\n line2 \n\t\tline3\n")) a.NotNil(l) a.True(l.match("Line")) a.Equal('1', l.data[l.pos]) l.pos++ l.pos++ // \n l.pos++ // 空格 l.pos++ // l a.False(l.match("2222")) // 不匹配 a.False(l.match("ine2")) // 前面有非空白字符,不匹配 l.pos += 8 // ine2 \n\t\t a.True(l.match("line3")) l.backup() l.backup() a.True(l.match("line3")) // 多次调用 backup 应该和调用一次的作用是一样的。 l.backup() a.False(l.match("line3\n\n")) // 不匹配,超长了。 a.True(l.match("line3\n")) // 能正确匹配结尾字符 l = newLexer([]rune("line1\n")) a.NotNil(l) a.True(l.match("line1\n")) }
func TestConfig_init(t *testing.T) { a := assert.New(t) conf := &config{} err := conf.init() a.Equal(err.Field, "version") // 版本号错误 conf.Version = "1.0" err = conf.init() a.Equal(err.Field, "version") // 未声明 inputs conf.Version = "1.0.1" err = conf.init() a.Equal(err.Field, "inputs") // 未声明 output conf.Inputs = []*input.Options{&input.Options{}} err = conf.init() a.Equal(err.Field, "output") // 查看错误提示格式是否正确 conf.Output = &output.Options{} conf.Inputs = append(conf.Inputs, &input.Options{ Lang: "123", }) err = conf.init() a.True(strings.HasPrefix(err.Field, "inputs[0]")) }
func TestTag_lineNumber(t *testing.T) { a := assert.New(t) l := &lexer{data: []rune("line0\nline1\nline2\n @api line3\n")} t1 := l.readTag() a.NotNil(t1) a.Equal(t1.lineNumber(), 0) a.Equal(t1.readLine(), "line0") a.Equal(t1.lineNumber(), 0) a.Equal(t1.readLine(), "line1") a.Equal(t1.lineNumber(), 1) // l.pos 不是从 0 开始 l.pos = 6 t1 = l.readTag() a.NotNil(t1) a.Equal(t1.lineNumber(), 1) a.Equal(t1.readLine(), "line1") a.Equal(t1.lineNumber(), 1) a.Equal(t1.readLine(), "line2") a.Equal(t1.lineNumber(), 2) }
func TestLexer_scanApiExample(t *testing.T) { a := assert.New(t) // 正常测试 code := ` xml <root> <data>123</data> </root>` matchCode := `<root> <data>123</data> </root>` l := newLexer([]rune(code), 100, "file.go") a.NotNil(l) e, err := l.scanApiExample() a.NotError(err). Equal(e.Type, "xml"). Equal(e.Code, matchCode) code = ` xml <root> <data>123</data> </root> @apiURL abc/test` matchCode = `<root> <data>123</data> </root>` l = newLexer([]rune(code), 100, "file.go") a.NotNil(l) e, err = l.scanApiExample() a.NotError(err). Equal(e.Type, "xml"). Equal(len(e.Code), len(matchCode)). Equal(e.Code, matchCode) }
func TestToByte(t *testing.T) { a := assert.New(t) eq := func(str string, val int64) { size, err := toByte(str) a.NotError(err).Equal(size, val) } e := func(str string) { size, err := toByte(str) a.Error(err).Equal(size, -1) } eq("1m", 1024*1024) eq("100G", 100*1024*1024*1024) eq("10.2k", 10*1024) eq("10.9K", 10*1024) e("") e("M") e("-1M") e("-1.0G") e("1P") e("10MB") }
// BenchmarkMake 5000 229378 ns/op func BenchmarkMake(b *testing.B) { a := assert.New(b) for i := 0; i < b.N; i++ { img, err := Make(size, back, fore, []byte("Make")) a.NotError(err).NotNil(img) } }
func TestRotateInitializer(t *testing.T) { a := assert.New(t) args := map[string]string{} w, err := rotateInitializer(args) a.Error(err).Nil(w) // 缺少size args["dir"] = "./testdata" w, err = rotateInitializer(args) a.Error(err).Nil(w) // 错误的size参数 args["size"] = "12P" w, err = rotateInitializer(args) a.Error(err).Nil(w) // 正常 args["size"] = "12" w, err = rotateInitializer(args) a.NotError(err).NotNil(w) _, ok := w.(*writers.Rotate) a.True(ok) }
func TestConfig_buildBeforeAfter(t *testing.T) { a := assert.New(t) beforeAfter := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ba")) }) fh := func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("123")) } r, err := http.NewRequest("GET", "", nil) a.NotError(err).NotNil(r) // before cfg := &Config{Before: beforeAfter} h := cfg.buildBefore(http.HandlerFunc(fh)) a.NotNil(h) w := httptest.NewRecorder() h.ServeHTTP(w, r) a.Equal(w.Body.String(), "ba123") // after cfg = &Config{After: beforeAfter} h = cfg.buildAfter(http.HandlerFunc(fh)) a.NotNil(h) w = httptest.NewRecorder() h.ServeHTTP(w, r) a.Equal(w.Body.String(), "123ba") // before & after cfg = &Config{Before: beforeAfter, After: beforeAfter} h = cfg.buildAfter(cfg.buildBefore(http.HandlerFunc(fh))) a.NotNil(h) w = httptest.NewRecorder() h.ServeHTTP(w, r) a.Equal(w.Body.String(), "ba123ba") }
func TestConsoleInitializer(t *testing.T) { a := assert.New(t) args := map[string]string{} // 可以接受空参数,consoleInitializer的args都有默认值 w, err := consoleInitializer(args) a.NotError(err).NotNil(w) // 无效的output args["output"] = "stdin" w, err = consoleInitializer(args) a.Error(err).Nil(w) args["output"] = "stderr" // 无效的foreground args["foreground"] = "red1" w, err = consoleInitializer(args) a.Error(err).Nil(w) args["foreground"] = "red" // 无效的background args["background"] = "red1" w, err = consoleInitializer(args) a.Error(err).Nil(w) args["background"] = "blue" w, err = consoleInitializer(args) a.NotError(err).NotNil(w) _, ok := w.(*writers.Console) a.True(ok) }
func TestConfig_buildPprof(t *testing.T) { a := assert.New(t) fh := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) w.Write([]byte("123")) } cfg := &Config{Pprof: "/debug/"} h := cfg.buildPprof(http.HandlerFunc(fh)) srv := httptest.NewServer(h) defer srv.Close() resp, err := http.Get(srv.URL + "/debug/synbol") a.NotError(err).NotNil(resp) a.Equal(resp.StatusCode, http.StatusOK) resp, err = http.Get(srv.URL + "/debug/cmdline") a.NotError(err).NotNil(resp) a.Equal(resp.StatusCode, http.StatusOK) // 不存在的路由,跳转到fh函数 resp, err = http.Get(srv.URL + "/debug1/cmdline") a.NotError(err).NotNil(resp) a.Equal(resp.StatusCode, http.StatusNotFound) }
func TestCheckConfigURL(t *testing.T) { a := assert.New(t) a.Error(checkConfigURL("", "uploadURL")) a.Error(checkConfigURL("/abc/", "uploadURL")) a.NotError(checkConfigURL("/abc", "uploadURL")) }
func TestLoadThemeFile(t *testing.T) { a := assert.New(t) theme, err := loadThemeFile("./testdata/theme1/theme.json") a.NotError(err) a.Equal(theme.Name, "default").Equal(theme.Author.Name, "caixw") }
func TestGetOption(t *testing.T) { a := assert.New(t) options = &Options{PageSize: 22} val, found := GetOption("pageSize") a.True(found).Equal(val, 22) }
func TestInit(t *testing.T) { a := assert.New(t) _, err := Init() a.NotError(err) a.True(len(locales) > 0) }
func TestRecursivePath(t *testing.T) { a := assert.New(t) a.Equal(recursivePath(false, []string{"./testdir"}), []string{ "./testdir", }) a.Equal(recursivePath(true, []string{"./testdir"}), []string{ "./testdir", "testdir/testdir1", "testdir/testdir2", "testdir/testdir2/testdir3", }) a.Equal(recursivePath(true, []string{"./testdir/testdir1", "./testdir/testdir2"}), []string{ "./testdir/testdir1", "./testdir/testdir2", "testdir/testdir2/testdir3", }) a.Equal(recursivePath(true, []string{"./testdir/testdir2"}), []string{ "./testdir/testdir2", "testdir/testdir2/testdir3", }) }