aboutsummaryrefslogtreecommitdiffstats
path: root/entity/dag/operation_testing.go
blob: 6ebdcae8408aa267d5c4c536dd05aa199be6d32d (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
package dag

import (
	"encoding/json"
	"testing"
	"time"

	"github.com/stretchr/testify/require"

	"github.com/MichaelMure/git-bug/entities/identity"
	"github.com/MichaelMure/git-bug/entity"
	"github.com/MichaelMure/git-bug/repository"
)

// SerializeRoundTripTest realize a marshall/unmarshall round-trip in the same condition as with OperationPack,
// and check if the recovered operation is identical.
func SerializeRoundTripTest[OpT Operation](t *testing.T, maker func(author identity.Interface, unixTime int64) OpT) {
	repo := repository.NewMockRepo()

	rene, err := identity.NewIdentity(repo, "René Descartes", "rene@descartes.fr")
	require.NoError(t, err)

	op := maker(rene, time.Now().Unix())
	// enforce having an id
	op.Id()

	rdt := &roundTripper[OpT]{Before: op, author: rene}

	data, err := json.Marshal(rdt)
	require.NoError(t, err)

	err = json.Unmarshal(data, &rdt)
	require.NoError(t, err)

	require.Equal(t, op, rdt.after)
}

type roundTripper[OpT Operation] struct {
	Before OpT
	author identity.Interface
	after  OpT
}

func (r *roundTripper[OpT]) MarshalJSON() ([]byte, error) {
	return json.Marshal(r.Before)
}

func (r *roundTripper[OpT]) UnmarshalJSON(data []byte) error {
	if err := json.Unmarshal(data, &r.after); err != nil {
		return err
	}
	// Set the id from the serialized data
	r.after.setId(entity.DeriveId(data))
	// Set the author, as OperationPack would do
	r.after.setAuthor(r.author)
	return nil
}