github.com/anacrolix/torrent@v1.61.0/test/sqlite_test.go (about)

     1  // This infernal language makes me copy conditional compilation expressions around. This test should
     2  // run if sqlite storage is enabled, period.
     3  
     4  //go:build cgo
     5  // +build cgo
     6  
     7  package test
     8  
     9  import (
    10  	"errors"
    11  	"net"
    12  	"net/http"
    13  	"testing"
    14  
    15  	qt "github.com/go-quicktest/qt"
    16  
    17  	"github.com/anacrolix/torrent"
    18  	"github.com/anacrolix/torrent/bencode"
    19  	"github.com/anacrolix/torrent/metainfo"
    20  	sqliteStorage "github.com/anacrolix/torrent/storage/sqlite"
    21  )
    22  
    23  func TestSqliteStorageClosed(t *testing.T) {
    24  	cfg := torrent.TestingConfig(t)
    25  	storage, err := sqliteStorage.NewDirectStorage(sqliteStorage.NewDirectStorageOpts{})
    26  	defer storage.Close()
    27  	cfg.DefaultStorage = storage
    28  	cfg.Debug = true
    29  	qt.Assert(t, qt.IsNil(err))
    30  	cl, err := torrent.NewClient(cfg)
    31  	qt.Assert(t, qt.IsNil(err))
    32  	defer cl.Close()
    33  	l, err := net.Listen("tcp", "localhost:0")
    34  	qt.Assert(t, qt.IsNil(err))
    35  	defer l.Close()
    36  	// We need at least once piece to trigger a call to storage to determine completion state. We
    37  	// need non-zero content length to trigger piece hashing.
    38  	i := metainfo.Info{
    39  		Pieces:      make([]byte, metainfo.HashSize),
    40  		PieceLength: 1,
    41  		Files: []metainfo.FileInfo{
    42  			{Length: 1},
    43  		},
    44  	}
    45  	mi := metainfo.MetaInfo{}
    46  	mi.InfoBytes, err = bencode.Marshal(i)
    47  	qt.Assert(t, qt.IsNil(err))
    48  	s := http.Server{
    49  		Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    50  			mi.Write(w)
    51  		}),
    52  	}
    53  	defer s.Close()
    54  	go func() {
    55  		err := s.Serve(l)
    56  		if !errors.Is(err, http.ErrServerClosed) {
    57  			panic(err)
    58  		}
    59  	}()
    60  	// Close storage prematurely.
    61  	storage.Close()
    62  	tor, _ := cl.AddTorrentOpt(torrent.AddTorrentOpts{
    63  		InfoHash: mi.HashInfoBytes(),
    64  	})
    65  	tor.AddSources([]string{"http://" + l.Addr().String()})
    66  	qt.Assert(t, qt.IsNil(err))
    67  	<-tor.GotInfo()
    68  }