github.com/zhongdalu/gf@v1.0.0/g/os/gfcache/gfcache_z_unit_test.go (about)

     1  // Copyright 2017 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/zhongdalu/gf.
     6  
     7  // go test *.go -bench=".*" -benchmem
     8  
     9  package gfcache_test
    10  
    11  import (
    12  	"io/ioutil"
    13  	"os"
    14  	"testing"
    15  	"time"
    16  
    17  	"github.com/zhongdalu/gf/g/os/gfcache"
    18  	"github.com/zhongdalu/gf/g/os/gfile"
    19  	"github.com/zhongdalu/gf/g/test/gtest"
    20  )
    21  
    22  func TestGetContents(t *testing.T) {
    23  	gtest.Case(t, func() {
    24  
    25  		var f *os.File
    26  		var err error
    27  		fileName := "test"
    28  		strTest := "123"
    29  
    30  		if !gfile.Exists(fileName) {
    31  			f, err = ioutil.TempFile("", fileName)
    32  			if err != nil {
    33  				t.Error("create file fail")
    34  			}
    35  		}
    36  
    37  		defer f.Close()
    38  		defer os.Remove(f.Name())
    39  
    40  		if gfile.Exists(f.Name()) {
    41  
    42  			f, err = gfile.OpenFile(f.Name(), os.O_APPEND|os.O_WRONLY, os.ModeAppend)
    43  			if err != nil {
    44  				t.Error("file open fail", err)
    45  			}
    46  
    47  			err = gfile.PutContents(f.Name(), strTest)
    48  			if err != nil {
    49  				t.Error("write error", err)
    50  			}
    51  
    52  			cache := gfcache.GetContents(f.Name(), 1)
    53  			gtest.Assert(cache, strTest)
    54  		}
    55  	})
    56  
    57  	gtest.Case(t, func() {
    58  
    59  		var f *os.File
    60  		var err error
    61  		fileName := "test2"
    62  		strTest := "123"
    63  
    64  		if !gfile.Exists(fileName) {
    65  			f, err = ioutil.TempFile("", fileName)
    66  			if err != nil {
    67  				t.Error("create file fail")
    68  			}
    69  		}
    70  
    71  		defer f.Close()
    72  		defer os.Remove(f.Name())
    73  
    74  		if gfile.Exists(f.Name()) {
    75  			cache := gfcache.GetContents(f.Name())
    76  
    77  			f, err = gfile.OpenFile(f.Name(), os.O_APPEND|os.O_WRONLY, os.ModeAppend)
    78  			if err != nil {
    79  				t.Error("file open fail", err)
    80  			}
    81  
    82  			err = gfile.PutContents(f.Name(), strTest)
    83  			if err != nil {
    84  				t.Error("write error", err)
    85  			}
    86  
    87  			gtest.Assert(cache, "")
    88  
    89  			time.Sleep(100 * time.Millisecond)
    90  		}
    91  	})
    92  }