7 "github.com/davecgh/go-spew/spew"
8 "github.com/stretchr/testify/assert"
10 "go.uber.org/zap/zapcore"
16 type testCase struct {
17 name string // test case description
18 account Account // Account struct for a user that will test transaction will execute under
19 request *Transaction // transaction that will be sent by the client to the server
20 setup func() // Optional test-specific setup required for the scenario
21 teardown func() // Optional test-specific teardown for the scenario
22 mockHandler map[int]*mockClientHandler
25 func (tt *testCase) Setup(srv *Server) error {
26 if err := srv.NewUser(tt.account.Login, tt.account.Name, string(negateString([]byte(tt.account.Password))), *tt.account.Access); err != nil {
37 func (tt *testCase) Teardown(srv *Server) error {
38 if err := srv.DeleteUser(tt.account.Login); err != nil {
42 if tt.teardown != nil {
49 func NewTestLogger() *zap.SugaredLogger {
50 encoderCfg := zap.NewProductionEncoderConfig()
51 encoderCfg.TimeKey = "timestamp"
52 encoderCfg.EncodeTime = zapcore.ISO8601TimeEncoder
54 core := zapcore.NewCore(
55 zapcore.NewConsoleEncoder(encoderCfg),
56 zapcore.Lock(os.Stdout),
60 cores := []zapcore.Core{core}
61 l := zap.New(zapcore.NewTee(cores...))
62 defer func() { _ = l.Sync() }()
66 func StartTestServer() (*Server, context.Context, context.CancelFunc) {
67 ctx, cancelRoot := context.WithCancel(context.Background())
71 srv, err := NewServer("test/config/", "localhost", 0, NewTestLogger())
77 err := srv.ListenAndServe(ctx, cancelRoot)
83 return srv, ctx, cancelRoot
86 func TestHandshake(t *testing.T) {
87 mfs := MockFileStore{}
88 fh, _ := os.Open("./test/config/Agreement.txt")
89 mfs.On("Open", "/test/config/Agreement.txt").Return(fh, nil)
90 fh, _ = os.Open("./test/config/config.yaml")
91 mfs.On("Open", "/test/config/config.yaml").Return(fh, nil)
95 srv, _, cancelFunc := StartTestServer()
98 port := srv.APIListener.Addr().(*net.TCPAddr).Port
100 conn, err := net.Dial("tcp", fmt.Sprintf(":%v", port))
106 conn.Write([]byte{0x54, 0x52, 0x54, 0x50, 0x00, 0x01, 0x00, 0x00})
108 replyBuf := make([]byte, 8)
109 _, _ = conn.Read(replyBuf)
111 want := []byte{84, 82, 84, 80, 0, 0, 0, 0}
112 if bytes.Compare(replyBuf, want) != 0 {
113 t.Errorf("%q, want %q", replyBuf, want)
118 //func TestLogin(t *testing.T) {
120 // tests := []struct {
125 // name: "when login is successful",
126 // client: NewClient("guest", NewTestLogger()),
129 // for _, test := range tests {
130 // t.Run(test.name, func(t *testing.T) {
136 func TestNewUser(t *testing.T) {
137 srv, _, _ := StartTestServer()
141 // name: "a valid new account",
142 // mockHandler: func() mockClientHandler {
143 // mh := mockClientHandler{}
144 // mh.On("Handle", mock.AnythingOfType("*hotline.Client"), mock.MatchedBy(func(t *Transaction) bool {
145 // println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
147 // spew.Dump(bytes.Equal(t.Type, []byte{0x01, 0x5e}))
148 // //if !bytes.Equal(t.GetField(fieldError).Data, []byte("You are not allowed to create new accounts.")) {
151 // return bytes.Equal(t.Type, []byte{0x01, 0x5e},
154 // []Transaction{}, nil,
157 // clientHandlers[tranNewUser] = mh
160 // client: func() *Client {
161 // c := NewClient("testUser", NewTestLogger())
164 // teardown: func() {
165 // _ = srv.DeleteUser("testUser")
171 // Access: &[]byte{255, 255, 255, 255, 255, 255, 255, 255},
173 // request: NewTransaction(
175 // NewField(fieldUserLogin, []byte(NegatedUserString([]byte("testUser")))),
176 // NewField(fieldUserName, []byte("testUserName")),
177 // NewField(fieldUserPassword, []byte(NegatedUserString([]byte("testPw")))),
178 // NewField(fieldUserAccess, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}),
180 // want: &Transaction{
181 // Fields: []Field{},
185 // name: "a newUser request from a user without the required access",
186 // mockHandler: func() *mockClientHandler {
187 // mh := mockClientHandler{}
188 // mh.On("Handle", mock.AnythingOfType("*hotline.Client"), mock.MatchedBy(func(t *Transaction) bool {
189 // if !bytes.Equal(t.GetField(fieldError).Data, []byte("You are not allowed to create new accounts.")) {
192 // return bytes.Equal(t.Type, []byte{0x01, 0x5e})
194 // []Transaction{}, nil,
198 // teardown: func() {
199 // _ = srv.DeleteUser("testUser")
205 // Access: &[]byte{0, 0, 0, 0, 0, 0, 0, 0},
207 // request: NewTransaction(
209 // NewField(fieldUserLogin, []byte(NegatedUserString([]byte("testUser")))),
210 // NewField(fieldUserName, []byte("testUserName")),
211 // NewField(fieldUserPassword, []byte(NegatedUserString([]byte("testPw")))),
212 // NewField(fieldUserAccess, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}),
216 // name: "when user does not have required permission",
217 // mockHandler: func() map[int]*mockClientHandler {
218 // mockHandlers := make(map[int]*mockClientHandler)
220 // mh := mockClientHandler{}
221 // mh.On("Handle", mock.AnythingOfType("*hotline.Client"), mock.MatchedBy(func(t *Transaction) bool {
222 // return t.equal(Transaction{
223 // Type: []byte{0x01, 0x5e},
225 // ErrorCode: []byte{0, 0, 0, 1},
227 // NewField(fieldError, []byte("You are not allowed to create new accounts.")),
231 // []Transaction{}, nil,
233 // mockHandlers[tranNewUser] = &mh
235 // return mockHandlers
238 // teardown: func() {
239 // _ = srv.DeleteUser("testUser")
245 // Access: &[]byte{0, 0, 0, 0, 0, 0, 0, 0},
247 // request: NewTransaction(
249 // NewField(fieldUserLogin, []byte(NegatedUserString([]byte("testUser")))),
250 // NewField(fieldUserName, []byte("testUserName")),
251 // NewField(fieldUserPassword, []byte(NegatedUserString([]byte("testPw")))),
252 // NewField(fieldUserAccess, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}),
257 // name: "a request to create a user that already exists",
261 // teardown: func() {
262 // _ = srv.DeleteUser("testUser")
268 // Access: &[]byte{255, 255, 255, 255, 255, 255, 255, 255},
270 // request: NewTransaction(
272 // NewField(fieldUserLogin, []byte(NegatedUserString([]byte("guest")))),
273 // NewField(fieldUserName, []byte("testUserName")),
274 // NewField(fieldUserPassword, []byte(NegatedUserString([]byte("testPw")))),
275 // NewField(fieldUserAccess, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}),
277 // want: &Transaction{
279 // NewField(fieldError, []byte("Cannot create account guest because there is already an account with that login.")),
285 for _, test := range tests {
286 t.Run(test.name, func(t *testing.T) {
290 c := NewClient(test.account.Name, NewTestLogger())
291 err := c.JoinServer(fmt.Sprintf(":%v", srv.APIPort()), test.account.Login, test.account.Password)
293 t.Errorf("login failed: %v", err)
295 // end move to Setup??
297 for key, value := range test.mockHandler {
298 c.Handlers[uint16(key)] = value
301 // send test case request
302 _ = c.Send(*test.request)
304 //time.Sleep(1 * time.Second)
307 transactions, _ := readN(c.Connection, 1)
308 for _, t := range transactions {
309 _ = c.HandleTransaction(&t)
314 for _, handler := range test.mockHandler {
315 handler.AssertExpectations(t)
323 func tranAssertEqual(t *testing.T, tran1, tran2 []Transaction) bool {
324 var newT1 []Transaction
325 var newT2 []Transaction
326 for _, trans := range tran1 {
327 trans.ID = []byte{0, 0, 0, 0}
328 newT1 = append(newT1, trans)
331 for _, trans := range tran2 {
332 trans.ID = []byte{0, 0, 0, 0}
333 newT2 = append(newT2, trans)
337 return assert.Equal(t, newT1, newT2)