github.com/enetx/g@v1.0.80/tests/file_encdec_test.go (about) 1 package g_test 2 3 import ( 4 "testing" 5 6 "github.com/enetx/g" 7 ) 8 9 func TestGobEncodingDecoding(t *testing.T) { 10 file, err := g.NewFile("testfile.gob").CreateTemp().Result() 11 if err != nil { 12 t.Fatalf("Failed to create a temporary file: %v", err) 13 } 14 15 defer file.Remove() 16 17 // Encode data to the file 18 dataToEncode := g.SliceOf(1, 2, 3, 4, 5) 19 result := file.Enc().Gob(dataToEncode) 20 if result.IsErr() { 21 t.Fatalf("Gob encoding failed: %v", result.Err()) 22 } 23 24 // Decode data from the file 25 var decodedData g.Slice[int] 26 result = file.Dec().Gob(&decodedData) 27 if result.IsErr() { 28 t.Fatalf("Gob decoding failed: %v", result.Err()) 29 } 30 31 if dataToEncode.Ne(decodedData) { 32 t.Errorf("Decoded data does not match the original data.") 33 } 34 } 35 36 func TestJSONEncodingDecoding(t *testing.T) { 37 file, err := g.NewFile("testfile.json").CreateTemp().Result() 38 if err != nil { 39 t.Fatalf("Failed to create a temporary file: %v", err) 40 } 41 42 defer file.Remove() 43 44 // Encode data to the file 45 dataToEncode := g.SliceOf(1, 2, 3, 4, 5) 46 result := file.Enc().JSON(dataToEncode) 47 if result.IsErr() { 48 t.Fatalf("JSON encoding failed: %v", result.Err()) 49 } 50 51 // Decode data from the file 52 var decodedData g.Slice[int] 53 result = file.Dec().JSON(&decodedData) 54 if result.IsErr() { 55 t.Fatalf("JSON decoding failed: %v", result.Err()) 56 } 57 58 if dataToEncode.Ne(decodedData) { 59 t.Errorf("Decoded data does not match the original data.") 60 } 61 }