/
scene.go
1532 lines (1393 loc) · 41.6 KB
/
scene.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
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2021 Terminus, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package autotestv2
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/http/cookiejar"
"regexp"
"strconv"
"strings"
"time"
"golang.org/x/net/publicsuffix"
"github.com/jinzhu/gorm"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
cmspb "github.com/erda-project/erda-proto-go/core/pipeline/cms/pb"
"github.com/erda-project/erda/apistructs"
"github.com/erda-project/erda/modules/dop/dao"
"github.com/erda-project/erda/modules/dop/services/apierrors"
"github.com/erda-project/erda/modules/dop/services/autotest"
"github.com/erda-project/erda/modules/dop/utils"
"github.com/erda-project/erda/pkg/apitestsv2"
"github.com/erda-project/erda/pkg/expression"
"github.com/erda-project/erda/pkg/parser/pipelineyml"
"github.com/erda-project/erda/pkg/parser/pipelineyml/pexpr"
"github.com/erda-project/erda/pkg/strutil"
)
const (
maxSize int = 500
spaceMaxSize int = 50000
nameMaxLength int = 50
descMaxLength int = 1000
)
// CreateAutotestScene 创建场景
func (svc *Service) CreateAutotestScene(req apistructs.AutotestSceneRequest) (uint64, error) {
set, err := svc.GetSceneSet(req.SetID)
if err != nil {
return 0, err
}
sp, err := svc.GetSpace(set.SpaceID)
if err != nil {
return 0, err
}
if !sp.IsOpen() {
return 0, fmt.Errorf("the space is locked")
}
req.SpaceID = sp.ID
// 鉴权
if !req.IdentityInfo.IsInternalClient() {
access, err := svc.bdl.CheckPermission(&apistructs.PermissionCheckRequest{
UserID: req.IdentityInfo.UserID,
Scope: apistructs.ProjectScope,
ScopeID: uint64(sp.ProjectID),
Resource: apistructs.AutotestSceneResource,
Action: apistructs.CreateAction,
})
if err != nil {
return 0, err
}
if !access.Access {
return 0, apierrors.ErrUpdateAutoTestScene.AccessDenied()
}
}
if err = strutil.Validate(req.Name, strutil.MaxRuneCountValidator(nameMaxLength)); err != nil {
return 0, err
}
if err = strutil.Validate(req.Description, strutil.MaxRuneCountValidator(descMaxLength)); err != nil {
return 0, err
}
if ok, _ := regexp.MatchString("^[a-zA-Z\u4e00-\u9fa50-9_-]*$", req.Name); !ok {
return 0, apierrors.ErrCreateAutoTestScene.InvalidState("只可输入中文、英文、数字、中划线或下划线")
}
if ok := svc.checkSceneSetSameNameScene(req.SetID, req.Name, 0); !ok {
return 0, apierrors.ErrCreateAutoTestScene.AlreadyExists()
}
// check whether the depth of the reference scene set is greater than 10
checkScene := dao.AutoTestScene{
SpaceID: req.SpaceID,
SetID: req.SetID,
RefSetID: req.RefSetID,
Name: req.Name,
}
if err := svc.checkCycle(checkScene, nil, nil, nil); err != nil {
return 0, apierrors.ErrCreateAutoTestScene.InternalError(err)
}
// 一个场景集下500个场景
total, scenes, err := svc.ListAutotestScene(req)
if err != nil {
return 0, err
}
if int(total) >= maxSize {
return 0, fmt.Errorf("一个场景集合下,限制500个测试场景")
}
// 一个测试空间下50000个场景
total, err = svc.db.CountSceneBySpaceID(req.SpaceID)
if err != nil {
return 0, err
}
if int(total) >= spaceMaxSize {
return 0, fmt.Errorf("一个空间下,限制五万个场景")
}
var preID uint64
if req.PreID > 0 {
preID = req.PreID
} else {
if len(scenes) > 0 {
preID = scenes[len(scenes)-1].ID
} else {
preID = 0
}
}
scene := &dao.AutoTestScene{
Name: req.Name,
Description: req.Description,
SpaceID: req.SpaceID,
SetID: req.SetID,
PreID: preID,
CreatorID: req.UserID,
Status: apistructs.DefaultSceneStatus,
RefSetID: req.RefSetID,
GroupID: req.SceneGroupID,
}
if scene.RefSetID > 0 && req.Policy != "" {
scene.Policy = req.Policy
}
if err := svc.db.CreateAutotestScene(scene); err != nil {
return 0, err
}
return scene.ID, nil
}
// check whether the nesting depth of the scene reference scene set is greater than a certain value
func (svc *Service) checkCycle(scene dao.AutoTestScene, allNodes []uint64, allNodesMap map[uint64]bool, tx *gorm.DB) error {
// Initialization data, add begin data
if allNodes == nil && allNodesMap == nil {
allNodes = append(allNodes, scene.SetID)
allNodesMap = map[uint64]bool{
scene.SetID: true,
}
}
if scene.RefSetID <= 0 {
return nil
}
// checkCycle
if _, ok := allNodesMap[scene.RefSetID]; !ok {
allNodesMap[scene.RefSetID] = true
allNodes = append(allNodes, scene.RefSetID)
} else {
return fmt.Errorf("error scene reference scene set cycle error, scene reference path : %v", allNodes)
}
_, refScenes, err := svc.db.ListAutotestSceneTx(apistructs.AutotestSceneRequest{SetID: scene.RefSetID}, tx)
if err != nil {
return err
}
// depth first, meet the bifurcation record backtracking
for _, refScene := range refScenes {
if refScene.RefSetID <= 0 {
continue
}
err := svc.checkCycle(refScene, allNodes, allNodesMap, tx)
if err != nil {
return err
}
if len(allNodes) > 0 {
allNodes = allNodes[:len(allNodes)-1]
}
delete(allNodesMap, refScene.RefSetID)
}
return nil
}
// UpdateAutotestScene 更新场景
func (svc *Service) UpdateAutotestScene(req apistructs.AutotestSceneSceneUpdateRequest) (uint64, error) {
sc, err := svc.GetAutotestScene(apistructs.AutotestSceneRequest{SceneID: req.SceneID})
if err != nil {
return 0, err
}
req.SetID = sc.SetID
sp, err := svc.GetSpace(sc.SpaceID)
if err != nil {
return 0, err
}
if !sp.IsOpen() {
return 0, fmt.Errorf("the space is locked")
}
// check permission
if !req.IdentityInfo.IsInternalClient() {
access, err := svc.bdl.CheckPermission(&apistructs.PermissionCheckRequest{
UserID: req.IdentityInfo.UserID,
Scope: apistructs.ProjectScope,
ScopeID: uint64(sp.ProjectID),
Resource: apistructs.AutotestSceneResource,
Action: apistructs.UpdateAction,
})
if err != nil {
return 0, err
}
if !access.Access {
return 0, apierrors.ErrUpdateAutoTestScene.AccessDenied()
}
}
if err := strutil.Validate(req.Name, strutil.MaxRuneCountValidator(nameMaxLength)); err != nil {
return 0, err
}
if err := strutil.Validate(req.Description, strutil.MaxRuneCountValidator(descMaxLength)); err != nil {
return 0, err
}
if ok, _ := regexp.MatchString("^[a-zA-Z\u4e00-\u9fa50-9_-]*$", req.Name); !ok {
return 0, apierrors.ErrUpdateAutoTestScene.InvalidState("只可输入中文、英文、数字、中划线或下划线")
}
scene, err := svc.db.GetAutotestScene(req.SceneID)
if err != nil {
return 0, err
}
if ok := svc.checkSceneSetSameNameScene(req.SetID, req.Name, scene.ID); !ok {
return 0, apierrors.ErrUpdateAutoTestScene.AlreadyExists()
}
if req.Name != "" {
scene.Name = req.Name
}
if req.Status != "" {
scene.Status = req.Status
}
scene.Description = req.Description
if !req.IsStatus {
scene.UpdaterID = req.IdentityInfo.UserID
}
if scene.RefSetID > 0 && req.Policy != "" {
scene.Policy = req.Policy
}
if err = svc.db.UpdateAutotestScene(scene); err != nil {
return 0, err
}
go svc.db.AfterUpdateAutoTestSpaceElements(sc.SpaceID)
return scene.ID, nil
}
// MoveAutotestScene 移动场景
func (svc *Service) MoveAutotestScene(req apistructs.AutotestSceneRequest) (uint64, error) {
var preID uint64
// 移动到另一scene set
if req.GroupID > 0 {
if ok := svc.checkSceneSetSameNameScene(uint64(req.GroupID), req.Name, req.ID); !ok {
return 0, apierrors.ErrMoveAutoTestScene.AlreadyExists()
}
_, scenes, err := svc.ListAutotestScene(apistructs.AutotestSceneRequest{SetID: uint64(req.GroupID)})
if err != nil {
return 0, err
}
preID = 0
if len(scenes) > 0 {
preID = scenes[len(scenes)-1].ID
}
if preID == req.ID {
return 0, nil
}
} else {
setID, id, ok, err := svc.db.GetAutoTestScenePreByPosition(req)
if err != nil {
return 0, err
}
if ok == true {
return req.ID, nil
}
preID = id
req.GroupID = int64(setID)
if ok := svc.checkSceneSetSameNameScene(uint64(req.GroupID), req.Name, req.ID); !ok {
return 0, apierrors.ErrMoveAutoTestScene.AlreadyExists()
}
}
err := svc.db.Transaction(func(tx *gorm.DB) error {
err := svc.db.MoveAutoTestScene(req.ID, preID, uint64(req.GroupID), tx)
if err != nil {
return err
}
scene, err := svc.db.GetAutotestSceneTx(req.ID, tx)
if err != nil {
return err
}
// scene reference scene set is moved
if scene.RefSetID > 0 && req.GroupID > 0 {
checkScene := dao.AutoTestScene{
SpaceID: scene.SpaceID,
SetID: scene.SetID,
RefSetID: scene.RefSetID,
}
err := svc.checkCycle(checkScene, nil, nil, tx)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return 0, err
}
return req.ID, nil
}
// MoveAutotestSceneV2 Move scene between scene set, include the group drag
func (svc *Service) MoveAutotestSceneV2(req apistructs.AutotestSceneMoveRequest) error {
sc, err := svc.GetAutotestScene(apistructs.AutotestSceneRequest{SceneID: req.FirstID})
if err != nil {
return err
}
sp, err := svc.GetSpace(sc.SpaceID)
if err != nil {
return err
}
if !sp.IsOpen() {
return fmt.Errorf("the space is locked")
}
// check the permission
if !req.IdentityInfo.IsInternalClient() {
access, err := svc.bdl.CheckPermission(&apistructs.PermissionCheckRequest{
UserID: req.IdentityInfo.UserID,
Scope: apistructs.ProjectScope,
ScopeID: uint64(sp.ProjectID),
Resource: apistructs.AutotestSceneResource,
Action: apistructs.UpdateAction,
})
if err != nil {
return err
}
if !access.Access {
return apierrors.ErrMoveAutoTestScene.AccessDenied()
}
}
return svc.db.MoveAutoTestSceneV2(req)
}
func (svc *Service) checkSceneSetSameNameScene(sceneSetID uint64, sceneName string, sceneID uint64) bool {
dbScenes, err := svc.db.FindSceneBySetAndName(sceneSetID, sceneName)
if err != nil {
return false
}
var checkExistScenes []dao.AutoTestScene
for _, rangeScene := range dbScenes {
// mysql not case sensitive
if rangeScene.Name != sceneName {
continue
}
if rangeScene.ID == sceneID {
continue
}
checkExistScenes = append(checkExistScenes, rangeScene)
}
if len(checkExistScenes) >= 1 {
return false
}
return true
}
// GetAutotestScene 获取场景
func (svc *Service) GetAutotestScene(req apistructs.AutotestSceneRequest) (*apistructs.AutoTestScene, error) {
sc, err := svc.db.GetAutotestScene(req.SceneID)
if err != nil {
return nil, err
}
scene := sc.Convert()
return &scene, nil
}
// ListAutotestScene 获取场景列表
func (svc *Service) ListAutotestScene(req apistructs.AutotestSceneRequest) (uint64, []apistructs.AutoTestScene, error) {
if req.PageNo == 0 {
req.PageNo = 1
}
if req.PageSize == 0 {
req.PageSize = 500
}
total, scene, err := svc.db.ListAutotestScene(req)
if err != nil {
return 0, nil, err
}
list := getList(scene, req.PageNo, req.PageSize)
var sceneIDs []uint64
// 通过pre_id获取顺序列表
sceneMap := make(map[uint64]int)
for i, v := range list {
sceneMap[v.ID] = i
sceneIDs = append(sceneIDs, v.ID)
}
stepIDs, err := svc.db.GetAutoTestSceneStepCount(sceneIDs)
if err != nil {
return 0, nil, err
}
for _, v := range stepIDs {
list[sceneMap[v.SceneID]].StepCount++
}
return total, list, nil
}
// ListAutotestScenes 批量获取场景列表
func (svc *Service) ListAutotestScenes(setIDs []uint64) (map[uint64][]apistructs.AutoTestScene, error) {
scene, err := svc.db.ListAutotestScenes(setIDs)
if err != nil {
return nil, err
}
var sceneIDs []uint64
for _, each := range scene {
sceneIDs = append(sceneIDs, each.ID)
}
inputs, err := svc.ListAutoTestSceneInputByScenes(sceneIDs)
if err != nil {
return nil, err
}
outputs, err := svc.ListAutoTestSceneOutputByScenes(sceneIDs)
if err != nil {
return nil, err
}
lists := map[uint64][]apistructs.AutoTestScene{}
for _, each := range scene {
var inputsList []apistructs.AutoTestSceneInput
for inputsNo := 0; inputsNo < len(inputs); inputsNo++ {
if each.ID == inputs[inputsNo].SceneID {
inputsList = append(inputsList, inputs[inputsNo])
}
}
var outputList []apistructs.AutoTestSceneOutput
for outputNo := 0; outputNo < len(outputs); outputNo++ {
if each.ID == outputs[outputNo].SceneID {
outputList = append(outputList, outputs[outputNo])
}
}
lists[each.SetID] = append(lists[each.SetID], apistructs.AutoTestScene{
AutoTestSceneParams: apistructs.AutoTestSceneParams{
ID: each.ID,
SpaceID: each.SpaceID,
CreatorID: each.CreatorID,
UpdaterID: each.UpdaterID,
},
Name: each.Name,
Description: each.Description,
PreID: each.PreID,
SetID: each.SetID,
CreateAt: &each.CreatedAt,
UpdateAt: &each.UpdatedAt,
Status: each.Status,
Inputs: inputsList,
Output: outputList,
RefSetID: each.RefSetID,
GroupID: each.GroupID,
Policy: each.Policy,
})
}
return lists, nil
}
func (svc *Service) IsExistSceneSetName(spaceID uint64, sceneSetName string) bool {
sceneSets, err := svc.db.SceneSetsBySpaceID(spaceID)
if err != nil {
return false
}
for _, set := range sceneSets {
if set.Name == sceneSetName {
return true
}
}
return false
}
// CutAutotestScene 移除场景
func (svc *Service) CutAutotestScene(sc *dao.AutoTestScene) error {
next, err := svc.db.GetAutotestSceneByPreID(sc.ID)
if err != nil {
if !gorm.IsRecordNotFoundError(err) {
return err
}
next = nil
}
if next != nil {
next.PreID = sc.PreID
}
return svc.db.UpdateAutotestScene(next)
}
// DeleteAutotestScene 删除场景
func (svc *Service) DeleteAutotestScene(id uint64, identityInfo apistructs.IdentityInfo) error {
sc, err := svc.GetAutotestScene(apistructs.AutotestSceneRequest{SceneID: id})
if err != nil {
return err
}
sp, err := svc.GetSpace(sc.SpaceID)
if err != nil {
return err
}
if !sp.IsOpen() {
return fmt.Errorf("the space is locked")
}
// check permission
if !identityInfo.IsInternalClient() {
access, err := svc.bdl.CheckPermission(&apistructs.PermissionCheckRequest{
UserID: identityInfo.UserID,
Scope: apistructs.ProjectScope,
ScopeID: uint64(sp.ProjectID),
Resource: apistructs.AutotestSceneResource,
Action: apistructs.UpdateAction,
})
if err != nil {
return err
}
if !access.Access {
return apierrors.ErrDeleteAutoTestScene.AccessDenied()
}
}
err = svc.db.DeleteAutoTestScene(id)
if err == nil {
go svc.db.AfterUpdateAutoTestSpaceElements(sc.SpaceID)
}
return err
}
// UpdateAutotestSceneUpdater 更新场景更新人
func (svc *Service) UpdateAutotestSceneUpdater(sceneID uint64, userID string) error {
return svc.db.UpdateAutotestSceneUpdater(sceneID, userID)
}
// UpdateAutotestSceneUpdateTime 更新场景更新时间
func (svc *Service) UpdateAutotestSceneUpdateTime(sceneID uint64) error {
return svc.db.UpdateAutotestSceneUpdateAt(sceneID, time.Now())
}
func (svc *Service) ExecuteDiceAutotestScene(req apistructs.AutotestExecuteSceneRequest) (*apistructs.PipelineDTO, error) {
var autotestSceneRequest apistructs.AutotestSceneRequest
autotestSceneRequest.SceneID = req.AutoTestScene.ID
scene, err := svc.GetAutotestScene(autotestSceneRequest)
if err != nil {
return nil, err
}
sceneInputs, err := svc.ListAutoTestSceneInput(scene.ID)
if err != nil {
return nil, err
}
yml, err := svc.SceneToYml(scene.ID, apistructs.SnippetConfig{})
if err != nil {
return nil, err
}
var params []apistructs.PipelineRunParam
for _, input := range sceneInputs {
// replace mock temp before create pipeline
// and so steps can use the same mock temp
replacedTemp := expression.ReplaceRandomParams(input.Temp)
params = append(params, apistructs.PipelineRunParam{
Name: input.Name,
Value: replacedTemp,
})
}
var reqPipeline = apistructs.PipelineCreateRequestV2{
PipelineYmlName: strconv.Itoa(int(scene.ID)),
PipelineSource: apistructs.PipelineSourceAutoTest,
AutoRun: true,
ForceRun: true,
ClusterName: req.ClusterName,
PipelineYml: yml,
Labels: req.Labels,
RunParams: params,
IdentityInfo: req.IdentityInfo,
}
if req.ConfigManageNamespaces != "" {
reqPipeline.ConfigManageNamespaces = append(reqPipeline.ConfigManageNamespaces, req.ConfigManageNamespaces)
}
if reqPipeline.ClusterName == "" {
testClusterName, err := svc.GetTestClusterNameBySpaceID(scene.SpaceID)
if err != nil {
return nil, err
}
reqPipeline.ClusterName = testClusterName
}
pipelineDTO, err := svc.bdl.CreatePipeline(&reqPipeline)
if err != nil {
return nil, err
}
return pipelineDTO, nil
}
func (svc *Service) ExecuteDiceAutotestSceneStep(req apistructs.AutotestExecuteSceneStepRequest) (*apistructs.AutotestExecuteSceneStepRespData, error) {
step, err := svc.db.GetAutoTestSceneStep(req.SceneStepID)
if err != nil {
return nil, err
}
if step.Type != apistructs.StepTypeAPI {
return nil, fmt.Errorf("only supports api type execution")
}
if step.Value == "" {
return nil, fmt.Errorf("no api is referenced")
}
var pipelineCmsGetConfigsRequest cmspb.CmsNsConfigsGetRequest
pipelineCmsGetConfigsRequest.PipelineSource = apistructs.PipelineSourceAutoTest.String()
pipelineCmsGetConfigsRequest.GlobalDecrypt = true
pipelineCmsGetConfigsRequest.Ns = req.ConfigManageNamespaces
configs, _ := svc.cms.GetCmsNsConfigs(utils.WithInternalClientContext(context.Background()), &pipelineCmsGetConfigsRequest)
caseParams := make(map[string]*apistructs.CaseParams)
apiTestEnvData := &apistructs.APITestEnvData{}
for _, conf := range configs.Data {
switch conf.Key {
case autotest.CmsCfgKeyAPIGlobalConfig:
var apiConfig apistructs.AutoTestAPIConfig
if err := json.Unmarshal([]byte(conf.Value), &apiConfig); err != nil {
return nil, fmt.Errorf("failed to unmarshal apiConfig, err: %v", err)
}
apiTestEnvData.Domain = apiConfig.Domain
apiTestEnvData.Header = apiConfig.Header
apiTestEnvData.Global = make(map[string]*apistructs.APITestEnvVariable)
for name, item := range apiConfig.Global {
apiTestEnvData.Global[name] = &apistructs.APITestEnvVariable{
Value: item.Value,
Type: item.Type,
}
caseParams[name] = &apistructs.CaseParams{
Key: name,
Type: item.Type,
Value: item.Value,
}
}
}
}
var jsonMap = map[string]interface{}{}
err = json.Unmarshal([]byte(step.Value), &jsonMap)
if err != nil {
return nil, err
}
sceneInputs, err := svc.ListAutoTestSceneInput(step.SceneID)
if err != nil {
return nil, err
}
specJson, err := json.Marshal(jsonMap["apiSpec"])
if err != nil {
return nil, err
}
var apiTestStr = string(specJson)
for _, param := range sceneInputs {
param.Temp = convertJsonParam(param.Temp)
apiTestStr = strings.ReplaceAll(apiTestStr, expression.LeftPlaceholder+" "+expression.Params+"."+param.Name+" "+expression.RightPlaceholder, expression.ReplaceRandomParams(param.Temp))
apiTestStr = strings.ReplaceAll(apiTestStr, expression.OldLeftPlaceholder+expression.Params+"."+param.Name+expression.OldRightPlaceholder, expression.ReplaceRandomParams(param.Temp))
}
apiTestStr = svc.renderPreSceneStepsOutput(step.SceneID, apiTestStr)
for _, conf := range configs.Data {
switch conf.Key {
case autotest.CmsCfgKeyAPIGlobalConfig:
var apiConfig apistructs.AutoTestAPIConfig
if err := json.Unmarshal([]byte(conf.Value), &apiConfig); err != nil {
return nil, fmt.Errorf("failed to unmarshal apiConfig, err: %v", err)
}
for _, item := range apiConfig.Global {
item.Value = convertJsonParam(item.Value)
apiTestStr = strings.ReplaceAll(apiTestStr, expression.LeftPlaceholder+" "+expression.Configs+"."+apistructs.PipelineSourceAutoTest.String()+"."+item.Name+" "+expression.RightPlaceholder, expression.ReplaceRandomParams(item.Value))
}
}
}
apiTestStr = expression.ReplaceRandomParams(apiTestStr)
var apiInfoV2 apistructs.APIInfoV2
err = json.Unmarshal([]byte(apiTestStr), &apiInfoV2)
if err != nil {
return nil, err
}
apiTest := apitestsv2.New(&apistructs.APIInfo{
ID: apiInfoV2.ID,
Name: apiInfoV2.Name,
URL: apiInfoV2.URL,
Method: apiInfoV2.Method,
Headers: apiInfoV2.Headers,
Params: apiInfoV2.Params,
Body: apiInfoV2.Body,
OutParams: apiInfoV2.OutParams,
Asserts: [][]apistructs.APIAssert{apiInfoV2.Asserts},
})
var respData apistructs.AutotestExecuteSceneStepRespData
cookieJar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
if err != nil {
return nil, err
}
hc := http.Client{Jar: cookieJar}
apiReq, apiResp, err := apiTest.Invoke(&hc, apiTestEnvData, caseParams)
if err != nil {
// 单个 API 执行失败,不返回失败,继续执行下一个
logrus.Warningf("invoke api error, apiInfo:%+v, (%+v)", apiTest.API, err)
respData.Resp = &apistructs.APIResp{
BodyStr: err.Error(),
}
respData.Info = apiReq
respData.Asserts = &apistructs.APITestsAssertResult{
Success: false,
Result: []*apistructs.APITestsAssertData{},
}
return &respData, nil
}
respData.Resp = apiResp
respData.Info = apiReq
outParams := apiTest.ParseOutParams(apiTest.API.OutParams, apiResp, caseParams)
if len(apiTest.API.Asserts) > 0 {
asserts := apiTest.API.Asserts[0]
succ, assertResult := apiTest.JudgeAsserts(outParams, asserts)
logrus.Infof("judge assert result: %v", succ)
respData.Asserts = &apistructs.APITestsAssertResult{
Success: succ,
Result: assertResult,
}
}
return &respData, nil
}
func (svc *Service) renderPreSceneStepsOutput(sceneID uint64, replaceYml string) string {
var pipelinePageListRequest = apistructs.PipelinePageListRequest{
PageNum: 1,
PageSize: 1,
Sources: []apistructs.PipelineSource{
apistructs.PipelineSourceAutoTest,
},
YmlNames: []string{
strconv.Itoa(int(sceneID)),
},
Statuses: []string{apistructs.PipelineStatusSuccess.String(), apistructs.PipelineStatusFailed.String()},
DescCols: []string{"id"},
}
pagePipeline, err := svc.bdl.PageListPipeline(pipelinePageListRequest)
if err != nil {
logrus.Errorf("renderPreSceneStepsOutput, pageListPipeline error %v", err)
return replaceYml
}
if pagePipeline == nil || len(pagePipeline.Pipelines) <= 0 {
return replaceYml
}
pipeline, err := svc.bdl.GetPipeline(pagePipeline.Pipelines[0].ID)
if err != nil {
logrus.Errorf("renderPreSceneStepsOutput, GetPipeline error %v", err)
return replaceYml
}
if pipeline == nil {
return replaceYml
}
for _, stage := range pipeline.PipelineStages {
for _, task := range stage.PipelineTasks {
for _, result := range task.Result.Metadata {
replaceValue := convertJsonParam(result.Value)
replaceYml = strings.ReplaceAll(replaceYml, expression.GenOutputRef(task.Name, result.Name), replaceValue)
}
}
}
return replaceYml
}
func (svc *Service) SceneToYml(scene uint64, req apistructs.SnippetConfig) (string, error) {
sceneInputs, err := svc.ListAutoTestSceneInput(scene)
if err != nil {
return "", err
}
sceneOutputs, err := svc.ListAutoTestSceneOutput(scene)
if err != nil {
return "", err
}
sceneSteps, err := svc.ListAutoTestSceneStep(scene)
if err != nil {
return "", err
}
return svc.DoSceneToYml(sceneSteps, sceneInputs, sceneOutputs, req)
}
func (svc *Service) DoSceneToYml(sceneSteps []apistructs.AutoTestSceneStep, sceneInputs []apistructs.AutoTestSceneInput, sceneOutputs []apistructs.AutoTestSceneOutput, req apistructs.SnippetConfig) (string, error) {
sceneStages := StepToStages(sceneSteps)
yml, err := SceneToPipelineYml(sceneInputs, sceneOutputs, sceneStages, req)
if err != nil {
return "", err
}
return yml, err
}
func SceneToPipelineYml(inputs []apistructs.AutoTestSceneInput, outputs []apistructs.AutoTestSceneOutput, stages [][]apistructs.AutoTestSceneStep, req apistructs.SnippetConfig) (string, error) {
var spec pipelineyml.Spec
spec.Params = make([]*pipelineyml.PipelineParam, len(inputs))
spec.Outputs = make([]*pipelineyml.PipelineOutput, len(outputs))
for index, input := range inputs {
spec.Params[index] = &pipelineyml.PipelineParam{
Name: input.Name,
Desc: input.Description,
Required: true,
}
}
for index, output := range outputs {
spec.Outputs[index] = &pipelineyml.PipelineOutput{
Name: output.Name,
Desc: output.Description,
Ref: output.Value,
}
}
var stagesValue []*pipelineyml.Stage
for _, stage := range stages {
var specStage pipelineyml.Stage
var index = 0
for _, step := range stage {
// 跳过空的执行
if step.Value == "" {
continue
}
action, err := StepToAction(step, req)
if err != nil {
return "", err
}
specStage.Actions = append(specStage.Actions, action)
index++
}
if index > 0 {
stagesValue = append(stagesValue, &specStage)
}
}
spec.Stages = stagesValue
spec.Version = "1.1"
yml, err := pipelineyml.GenerateYml(&spec)
if err != nil {
return "", err
}
return string(yml), nil
}
func StepToAction(step apistructs.AutoTestSceneStep, req apistructs.SnippetConfig) (map[pipelineyml.ActionType]*pipelineyml.Action, error) {
var action pipelineyml.Action
stepJson, err := json.Marshal(step)
if err != nil {
return nil, err
}
action.Labels = map[string]string{}
action.Labels[apistructs.AutotestSceneStep] = base64.StdEncoding.EncodeToString(stepJson)
action.Labels[apistructs.AutotestType] = apistructs.AutotestSceneStep
action.Labels[apistructs.LabelIsRefSet] = req.Labels[apistructs.LabelIsRefSet]
action.Alias = pipelineyml.ActionAlias(strconv.Itoa(int(step.ID)))
action.If = expression.LeftPlaceholder + " 1 == 1 " + expression.RightPlaceholder
action.Disable = step.IsDisabled
switch step.Type {
case apistructs.StepTypeCustomScript:
var value apistructs.AutoTestRunCustom
err := json.Unmarshal([]byte(step.Value), &value)
if err != nil {
return nil, err
}
action.Type = "custom-script"
action.Version = "1.0"
action.Commands = value.Commands
action.Image = value.Image
case apistructs.StepTypeScene:
var value apistructs.AutoTestRunScene
err := json.Unmarshal([]byte(step.Value), &value)
if err != nil {
return nil, err
}
action.Params = make(map[string]interface{})
for key, value := range value.RunParams {
action.Params[key] = value
}
action.Type = pipelineyml.Snippet
action.SnippetConfig = &pipelineyml.SnippetConfig{
Name: strconv.Itoa(int(value.SceneID)),
Source: apistructs.PipelineSourceAutoTest.String(),
Labels: map[string]string{
apistructs.LabelAutotestExecType: apistructs.SceneAutotestExecType,
apistructs.LabelSceneID: strconv.Itoa(int(value.SceneID)),
apistructs.LabelSpaceID: strconv.Itoa(int(step.SpaceID)),
apistructs.LabelIterationID: req.Labels[apistructs.LabelIterationID],
apistructs.LabelTestPlanID: req.Labels[apistructs.LabelTestPlanID],
},
}
case apistructs.StepTypeAPI:
var value apistructs.AutoTestRunStep
err := json.Unmarshal([]byte(step.Value), &value)
if err != nil {
return nil, err
}
action.Type = "api-test"
action.Version = "2.0"
action.Params = value.ApiSpec
if value.Loop != nil && value.Loop.Strategy != nil && value.Loop.Strategy.MaxTimes > 0 {
action.Loop = value.Loop
}
case apistructs.StepTypeWait:
var value apistructs.AutoTestRunWait
err := json.Unmarshal([]byte(step.Value), &value)
if err != nil {
return nil, err
}
if value.WaitTime > 0 {
value.WaitTimeSec = value.WaitTime
}
if value.WaitTimeSec <= 0 {
return nil, errors.Errorf("Invalid wait time sec: %d", value.WaitTimeSec)
}
action.Type = "wait"
action.Version = "1.0"
action.Params = map[string]interface{}{
"wait_time_sec": value.WaitTimeSec,
}
case apistructs.StepTypeConfigSheet:
var value apistructs.AutoTestRunConfigSheet
err := json.Unmarshal([]byte(step.Value), &value)
if err != nil {
return nil, err
}
action.Params = make(map[string]interface{})
for key, value := range value.RunParams {
action.Params[key] = value
}
action.Type = apistructs.ActionTypeSnippet
action.SnippetConfig = &pipelineyml.SnippetConfig{
Name: value.ConfigSheetID,
Source: apistructs.PipelineSourceAutoTest.String(),
Labels: map[string]string{
apistructs.LabelSnippetScope: apistructs.FileTreeScopeAutoTestConfigSheet,
},