operation_testing.go

 1package dag
 2
 3import (
 4	"encoding/json"
 5	"testing"
 6	"time"
 7
 8	"github.com/stretchr/testify/require"
 9
10	"github.com/MichaelMure/git-bug/entities/identity"
11	"github.com/MichaelMure/git-bug/entity"
12	"github.com/MichaelMure/git-bug/repository"
13)
14
15// SerializeRoundTripTest realize a marshall/unmarshall round-trip in the same condition as with OperationPack,
16// and check if the recovered operation is identical.
17func SerializeRoundTripTest[OpT Operation](t *testing.T, maker func(author identity.Interface, unixTime int64) OpT) {
18	repo := repository.NewMockRepo()
19
20	rene, err := identity.NewIdentity(repo, "René Descartes", "rene@descartes.fr")
21	require.NoError(t, err)
22
23	op := maker(rene, time.Now().Unix())
24	// enforce having an id
25	op.Id()
26
27	rdt := &roundTripper[OpT]{Before: op, author: rene}
28
29	data, err := json.Marshal(rdt)
30	require.NoError(t, err)
31
32	err = json.Unmarshal(data, &rdt)
33	require.NoError(t, err)
34
35	require.Equal(t, op, rdt.after)
36}
37
38type roundTripper[OpT Operation] struct {
39	Before OpT
40	author identity.Interface
41	after  OpT
42}
43
44func (r *roundTripper[OpT]) MarshalJSON() ([]byte, error) {
45	return json.Marshal(r.Before)
46}
47
48func (r *roundTripper[OpT]) UnmarshalJSON(data []byte) error {
49	if err := json.Unmarshal(data, &r.after); err != nil {
50		return err
51	}
52	// Set the id from the serialized data
53	r.after.setId(entity.DeriveId(data))
54	// Set the author, as OperationPack would do
55	r.after.setAuthor(r.author)
56	return nil
57}