8 "go.uber.org/zap/zapcore"
15 type testCase struct {
16 name string // test case description
17 account Account // Account struct for a user that will test transaction will execute under
18 request *Transaction // transaction that will be sent by the client to the server
19 setup func() // Optional test-specific setup required for the scenario
20 teardown func() // Optional test-specific teardown for the scenario
21 mockHandler map[int]*mockClientHandler
24 func (tt *testCase) Setup(srv *Server) error {
25 if err := srv.NewUser(tt.account.Login, tt.account.Name, string(negateString([]byte(tt.account.Password))), *tt.account.Access); err != nil {
36 func (tt *testCase) Teardown(srv *Server) error {
37 if err := srv.DeleteUser(tt.account.Login); err != nil {
41 if tt.teardown != nil {
48 func NewTestLogger() *zap.SugaredLogger {
49 encoderCfg := zap.NewProductionEncoderConfig()
50 encoderCfg.TimeKey = "timestamp"
51 encoderCfg.EncodeTime = zapcore.ISO8601TimeEncoder
53 core := zapcore.NewCore(
54 zapcore.NewConsoleEncoder(encoderCfg),
55 zapcore.Lock(os.Stdout),
59 cores := []zapcore.Core{core}
60 l := zap.New(zapcore.NewTee(cores...))
61 defer func() { _ = l.Sync() }()
65 func StartTestServer() (*Server, context.Context, context.CancelFunc) {
66 ctx, cancelRoot := context.WithCancel(context.Background())
68 srv, err := NewServer("test/config/", "localhost", 0, NewTestLogger())
74 err := srv.ListenAndServe(ctx, cancelRoot)
80 return srv, ctx, cancelRoot
83 func TestHandshake(t *testing.T) {
84 srv, _, cancelFunc := StartTestServer()
87 port := srv.APIListener.Addr().(*net.TCPAddr).Port
89 conn, err := net.Dial("tcp", fmt.Sprintf(":%v", port))
95 conn.Write([]byte{0x54, 0x52, 0x54, 0x50, 0x00, 0x01, 0x00, 0x00})
97 replyBuf := make([]byte, 8)
98 _, _ = conn.Read(replyBuf)
100 want := []byte{84, 82, 84, 80, 0, 0, 0, 0}
101 if bytes.Compare(replyBuf, want) != 0 {
102 t.Errorf("%q, want %q", replyBuf, want)
107 //func TestLogin(t *testing.T) {
109 // tests := []struct {
114 // name: "when login is successful",
115 // client: NewClient("guest", NewTestLogger()),
118 // for _, test := range tests {
119 // t.Run(test.name, func(t *testing.T) {
125 func TestNewUser(t *testing.T) {
126 srv, _, _ := StartTestServer()
130 // name: "a valid new account",
131 // mockHandler: func() mockClientHandler {
132 // mh := mockClientHandler{}
133 // mh.On("Handle", mock.AnythingOfType("*hotline.Client"), mock.MatchedBy(func(t *Transaction) bool {
134 // println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
136 // spew.Dump(bytes.Equal(t.Type, []byte{0x01, 0x5e}))
137 // //if !bytes.Equal(t.GetField(fieldError).Data, []byte("You are not allowed to create new accounts.")) {
140 // return bytes.Equal(t.Type, []byte{0x01, 0x5e},
143 // []Transaction{}, nil,
146 // clientHandlers[tranNewUser] = mh
149 // client: func() *Client {
150 // c := NewClient("testUser", NewTestLogger())
153 // teardown: func() {
154 // _ = srv.DeleteUser("testUser")
160 // Access: &[]byte{255, 255, 255, 255, 255, 255, 255, 255},
162 // request: NewTransaction(
164 // NewField(fieldUserLogin, []byte(NegatedUserString([]byte("testUser")))),
165 // NewField(fieldUserName, []byte("testUserName")),
166 // NewField(fieldUserPassword, []byte(NegatedUserString([]byte("testPw")))),
167 // NewField(fieldUserAccess, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}),
169 // want: &Transaction{
170 // Fields: []Field{},
174 // name: "a newUser request from a user without the required access",
175 // mockHandler: func() *mockClientHandler {
176 // mh := mockClientHandler{}
177 // mh.On("Handle", mock.AnythingOfType("*hotline.Client"), mock.MatchedBy(func(t *Transaction) bool {
178 // if !bytes.Equal(t.GetField(fieldError).Data, []byte("You are not allowed to create new accounts.")) {
181 // return bytes.Equal(t.Type, []byte{0x01, 0x5e})
183 // []Transaction{}, nil,
187 // teardown: func() {
188 // _ = srv.DeleteUser("testUser")
194 // Access: &[]byte{0, 0, 0, 0, 0, 0, 0, 0},
196 // request: NewTransaction(
198 // NewField(fieldUserLogin, []byte(NegatedUserString([]byte("testUser")))),
199 // NewField(fieldUserName, []byte("testUserName")),
200 // NewField(fieldUserPassword, []byte(NegatedUserString([]byte("testPw")))),
201 // NewField(fieldUserAccess, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}),
205 // name: "when user does not have required permission",
206 // mockHandler: func() map[int]*mockClientHandler {
207 // mockHandlers := make(map[int]*mockClientHandler)
209 // mh := mockClientHandler{}
210 // mh.On("Handle", mock.AnythingOfType("*hotline.Client"), mock.MatchedBy(func(t *Transaction) bool {
211 // return t.equal(Transaction{
212 // Type: []byte{0x01, 0x5e},
214 // ErrorCode: []byte{0, 0, 0, 1},
216 // NewField(fieldError, []byte("You are not allowed to create new accounts.")),
220 // []Transaction{}, nil,
222 // mockHandlers[tranNewUser] = &mh
224 // return mockHandlers
227 // teardown: func() {
228 // _ = srv.DeleteUser("testUser")
234 // Access: &[]byte{0, 0, 0, 0, 0, 0, 0, 0},
236 // request: NewTransaction(
238 // NewField(fieldUserLogin, []byte(NegatedUserString([]byte("testUser")))),
239 // NewField(fieldUserName, []byte("testUserName")),
240 // NewField(fieldUserPassword, []byte(NegatedUserString([]byte("testPw")))),
241 // NewField(fieldUserAccess, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}),
246 // name: "a request to create a user that already exists",
250 // teardown: func() {
251 // _ = srv.DeleteUser("testUser")
257 // Access: &[]byte{255, 255, 255, 255, 255, 255, 255, 255},
259 // request: NewTransaction(
261 // NewField(fieldUserLogin, []byte(NegatedUserString([]byte("guest")))),
262 // NewField(fieldUserName, []byte("testUserName")),
263 // NewField(fieldUserPassword, []byte(NegatedUserString([]byte("testPw")))),
264 // NewField(fieldUserAccess, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}),
266 // want: &Transaction{
268 // NewField(fieldError, []byte("Cannot create account guest because there is already an account with that login.")),
274 for _, test := range tests {
275 t.Run(test.name, func(t *testing.T) {
279 c := NewClient(test.account.Name, NewTestLogger())
280 err := c.JoinServer(fmt.Sprintf(":%v", srv.APIPort()), test.account.Login, test.account.Password)
282 t.Errorf("login failed: %v", err)
284 // end move to Setup??
286 for key, value := range test.mockHandler {
287 c.Handlers[uint16(key)] = value
290 // send test case request
291 _ = c.Send(*test.request)
293 //time.Sleep(1 * time.Second)
296 transactions, _ := readN(c.Connection, 1)
297 for _, t := range transactions {
298 _ = c.HandleTransaction(&t)
303 for _, handler := range test.mockHandler {
304 handler.AssertExpectations(t)
312 // equal is a utility function used only in tests that determines if transactions are equal enough
313 func (t Transaction) equal(otherT Transaction) bool {
314 t.ID = []byte{0, 0, 0, 0}
315 otherT.ID = []byte{0, 0, 0, 0}
317 t.TotalSize = []byte{0, 0, 0, 0}
318 otherT.TotalSize = []byte{0, 0, 0, 0}
320 t.DataSize = []byte{0, 0, 0, 0}
321 otherT.DataSize = []byte{0, 0, 0, 0}
323 t.ParamCount = []byte{0, 0}
324 otherT.ParamCount = []byte{0, 0}
329 return reflect.DeepEqual(t, otherT)