github.com/astaxie/beego@v1.12.3/staticfile_test.go (about) 1 package beego 2 3 import ( 4 "bytes" 5 "compress/gzip" 6 "compress/zlib" 7 "fmt" 8 "io" 9 "io/ioutil" 10 "os" 11 "path/filepath" 12 "testing" 13 ) 14 15 var currentWorkDir, _ = os.Getwd() 16 var licenseFile = filepath.Join(currentWorkDir, "LICENSE") 17 18 func testOpenFile(encoding string, content []byte, t *testing.T) { 19 fi, _ := os.Stat(licenseFile) 20 b, n, sch, reader, err := openFile(licenseFile, fi, encoding) 21 if err != nil { 22 t.Log(err) 23 t.Fail() 24 } 25 26 t.Log("open static file encoding "+n, b) 27 28 assetOpenFileAndContent(sch, reader, content, t) 29 } 30 func TestOpenStaticFile_1(t *testing.T) { 31 file, _ := os.Open(licenseFile) 32 content, _ := ioutil.ReadAll(file) 33 testOpenFile("", content, t) 34 } 35 36 func TestOpenStaticFileGzip_1(t *testing.T) { 37 file, _ := os.Open(licenseFile) 38 var zipBuf bytes.Buffer 39 fileWriter, _ := gzip.NewWriterLevel(&zipBuf, gzip.BestCompression) 40 io.Copy(fileWriter, file) 41 fileWriter.Close() 42 content, _ := ioutil.ReadAll(&zipBuf) 43 44 testOpenFile("gzip", content, t) 45 } 46 func TestOpenStaticFileDeflate_1(t *testing.T) { 47 file, _ := os.Open(licenseFile) 48 var zipBuf bytes.Buffer 49 fileWriter, _ := zlib.NewWriterLevel(&zipBuf, zlib.BestCompression) 50 io.Copy(fileWriter, file) 51 fileWriter.Close() 52 content, _ := ioutil.ReadAll(&zipBuf) 53 54 testOpenFile("deflate", content, t) 55 } 56 57 func TestStaticCacheWork(t *testing.T) { 58 encodings := []string{"", "gzip", "deflate"} 59 60 fi, _ := os.Stat(licenseFile) 61 for _, encoding := range encodings { 62 _, _, first, _, err := openFile(licenseFile, fi, encoding) 63 if err != nil { 64 t.Error(err) 65 continue 66 } 67 68 _, _, second, _, err := openFile(licenseFile, fi, encoding) 69 if err != nil { 70 t.Error(err) 71 continue 72 } 73 74 address1 := fmt.Sprintf("%p", first) 75 address2 := fmt.Sprintf("%p", second) 76 if address1 != address2 { 77 t.Errorf("encoding '%v' can not hit cache", encoding) 78 } 79 } 80 } 81 82 func assetOpenFileAndContent(sch *serveContentHolder, reader *serveContentReader, content []byte, t *testing.T) { 83 t.Log(sch.size, len(content)) 84 if sch.size != int64(len(content)) { 85 t.Log("static content file size not same") 86 t.Fail() 87 } 88 bs, _ := ioutil.ReadAll(reader) 89 for i, v := range content { 90 if v != bs[i] { 91 t.Log("content not same") 92 t.Fail() 93 } 94 } 95 if staticFileLruCache.Len() == 0 { 96 t.Log("men map is empty") 97 t.Fail() 98 } 99 }