aboutsummaryrefslogtreecommitdiff
path: root/librsync/librsync_test.go
blob: 16f963301e88969d1995154627e7129c088ae57f (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
86
87
88
package librsync // import "code.laria.me/golibrsync/librsync"

import (
	"bytes"
	"code.laria.me/golibrsync/librsync/testdata"
	"io"
	"testing"
)

func TestSignatureDeltaPatch(t *testing.T) {
	// Generate signature
	orig := bytes.NewReader(testdata.RandomData())

	sigbuf := new(bytes.Buffer)
	siggen, err := NewDefaultSignatureGen(orig)
	if err != nil {
		t.Fatalf("could not create a signature generator: %s", err)
	}
	defer siggen.Close()

	if _, err = io.Copy(sigbuf, siggen); err != nil {
		t.Fatalf("Creating the signature failed: %s", err)
	}

	matches := false
	// Check both possible signatures.
	for _, sigcheck := range testdata.RandomDataSig() {
		if bytes.Equal(sigbuf.Bytes(), sigcheck) {
			matches = true
		}
	}
	if !matches {
		if path, err := dump(sigbuf); err == nil {
			t.Fatalf("Signatures do not match. Generated signature dumped to %s", path)
		} else {
			t.Fatalf("Signatures do not match. Could not dump signature: %s", err)
		}
	}

	// Loading signature
	sig, err := LoadSignature(sigbuf)
	if err != nil {
		t.Fatalf("Loading signature failed: %s", err)
	}
	defer sig.Close()

	// Generate delta
	mutation := bytes.NewReader(testdata.Mutation())

	deltabuf := new(bytes.Buffer)
	deltagen, err := NewDeltaGen(sig, mutation)
	if err != nil {
		t.Fatalf("could not create a delta generator: %s", err)
	}
	defer deltagen.Close()

	if _, err = io.Copy(deltabuf, deltagen); err != nil {
		t.Fatalf("Creating the delta failed: %s", err)
	}

	if !bytes.Equal(deltabuf.Bytes(), testdata.Delta()) {
		if path, err := dump(deltabuf); err == nil {
			t.Fatalf("deltas do not match. Generated delta dumped to %s", path)
		} else {
			t.Fatalf("deltas do not match. Could not dump delta: %s", err)
		}
	}

	// Apply Patch
	patchres := new(bytes.Buffer)
	patcher, err := NewPatcher(deltabuf, orig)
	if err != nil {
		t.Fatalf("could not create a patcher: %s", err)
	}
	defer patcher.Close()

	if _, err = io.Copy(patchres, patcher); err != nil {
		t.Fatalf("Applying the patch failed: %s", err)
	}

	if !bytes.Equal(patchres.Bytes(), testdata.Mutation()) {
		if path, err := dump(patchres); err == nil {
			t.Fatalf("patch result and mutation are not equal. Result dumped to %s", path)
		} else {
			t.Fatalf("patch result and mutation are not equal. Could not dump result: %s", err)
		}
	}
}