70 lines
1.6 KiB
Go
70 lines
1.6 KiB
Go
package storage
|
|
|
|
import (
|
|
"bytes"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
|
|
"github.com/veggiedefender/torrent-client/internal/torrentfile"
|
|
)
|
|
|
|
func TestPieceReader(t *testing.T) {
|
|
tempDir := t.TempDir()
|
|
|
|
file1 := filepath.Join(tempDir, "file1.txt")
|
|
file2 := filepath.Join(tempDir, "file2.txt")
|
|
|
|
data1 := []byte("hello ") // 6 bytes
|
|
data2 := []byte("world!") // 6 bytes
|
|
|
|
if err := os.WriteFile(file1, data1, 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(file2, data2, 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
files := []torrentfile.File{
|
|
{Path: "file1.txt", Length: 6},
|
|
{Path: "file2.txt", Length: 6},
|
|
}
|
|
|
|
pr := NewPieceReader(files, 4, 12, tempDir)
|
|
|
|
// Test reading from first file only
|
|
// Piece 0, begin 0, length 4 -> "hell"
|
|
b, err := pr.ReadBlock(0, 0, 4)
|
|
if err != nil {
|
|
t.Fatalf("unexpected error: %v", err)
|
|
}
|
|
if !bytes.Equal(b, []byte("hell")) {
|
|
t.Errorf("expected 'hell', got %q", b)
|
|
}
|
|
|
|
// Test reading across files
|
|
// Piece 1, begin 0, length 4 -> absolute offset 4 -> "o wo"
|
|
b, err = pr.ReadBlock(1, 0, 4)
|
|
if err != nil {
|
|
t.Fatalf("unexpected error: %v", err)
|
|
}
|
|
if !bytes.Equal(b, []byte("o wo")) {
|
|
t.Errorf("expected 'o wo', got %q", b)
|
|
}
|
|
|
|
// Test reading at the end
|
|
// Piece 2, begin 0, length 4 -> absolute offset 8 -> "rld!"
|
|
b, err = pr.ReadBlock(2, 0, 4)
|
|
if err != nil {
|
|
t.Fatalf("unexpected error: %v", err)
|
|
}
|
|
if !bytes.Equal(b, []byte("rld!")) {
|
|
t.Errorf("expected 'rld!', got %q", b)
|
|
}
|
|
|
|
// Test reading out of bounds
|
|
_, err = pr.ReadBlock(2, 2, 4)
|
|
if err == nil {
|
|
t.Errorf("expected error when reading out of bounds")
|
|
}
|
|
}
|