github.com/gogf/gf/v2@v2.7.4/encoding/gcompress/gcompress_z_unit_gzip_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 gcompress_test
     8  
     9  import (
    10  	"testing"
    11  
    12  	"github.com/gogf/gf/v2/encoding/gcompress"
    13  	"github.com/gogf/gf/v2/os/gfile"
    14  	"github.com/gogf/gf/v2/os/gtime"
    15  	"github.com/gogf/gf/v2/test/gtest"
    16  )
    17  
    18  func Test_Gzip_UnGzip(t *testing.T) {
    19  	var (
    20  		src  = "Hello World!!"
    21  		gzip = []byte{
    22  			0x1f, 0x8b, 0x08, 0x00, 0x00,
    23  			0x00, 0x00, 0x00, 0x00, 0xff,
    24  			0xf2, 0x48, 0xcd, 0xc9, 0xc9,
    25  			0x57, 0x08, 0xcf, 0x2f, 0xca,
    26  			0x49, 0x51, 0x54, 0x04, 0x04,
    27  			0x00, 0x00, 0xff, 0xff, 0x9d,
    28  			0x24, 0xa8, 0xd1, 0x0d, 0x00,
    29  			0x00, 0x00,
    30  		}
    31  	)
    32  
    33  	gtest.C(t, func(t *gtest.T) {
    34  		arr := []byte(src)
    35  		data, _ := gcompress.Gzip(arr)
    36  		t.Assert(data, gzip)
    37  
    38  		data, _ = gcompress.UnGzip(gzip)
    39  		t.Assert(data, arr)
    40  
    41  		data, _ = gcompress.UnGzip(gzip[1:])
    42  		t.Assert(data, nil)
    43  	})
    44  }
    45  
    46  func Test_Gzip_UnGzip_File(t *testing.T) {
    47  	var (
    48  		srcPath  = gtest.DataPath("gzip", "file.txt")
    49  		dstPath1 = gfile.Temp(gtime.TimestampNanoStr(), "gzip.zip")
    50  		dstPath2 = gfile.Temp(gtime.TimestampNanoStr(), "file.txt")
    51  	)
    52  
    53  	// Compress.
    54  	gtest.C(t, func(t *gtest.T) {
    55  		err := gcompress.GzipFile(srcPath, dstPath1, 9)
    56  		t.AssertNil(err)
    57  		defer gfile.Remove(dstPath1)
    58  		t.Assert(gfile.Exists(dstPath1), true)
    59  
    60  		// Decompress.
    61  		err = gcompress.UnGzipFile(dstPath1, dstPath2)
    62  		t.AssertNil(err)
    63  		defer gfile.Remove(dstPath2)
    64  		t.Assert(gfile.Exists(dstPath2), true)
    65  
    66  		t.Assert(gfile.GetContents(srcPath), gfile.GetContents(dstPath2))
    67  	})
    68  }