package server

import (
	"fmt"
	"os"
	"path"
	"testing"
)

func writeFile(file string, content []byte) (err error) {
	var fp *os.File
	if err = os.MkdirAll(path.Dir(file), os.ModeDir|0700); err != nil {
		return err
	}
	if fp, err = os.Create(file); err != nil {
		return err
	}
	defer fp.Close()

	if _, err = fp.Write(content); err != nil {
		return err
	}

	return nil
}

func TestBinaryDiff(t *testing.T) {
	var err error
	// Creating some files for testing.
	if err = writeFile("_tests/file-a", []byte(`in a gadda da vida, honey, don't you know that I'm loving you.`)); err != nil {
		t.Fatal(fmt.Sprintf("Failed to write test file: %q", err))
	}
	if err = writeFile("_tests/file-b", []byte(`in a gadda da vida, baby, don't you know that I'll always be true.`)); err != nil {
		t.Fatal(fmt.Sprintf("Failed to write test file: %q", err))
	}
	// Creating binary diffs.
	var patchfile string
	if patchfile, err = bsdiff("_tests/file-a", "_tests/file-b"); err != nil {
		t.Fatal(fmt.Sprintf("Failed to generate binary diff: %q", err))
	}
	// Testing patch application.
	if err = bspatch("_tests/file-a", "_tests/file-c", patchfile); err != nil {
		t.Fatal(fmt.Sprintf("Failed to apply binary diff: %q", err))
	}
	// At this point a new _tests/file-c should have been generated by patching
	// _tests/file-a with the patch created before, the contents of this file-c
	// must be exactly the same than the contents of file-b.
	if fileHash("_tests/file-c") != fileHash("_tests/file-b") {
		t.Fatal("File hashes after patch must be equal.")
	}
}
