github.com/anacrolix/torrent@v1.61.0/bencode/both_test.go (about)

     1  package bencode
     2  
     3  import (
     4  	"bytes"
     5  	"os"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  	"github.com/stretchr/testify/require"
    10  )
    11  
    12  func loadFile(name string, t *testing.T) []byte {
    13  	data, err := os.ReadFile(name)
    14  	require.NoError(t, err)
    15  	return data
    16  }
    17  
    18  func testFileInterface(t *testing.T, filename string) {
    19  	data1 := loadFile(filename, t)
    20  
    21  	var iface interface{}
    22  	err := Unmarshal(data1, &iface)
    23  	require.NoError(t, err)
    24  
    25  	data2, err := Marshal(iface)
    26  	require.NoError(t, err)
    27  
    28  	assert.EqualValues(t, data1, data2)
    29  }
    30  
    31  func TestBothInterface(t *testing.T) {
    32  	testFileInterface(t, "testdata/archlinux-2011.08.19-netinstall-i686.iso.torrent")
    33  	testFileInterface(t, "testdata/continuum.torrent")
    34  }
    35  
    36  type torrentFile struct {
    37  	Info struct {
    38  		Name        string `bencode:"name"`
    39  		Length      int64  `bencode:"length"`
    40  		MD5Sum      string `bencode:"md5sum,omitempty"`
    41  		PieceLength int64  `bencode:"piece length"`
    42  		Pieces      string `bencode:"pieces"`
    43  		Private     bool   `bencode:"private,omitempty"`
    44  	} `bencode:"info"`
    45  
    46  	Announce     string      `bencode:"announce"`
    47  	AnnounceList [][]string  `bencode:"announce-list,omitempty"`
    48  	CreationDate int64       `bencode:"creation date,omitempty"`
    49  	Comment      string      `bencode:"comment,omitempty"`
    50  	CreatedBy    string      `bencode:"created by,omitempty"`
    51  	URLList      interface{} `bencode:"url-list,omitempty"`
    52  }
    53  
    54  func testFile(t *testing.T, filename string) {
    55  	data1 := loadFile(filename, t)
    56  	var f torrentFile
    57  
    58  	err := Unmarshal(data1, &f)
    59  	if err != nil {
    60  		t.Fatal(err)
    61  	}
    62  
    63  	data2, err := Marshal(&f)
    64  	if err != nil {
    65  		t.Fatal(err)
    66  	}
    67  
    68  	if !bytes.Equal(data1, data2) {
    69  		println(string(data2))
    70  		t.Fatalf("equality expected")
    71  	}
    72  }
    73  
    74  func TestBoth(t *testing.T) {
    75  	testFile(t, "testdata/archlinux-2011.08.19-netinstall-i686.iso.torrent")
    76  }