aboutsummaryrefslogtreecommitdiff
path: root/models/infohash_test.go
blob: c1d9cca7fa47ab1ffd3ec44b65ad91cd521940cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package models

import (
	"encoding/hex"
	"testing"
)

func TestInfohashImport(t *testing.T) {

	tests := []struct {
		str string
		ok  bool
	}{
		{str: "5a3ce1c14e7a08645677bbd1cfe7d8f956d53256", ok: true},
		{str: "5a3ce1c14e7a08645677bbd1cfe7d8f956d53256000", ok: false},
	}

	for _, tt := range tests {
		ih, err := InfohashFromString(tt.str)
		if tt.ok {
			if err != nil {
				t.Errorf("FromString failed with %s", err)
			}

			idBytes, err := hex.DecodeString(tt.str)
			if err != nil {
				t.Errorf("failed to decode %s to hex", tt.str)
			}
			ih2 := Infohash(idBytes)
			if !ih.Equal(ih2) {
				t.Errorf("expected %s to equal %s", ih, ih2)
			}
			if ih.String() != tt.str {
				t.Errorf("expected ih.String() to equal %s, got %s", tt.str, ih.String())
			}
			byt := ih.Bytes()
			for i := range byt {
				if byt[i] != []byte(tt.str)[i] {
					t.Errorf("expected ih.Bytes() to equal %s, got %s", []byte(tt.str), ih.Bytes())
				}
			}
		} else {
			if err == nil {
				t.Errorf("FromString should have failed for %s", tt.str)
			}
		}
	}
}

func TestInfohashLength(t *testing.T) {
	ih := GenInfohash()
	if len(ih) != 20 {
		t.Errorf("%s as string should be length 20, got %d", ih, len(ih))
	}
}

func TestInfohashDistance(t *testing.T) {
	id := "d1c5676ae7ac98e8b19f63565905105e3c4c37a2"

	var tests = []struct {
		ih       string
		other    string
		distance int
	}{
		{id, id, 160},
		{id, "d1c5676ae7ac98e8b19f63565905105e3c4c37a3", 159},
	}

	ih, err := InfohashFromString(id)
	if err != nil {
		t.Errorf("Failed to create Infohash: %s", err)
	}

	for _, tt := range tests {
		other, err := InfohashFromString(tt.other)
		if err != nil {
			t.Errorf("Failed to create Infohash: %s", err)
		}

		dist := ih.Distance(*other)
		if dist != tt.distance {
			t.Errorf("Distance() => %d, expected %d", dist, tt.distance)
		}
	}
}