github.com/gogf/gf/v2@v2.7.4/os/gfile/gfile_z_unit_cache_test.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). 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/gogf/gf.
     6  
     7  package gfile_test
     8  
     9  import (
    10  	"os"
    11  	"testing"
    12  	"time"
    13  
    14  	"github.com/gogf/gf/v2/os/gfile"
    15  	"github.com/gogf/gf/v2/test/gtest"
    16  )
    17  
    18  func Test_GetContentsWithCache(t *testing.T) {
    19  	gtest.C(t, func(t *gtest.T) {
    20  		var f *os.File
    21  		var err error
    22  		fileName := "test"
    23  		strTest := "123"
    24  
    25  		if !gfile.Exists(fileName) {
    26  			f, err = os.CreateTemp("", fileName)
    27  			if err != nil {
    28  				t.Error("create file fail")
    29  			}
    30  		}
    31  
    32  		defer f.Close()
    33  		defer os.Remove(f.Name())
    34  
    35  		if gfile.Exists(f.Name()) {
    36  			f, err = gfile.OpenFile(f.Name(), os.O_APPEND|os.O_WRONLY, os.ModeAppend)
    37  			if err != nil {
    38  				t.Error("file open fail", err)
    39  			}
    40  
    41  			err = gfile.PutContents(f.Name(), strTest)
    42  			if err != nil {
    43  				t.Error("write error", err)
    44  			}
    45  
    46  			cache := gfile.GetContentsWithCache(f.Name(), 1)
    47  			t.Assert(cache, strTest)
    48  		}
    49  	})
    50  
    51  	gtest.C(t, func(t *gtest.T) {
    52  
    53  		var f *os.File
    54  		var err error
    55  		fileName := "test2"
    56  		strTest := "123"
    57  
    58  		if !gfile.Exists(fileName) {
    59  			f, err = os.CreateTemp("", fileName)
    60  			if err != nil {
    61  				t.Error("create file fail")
    62  			}
    63  		}
    64  
    65  		defer f.Close()
    66  		defer os.Remove(f.Name())
    67  
    68  		if gfile.Exists(f.Name()) {
    69  			cache := gfile.GetContentsWithCache(f.Name())
    70  
    71  			f, err = gfile.OpenFile(f.Name(), os.O_APPEND|os.O_WRONLY, os.ModeAppend)
    72  			if err != nil {
    73  				t.Error("file open fail", err)
    74  			}
    75  
    76  			err = gfile.PutContents(f.Name(), strTest)
    77  			if err != nil {
    78  				t.Error("write error", err)
    79  			}
    80  
    81  			t.Assert(cache, "")
    82  
    83  			time.Sleep(100 * time.Millisecond)
    84  		}
    85  	})
    86  }