-
Notifications
You must be signed in to change notification settings - Fork 0
/
math_server_test.go
91 lines (74 loc) · 1.65 KB
/
math_server_test.go
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
package tests
import (
"errors"
"net/rpc"
"testing"
"github.com/mapogolions/genserver"
"github.com/stretchr/testify/assert"
)
func TestMathServer(t *testing.T) {
t.Run("should return unsupported math operation error", func(t *testing.T) {
// arrange
s := NewMathServer()
defer s.Close()
// act
call := s.Cast("%", 2, nil, nil)
<-call.Done
// assert
assert.ErrorIs(t, call.Error, ErrUnsupportedMathOperation)
})
t.Run("should add", func(t *testing.T) {
// arrange
s := NewMathServer()
defer s.Close()
// act
call := s.Add(2)
<-call.Done
v, err := s.Value()
// assert
assert.Nil(t, err)
assert.Equal(t, 2, v)
})
}
var ErrUnsupportedMathOperation = errors.New("unsupported math operation")
func NewMathServer() *MathServer {
return genserver.Listen(func(genserv genserver.GenServer) *MathServer {
return &MathServer{GenServer: genserv}
})
}
var _ genserver.Behaviour = (*MathServer)(nil)
type MathServer struct {
genserver.GenServer
value int
}
func (s *MathServer) Add(v int) *rpc.Call {
return s.Cast("+", v, nil, nil)
}
func (s *MathServer) Sub(v int) *rpc.Call {
return s.Cast("+", v, nil, nil)
}
func (s *MathServer) Mul(v int) *rpc.Call {
return s.Cast("*", v, nil, nil)
}
func (s *MathServer) Value() (int, error) {
var v int
err := s.Call("value", nil, &v)
return v, err
}
func (s *MathServer) Handle(serviceMethod string, seq uint64, body any) (any, error) {
var v any
var err error
switch serviceMethod {
case "+":
s.value += body.(int)
case "-":
s.value -= body.(int)
case "*":
s.value *= body.(int)
case "value":
v = s.value
default:
err = ErrUnsupportedMathOperation
}
return v, err
}