aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--objects/object.go20
-rw-r--r--objects/object_test.go62
2 files changed, 82 insertions, 0 deletions
diff --git a/objects/object.go b/objects/object.go
index ced78bd..4e096ad 100644
--- a/objects/object.go
+++ b/objects/object.go
@@ -118,3 +118,23 @@ type Object interface {
Payload() []byte
FromPayload([]byte) error
}
+
+func (ro RawObject) Object() (o Object, err error) {
+ switch ro.Type {
+ case OTBlob:
+ o = new(Blob)
+ case OTFile:
+ o = new(File)
+ case OTTree:
+ o = make(Tree)
+ case OTSnapshot:
+ o = new(Snapshot)
+ default:
+ return nil, fmt.Errorf("Unknown object type %s", ro.Type)
+ }
+
+ if err = o.FromPayload(ro.Payload); err != nil {
+ o = nil
+ }
+ return
+}
diff --git a/objects/object_test.go b/objects/object_test.go
index 3808d13..2772501 100644
--- a/objects/object_test.go
+++ b/objects/object_test.go
@@ -3,6 +3,7 @@ package objects
import (
"bufio"
"bytes"
+ "fmt"
"testing"
)
@@ -104,3 +105,64 @@ func TestSerializeAndId(t *testing.T) {
t.Errorf("Verification failed")
}
}
+
+func unserializeObj(t *testing.T, ot ObjectType, b []byte) Object {
+ ro, err := Unserialize(bytes.NewReader(b))
+ if err != nil {
+ t.Fatalf("Failed unserializing: %s", err)
+ }
+
+ o, err := ro.Object()
+ if err != nil {
+ t.Fatalf("Failed generating Object from RawObject: %s", err)
+ }
+
+ if o.Type() != ot {
+ t.Fatalf("Unexpected object type, have %s, want %s", o.Type(), ot)
+ }
+
+ return o
+}
+
+func TestUnserializeBlobObj(t *testing.T) {
+ blob := unserializeObj(t, OTBlob, []byte(""+
+ "blob 6\n"+
+ "foobar")).(*Blob)
+
+ if string(*blob) != "foobar" {
+ t.Errorf("Unexpected blob content: %v", blob)
+ }
+}
+
+func TestUnserializeFileObj(t *testing.T) {
+ file := unserializeObj(t, OTFile, append(
+ []byte(fmt.Sprintf("file %d\n", len(testFileSerialization))),
+ testFileSerialization...,
+ )).(*File)
+
+ if !file.Equals(testFileObj) {
+ t.Errorf("Unexpected file object: %v", *file)
+ }
+}
+
+func TestUnserializeTreeObj(t *testing.T) {
+ tree := unserializeObj(t, OTTree, append(
+ []byte(fmt.Sprintf("tree %d\n", len(testTreeSerialization))),
+ testTreeSerialization...,
+ )).(Tree)
+
+ if !tree.Equals(testTreeObj) {
+ t.Errorf("Unexpected tree object: %v", tree)
+ }
+}
+
+func TestUnserializeSnapshotObj(t *testing.T) {
+ snapshot := unserializeObj(t, OTSnapshot, append(
+ []byte(fmt.Sprintf("snapshot %d\n", len(testSnapshotSerialization))),
+ testSnapshotSerialization...,
+ )).(*Snapshot)
+
+ if !snapshot.Equals(testSnapshotObj) {
+ t.Errorf("Unexpected snapshot object: %v", *snapshot)
+ }
+}