aboutsummaryrefslogtreecommitdiffstats
path: root/entity/entity_test.go
blob: 92a531796ac57d31c72e2528cbe6c9412693b2c5 (plain) (blame)
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package entity

import (
	"encoding/json"
	"fmt"
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/MichaelMure/git-bug/repository"
)

// func TestFoo(t *testing.T) {
// 	repo, err := repository.OpenGoGitRepo("~/dev/git-bug", nil)
// 	require.NoError(t, err)
//
// 	b, err := ReadBug(repo, Id("8b22e548c93a6ed23c31fd4e337c6286c3d1e5c9cae5537bc8e5842e11bd1099"))
// 	require.NoError(t, err)
//
// 	fmt.Println(b)
// }

type op1 struct {
	OperationType int    `json:"type"`
	Field1        string `json:"field_1"`
}

func newOp1(field1 string) *op1 {
	return &op1{OperationType: 1, Field1: field1}
}

func (o op1) Id() Id {
	data, _ := json.Marshal(o)
	return DeriveId(data)
}

func (o op1) Validate() error { return nil }

type op2 struct {
	OperationType int    `json:"type"`
	Field2        string `json:"field_2"`
}

func newOp2(field2 string) *op2 {
	return &op2{OperationType: 2, Field2: field2}
}

func (o op2) Id() Id {
	data, _ := json.Marshal(o)
	return DeriveId(data)
}

func (o op2) Validate() error { return nil }

var def = Definition{
	typename:             "foo",
	namespace:            "foos",
	operationUnmarshaler: unmarshaller,
	formatVersion:        1,
}

func unmarshaller(raw json.RawMessage) (Operation, error) {
	var t struct {
		OperationType int `json:"type"`
	}

	if err := json.Unmarshal(raw, &t); err != nil {
		return nil, err
	}

	switch t.OperationType {
	case 1:
		op := &op1{}
		err := json.Unmarshal(raw, &op)
		return op, err
	case 2:
		op := &op2{}
		err := json.Unmarshal(raw, &op)
		return op, err
	default:
		return nil, fmt.Errorf("unknown operation type %v", t.OperationType)
	}
}

func TestWriteRead(t *testing.T) {
	repo := repository.NewMockRepo()

	entity := New(def)
	require.False(t, entity.NeedCommit())

	entity.Append(newOp1("foo"))
	entity.Append(newOp2("bar"))

	require.True(t, entity.NeedCommit())
	require.NoError(t, entity.CommitAdNeeded(repo))
	require.False(t, entity.NeedCommit())

	entity.Append(newOp2("foobar"))
	require.True(t, entity.NeedCommit())
	require.NoError(t, entity.CommitAdNeeded(repo))
	require.False(t, entity.NeedCommit())

	read, err := Read(def, repo, entity.Id())
	require.NoError(t, err)

	fmt.Println(*read)
}