-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcover.html
644 lines (553 loc) · 24.9 KB
/
cover.html
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>basic: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">go-unit-test/basic/calculator.go (100.0%)</option>
<option value="file1">go-unit-test/basic/usecase/usecase.go (85.7%)</option>
<option value="file2">go-unit-test/web-api/module/handler/handler.go (50.0%)</option>
<option value="file3">go-unit-test/web-api/module/repository/repository.go (80.0%)</option>
<option value="file4">go-unit-test/web-api/module/usecase/usecase.go (66.3%)</option>
<option value="file5">go-unit-test/web-api/router/router.go (100.0%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">not covered</span>
<span class="cov8">covered</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">package basic
func Sum(a int, b int) int <span class="cov8" title="1">{
return a + b
}</span>
</pre>
<pre class="file" id="file1" style="display: none">package usecase
import (
"context"
"errors"
"go-unit-test/basic/domain"
"go-unit-test/basic/repository"
"go.mongodb.org/mongo-driver/bson"
)
type Usecase interface {
GetUser(ctx context.Context, id string) (*domain.User, error)
}
type UsecaseImpl struct {
repository repository.Repository
}
func NewUsecase(repository repository.Repository) Usecase <span class="cov8" title="1">{
return &UsecaseImpl{
repository: repository,
}
}</span>
func (usecase *UsecaseImpl) GetUser(ctx context.Context, id string) (*domain.User, error) <span class="cov8" title="1">{
user, err := usecase.repository.FindOneUser(ctx, bson.M{})
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">if user == nil </span><span class="cov8" title="1">{
return nil, errors.New("user not found")
}</span>
<span class="cov8" title="1">return user, nil</span>
}
</pre>
<pre class="file" id="file2" style="display: none">package handler
import (
"net/http"
"go-unit-test/web-api/helper"
"go-unit-test/web-api/logger"
"go-unit-test/web-api/module/model/web"
"go-unit-test/web-api/module/usecase"
"github.com/gin-gonic/gin"
"go.elastic.co/apm"
"go.elastic.co/apm/module/apmzap/v2"
)
type Handler interface {
Index(c *gin.Context)
Register(c *gin.Context)
VerifyRegister(c *gin.Context)
}
type HandlerImpl struct {
usecase usecase.Usecase
logger logger.Logger
}
func NewHandler(usecase usecase.Usecase, logger logger.Logger) Handler <span class="cov8" title="1">{
return &HandlerImpl{
usecase: usecase,
logger: logger,
}
}</span>
func (handler HandlerImpl) Index(c *gin.Context) <span class="cov0" title="0">{
span, _ := apm.StartSpan(c.Request.Context(), "Index", "handler")
defer span.End()
traceContextFields := apmzap.TraceContext(c.Request.Context())
handler.logger.GetLogger().With(traceContextFields...).Debug("handling request")
helper.RespSuccess(c, nil, "Index success")
}</span>
func (handler HandlerImpl) Register(c *gin.Context) <span class="cov8" title="1">{
span, ctx := apm.StartSpan(c.Request.Context(), "Register", "handler")
defer span.End()
traceContextFields := apmzap.TraceContext(c.Request.Context())
handler.logger.GetLogger().With(traceContextFields...).Debug("handling request")
request := &web.RegisterRequest{}
if err := c.ShouldBind(request); err != nil </span><span class="cov0" title="0">{
helper.RespError(c, helper.CustomError(http.StatusBadRequest, err.Error()))
return
}</span>
<span class="cov8" title="1">if err := helper.Validate(request); err != nil </span><span class="cov0" title="0">{
helper.RespError(c, helper.CustomError(http.StatusBadRequest, err.Error()))
return
}</span>
<span class="cov8" title="1">err := handler.usecase.Register(ctx, *request)
if err != nil </span><span class="cov0" title="0">{
helper.RespError(c, err)
return
}</span>
<span class="cov8" title="1">helper.RespSuccess(c, nil, "Register success")</span>
}
func (handler HandlerImpl) VerifyRegister(c *gin.Context) <span class="cov8" title="1">{
request := &web.VerifyRegisterRequest{}
if err := c.ShouldBind(request); err != nil </span><span class="cov0" title="0">{
helper.RespError(c, helper.CustomError(http.StatusBadRequest, err.Error()))
return
}</span>
<span class="cov8" title="1">if err := helper.Validate(request); err != nil </span><span class="cov0" title="0">{
helper.RespError(c, helper.CustomError(http.StatusBadRequest, err.Error()))
return
}</span>
<span class="cov8" title="1">response, err := handler.usecase.VerifyRegister(c.Request.Context(), *request)
if err != nil </span><span class="cov0" title="0">{
helper.RespError(c, err)
return
}</span>
<span class="cov8" title="1">helper.RespSuccess(c, response, "Register success")</span>
}
</pre>
<pre class="file" id="file3" style="display: none">package repository
import (
"context"
"go-unit-test/web-api/database"
"go-unit-test/web-api/module/model/domain"
)
type Repository interface {
InsertOneUser(ctx context.Context, document interface{}) (*string, error)
FindOneUser(ctx context.Context, filter interface{}) (*domain.User, error)
}
type RepositoryImpl struct {
mongo database.MongoDatabase
}
func NewRepository(mongo database.MongoDatabase) Repository <span class="cov8" title="1">{
return &RepositoryImpl{
mongo: mongo,
}
}</span>
func (repository *RepositoryImpl) InsertOneUser(ctx context.Context, document interface{}) (*string, error) <span class="cov8" title="1">{
insertedId, err := repository.mongo.InsertOne(ctx, database.InsertOne{
CollectionName: "users",
Document: document,
})
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">return insertedId, nil</span>
}
func (repository *RepositoryImpl) FindOneUser(ctx context.Context, filter interface{}) (*domain.User, error) <span class="cov8" title="1">{
var result *domain.User
err := repository.mongo.FindOne(ctx, database.FindOne{
CollectionName: "users",
Filter: filter,
Result: &result,
})
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">return result, nil</span>
}
</pre>
<pre class="file" id="file4" style="display: none">package usecase
import (
"context"
"encoding/json"
"fmt"
"net/http"
"regexp"
"strings"
"time"
"go-unit-test/web-api/database"
"go-unit-test/web-api/helper"
"go-unit-test/web-api/jwt"
"go-unit-test/web-api/kafka"
"go-unit-test/web-api/logger"
"go-unit-test/web-api/module/model/domain"
"go-unit-test/web-api/module/model/web"
"go-unit-test/web-api/module/repository"
"github.com/go-redis/redis/v8"
"go.mongodb.org/mongo-driver/bson"
"go.uber.org/zap"
"golang.org/x/crypto/bcrypt"
)
type Usecase interface {
Register(ctx context.Context, request web.RegisterRequest) error
VerifyRegister(ctx context.Context, request web.VerifyRegisterRequest) (*web.VerifyRegisterResponse, error)
}
type UsecaseImpl struct {
repository repository.Repository
jwtAuth jwt.JWT
redis database.RedisClient
kafkaProducer kafka.KafkaProducer
logger logger.Logger
}
func NewUsecase(repository repository.Repository, jwtAuth jwt.JWT, redis database.RedisClient, kafkaProducer kafka.KafkaProducer, logger logger.Logger) Usecase <span class="cov8" title="1">{
return &UsecaseImpl{
repository: repository,
jwtAuth: jwtAuth,
redis: redis,
kafkaProducer: kafkaProducer,
logger: logger,
}
}</span>
func (service UsecaseImpl) Register(ctx context.Context, request web.RegisterRequest) error <span class="cov8" title="1">{
context := "service-Register"
marshaledRequest, err := json.Marshal(request)
if err != nil </span><span class="cov0" title="0">{
service.logger.GetLogger().Error("Marshal request fail", zap.Error(err), zap.String("context", context))
return helper.CustomError(http.StatusInternalServerError, "Internal server error")
}</span>
// Preprocecss username & mobile number
<span class="cov8" title="1">request.Username = strings.ToLower(request.Username)
mobileNumberRegex := regexp.MustCompile(`^(\+628|628|08|8)`)
if !mobileNumberRegex.MatchString(request.MobileNumber) </span><span class="cov8" title="1">{
service.logger.GetLogger().Warn("Wrong format mobile number", zap.String("context", context), zap.ByteString("request", marshaledRequest))
return helper.CustomError(http.StatusBadRequest, "Wrong format mobile number")
}</span>
<span class="cov8" title="1">request.MobileNumber = mobileNumberRegex.ReplaceAllString(request.MobileNumber, "+628")
// Check username is already registered or not yet
user, err := service.repository.FindOneUser(ctx, bson.M{
"username": request.Username,
})
if err != nil </span><span class="cov0" title="0">{
service.logger.GetLogger().Error("Find one user fail", zap.Error(err), zap.String("context", context), zap.ByteString("request", marshaledRequest))
return helper.CustomError(http.StatusInternalServerError, "Internal server error")
}</span>
<span class="cov8" title="1">if user != nil </span><span class="cov8" title="1">{
service.logger.GetLogger().Warn("Username already registered", zap.String("context", context), zap.ByteString("request", marshaledRequest))
return helper.CustomError(http.StatusUnprocessableEntity, "Username already registered")
}</span>
// Check username is already registered or not yet
<span class="cov8" title="1">user, err = service.repository.FindOneUser(ctx, bson.M{
"mobileNumber": request.MobileNumber,
})
if err != nil </span><span class="cov0" title="0">{
service.logger.GetLogger().Error("Find one user 2 fail", zap.Error(err), zap.String("context", context), zap.ByteString("request", marshaledRequest))
return helper.CustomError(http.StatusInternalServerError, "Internal server error")
}</span>
<span class="cov8" title="1">if user != nil </span><span class="cov8" title="1">{
service.logger.GetLogger().Warn("Mobile number already registered", zap.String("context", context), zap.ByteString("request", marshaledRequest))
return helper.CustomError(http.StatusUnprocessableEntity, "Mobile number already registered")
}</span>
// Generate hashed password
<span class="cov8" title="1">hashedPassword, err := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost)
if err != nil </span><span class="cov0" title="0">{
service.logger.GetLogger().Error("Generate hashed password fail", zap.Error(err), zap.String("context", context), zap.ByteString("request", marshaledRequest))
return helper.CustomError(http.StatusInternalServerError, "Internal server error")
}</span>
// Generate otp 6 digit
<span class="cov8" title="1">otp, err := helper.GenerateOTP(6)
if err != nil </span><span class="cov0" title="0">{
service.logger.GetLogger().Error("Generate otp fail", zap.Error(err), zap.String("context", context), zap.ByteString("request", marshaledRequest))
return helper.CustomError(http.StatusInternalServerError, "Internal server error")
}</span>
// Generate user json for redis
<span class="cov8" title="1">userRedis := domain.UserRedis{
Username: request.Username,
Password: string(hashedPassword),
Name: request.Name,
Otp: *otp,
MobileNumber: request.MobileNumber,
}
userRedisJson, err := json.Marshal(userRedis)
if err != nil </span><span class="cov0" title="0">{
service.logger.GetLogger().Error("Marshal redis fail", zap.Error(err), zap.String("context", context), zap.ByteString("request", marshaledRequest))
return helper.CustomError(http.StatusInternalServerError, "Internal server error")
}</span>
// Insert user json to redis
<span class="cov8" title="1">if err = service.redis.Set(
ctx,
fmt.Sprintf("REGISTER:%s", request.Username),
string(userRedisJson),
time.Minute*10,
).Err(); err != nil </span><span class="cov0" title="0">{
service.logger.GetLogger().Error("Set redis fail", zap.Error(err), zap.String("context", context), zap.ByteString("request", marshaledRequest))
return helper.CustomError(http.StatusInternalServerError, "Internal server error")
}</span>
// Generate user json for kafka
<span class="cov8" title="1">userKafka := domain.RegisterOtpKafka{
Name: request.Name,
Otp: *otp,
MobileNumber: request.MobileNumber,
}
userKafkaJson, err := json.Marshal(userKafka)
if err != nil </span><span class="cov0" title="0">{
service.logger.GetLogger().Error("Marshal kafka fail", zap.Error(err), zap.String("context", context), zap.ByteString("request", marshaledRequest))
return helper.CustomError(http.StatusInternalServerError, "Internal server error")
}</span>
// Produce user json to kafka
<span class="cov8" title="1">err = service.kafkaProducer.SendMessage("REGISTER-OTP", string(userKafkaJson))
if err != nil </span><span class="cov0" title="0">{
service.logger.GetLogger().Error("Send message kafka fail", zap.Error(err), zap.String("context", context), zap.ByteString("request", marshaledRequest))
return helper.CustomError(http.StatusInternalServerError, "Internal server error")
}</span>
<span class="cov8" title="1">service.logger.GetLogger().Info(
"Register success",
zap.String("context", context),
zap.ByteString("request", marshaledRequest),
)
return nil</span>
}
func (service UsecaseImpl) VerifyRegister(ctx context.Context, request web.VerifyRegisterRequest) (*web.VerifyRegisterResponse, error) <span class="cov8" title="1">{
context := "service-VerifyRegister"
marshaledRequest, err := json.Marshal(request)
if err != nil </span><span class="cov0" title="0">{
service.logger.GetLogger().Error(
"Marshal request fail",
zap.String("context", context),
zap.Error(err),
)
return nil, helper.CustomError(http.StatusInternalServerError, "Internal server error")
}</span>
<span class="cov8" title="1">request.Username = strings.ToLower(request.Username)
// Check username is already registered or not yet
user, err := service.repository.FindOneUser(ctx, bson.M{
"username": request.Username,
})
if err != nil </span><span class="cov0" title="0">{
service.logger.GetLogger().Error(
"Find one user fail",
zap.String("context", context),
zap.Error(err),
zap.ByteString("request", marshaledRequest),
)
return nil, helper.CustomError(http.StatusInternalServerError, "Internal server error")
}</span>
<span class="cov8" title="1">if user != nil </span><span class="cov8" title="1">{
service.logger.GetLogger().Warn(
"Username already registered",
zap.String("context", context),
zap.ByteString("request", marshaledRequest),
)
return nil, helper.CustomError(http.StatusUnprocessableEntity, "Username already registered")
}</span>
// Get user from redis
<span class="cov8" title="1">userRedisJson, err := service.redis.Get(ctx, fmt.Sprintf("REGISTER:%s", request.Username)).Result()
if err != nil </span><span class="cov8" title="1">{
if err == redis.Nil </span><span class="cov8" title="1">{
service.logger.GetLogger().Warn(
"OTP has expired",
zap.String("context", context),
zap.ByteString("request", marshaledRequest),
)
return nil, helper.CustomError(http.StatusUnauthorized, "OTP has expired")
}</span>
<span class="cov0" title="0">service.logger.GetLogger().Error(
"Get redis fail",
zap.String("context", context),
zap.Error(err),
zap.ByteString("request", marshaledRequest),
)
return nil, helper.CustomError(http.StatusInternalServerError, "Internal server error")</span>
}
// Parse user json to user object
<span class="cov8" title="1">var userRedis domain.UserRedis
err = json.Unmarshal([]byte(userRedisJson), &userRedis)
if err != nil </span><span class="cov0" title="0">{
service.logger.GetLogger().Error(
"Unmarshal redis fail",
zap.String("context", context),
zap.Error(err),
zap.ByteString("request", marshaledRequest),
)
return nil, helper.CustomError(http.StatusInternalServerError, "Internal server error")
}</span>
// Validate otp
<span class="cov8" title="1">if userRedis.Otp != request.Otp </span><span class="cov8" title="1">{
service.logger.GetLogger().Warn(
"Invalid OTP",
zap.String("context", context),
zap.ByteString("request", marshaledRequest),
)
return nil, helper.CustomError(http.StatusUnauthorized, "Invalid OTP")
}</span>
// Insert user to mongodb
<span class="cov8" title="1">insertUser := domain.InsertUser{
Username: userRedis.Username,
Password: userRedis.Password,
Name: userRedis.Name,
MobileNumber: userRedis.MobileNumber,
}
insertedId, err := service.repository.InsertOneUser(ctx, insertUser)
if err != nil </span><span class="cov0" title="0">{
service.logger.GetLogger().Error(
"Insert one user fail",
zap.String("context", context),
zap.Error(err),
zap.ByteString("request", marshaledRequest),
)
return nil, helper.CustomError(http.StatusInternalServerError, "Internal server error")
}</span>
// Delete user in redis
<span class="cov8" title="1">err = service.redis.Del(ctx, fmt.Sprintf("REGISTER:%s", request.Username)).Err()
if err != nil </span><span class="cov0" title="0">{
service.logger.GetLogger().Error(
"Delete redis fail",
zap.String("context", context),
zap.Error(err),
zap.ByteString("request", marshaledRequest),
)
return nil, helper.CustomError(http.StatusInternalServerError, "Internal server error")
}</span>
// Generate token
<span class="cov8" title="1">token, err := service.jwtAuth.GenerateToken(jwt.Payload{
Id: *insertedId,
})
if err != nil </span><span class="cov0" title="0">{
service.logger.GetLogger().Error(
"Generate token fail",
zap.String("context", context),
zap.Error(err),
zap.ByteString("request", marshaledRequest),
)
return nil, helper.CustomError(http.StatusInternalServerError, "Internal server error")
}</span>
<span class="cov8" title="1">response := web.VerifyRegisterResponse{
Token: *token,
}
marshaledResponse, err := json.Marshal(response)
if err != nil </span><span class="cov0" title="0">{
service.logger.GetLogger().Error(
"Marshal response fail",
zap.String("context", context),
zap.Error(err),
zap.ByteString("request", marshaledRequest),
)
return nil, helper.CustomError(http.StatusInternalServerError, "Internal server error")
}</span>
<span class="cov8" title="1">service.logger.GetLogger().Info(
"Verify register success",
zap.String("context", context),
zap.ByteString("request", marshaledRequest),
zap.ByteString("response", marshaledResponse),
)
return &response, nil</span>
}
</pre>
<pre class="file" id="file5" style="display: none">package router
import (
"go-unit-test/web-api/middleware"
"go-unit-test/web-api/module/handler"
"github.com/gin-gonic/gin"
"go.elastic.co/apm/module/apmgin"
)
type Router interface {
GetGinEngine() *gin.Engine
}
type RouterImpl struct {
ginEngine *gin.Engine
auth middleware.Auth
}
func NewRouter(handler handler.Handler, auth middleware.Auth) Router <span class="cov8" title="1">{
router := gin.New()
router.Use(apmgin.Middleware(router))
userRouter := router.Group("/user")
userRouter.Use(apmgin.Middleware(router))
userRouter.GET("/", handler.Index)
userRouter.POST("/v1/register", handler.Register)
userRouter.POST("/v1/register/verify", handler.VerifyRegister)
return &RouterImpl{
ginEngine: router,
}
}</span>
func (router RouterImpl) GetGinEngine() *gin.Engine <span class="cov8" title="1">{
return router.ginEngine
}</span>
</pre>
</div>
</body>
<script>
(function() {
var files = document.getElementById('files');
var visible;
files.addEventListener('change', onChange, false);
function select(part) {
if (visible)
visible.style.display = 'none';
visible = document.getElementById(part);
if (!visible)
return;
files.value = part;
visible.style.display = 'block';
location.hash = part;
}
function onChange() {
select(files.value);
window.scrollTo(0, 0);
}
if (location.hash != "") {
select(location.hash.substr(1));
}
if (!visible) {
select("file0");
}
})();
</script>
</html>