| 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 |
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
2x
2x
2x
2x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
6x
1x
1x
1x
1x
1x
1x
1x
1x
|
/**
* TestIt API
*/
import { IBuild, IGetSuggestTestCasesResponseDTO, IProject, IProjectInfo, IProjectKeyword, IProjectMetaData, ISectionInfo, ISuite, ITestCase, ITestExecution, ITestPlan, IVersion } from 'einstein-sdk/lib/@types/sdk/dto';
import { IGlobalData } from 'einstein-sdk/lib/@types/sdk/dto';
import { mkdir } from 'fs';
import _, { identity } from 'lodash';
import qs, { stringify } from 'qs';
import { threadId } from 'worker_threads';
import * as Parser from '../parser/parser';
import HttpClient from '../util/httpClient';
import { PREDEFINED_PROPERTY_MAP, PREDEFINED_VALUE_MAP, OPERATOR_MAP, Scope, CacheKey, KeywordsMap } from './constants';
import { TemplateInfo } from './dto';
export default class TestItSDK{
private endpoint : string;
private userName : string | null;
private accessToken : string | null;
private cache: Map<string, any>;
private httpClient : HttpClient;
constructor(endpoint: string){
this.endpoint = endpoint;
this.userName = null;
this.accessToken = null;
this.cache = new Map<string,any>();
this.httpClient = new HttpClient();
}
/**
* Return true if client is authorized.
*/
public getAutorized() : boolean{
return this.accessToken != null;
}
/**
* Login to TestIt. Save cookies if login successfully.
* @param username
* @param password
*/
public async login(username : string,password : string): Promise<void>{
try{
const url = `${this.endpoint}/api/v1/login`;
const data = {username, password};
const headers = {
'Content-Type' : 'application/json',
};
const config = {headers,data};
const response = await this.httpClient.post(url,config);
this.userName = response.data.username;
this.accessToken = response.data.access_token;
console.log(response.data);
await this.init();
}catch(err){
throw new Error('Failed to login TestIt, please check your username and password.')
}
}
/**
* Logout Testit, delete cookies.
*/
public logout():void{
this.userName = null;
this.accessToken = null;
}
/**
* Initialize sdk,fetch global data.
* @return {Promise<void>}
*/
public async init(): Promise<void> {
const globalData = await this.getGlobalData();
this.cache.set(CacheKey.GLOBAL_DATA, globalData);
}
/**
* Fetch fields information by project id for further using.
* @param projectId
*/
public async fetchFieldsInfoById(projectId : number) : Promise <any>{
const url = `${this.endpoint}/api/v1/fields?projectId=${projectId}`;
const headers = {
Authorization : this.accessToken,
'Content-type' : 'application/json',
};
const config = {
headers,
};
const response = await this.httpClient.get(url,config);
return response.data;
}
/**
* Get search elements map from fields by name.
* @param response
* @param name (like Keywords Subtype...)
*/
private async getFieldsInfoMapByName(response : any,name : string) : Promise<Map<string,number>>{
var fieldsIdxMap = await this.getFieldsIndexMap(response);
var index = fieldsIdxMap.get(name);
if(index == undefined){
throw new Error(`Not found the name : ${name}`);
}
const values = response[index].values;
var resMap = new Map<string,number>();
for(var i = 0;i < values.length;i++){
resMap.set(values[i].name,values[i].id)
}
return resMap;
}
/**
* Get field's response values map (name -> index).
* @param response
*/
private async getFieldsIndexMap(response : any) : Promise<Map<string,number>>{
var valuesMap = new Map<string,number>();
for(var i = 0;i < response.length;i++){
valuesMap.set(response[i].name,i);
}
return valuesMap;
}
/**
* Get field's response values map (name -> id).
* @param response
*/
private async getFieldsIdMap(response : any) : Promise<Map<string,number>>{
var valuesMap = new Map<string,number>();
for(var i = 0;i < response.length;i++){
valuesMap.set(response[i].name,response[i].id);
}
return valuesMap;
}
/**
* Get projects.
* @return {Promise<IProject[]>}
*/
public async getProjects(): Promise<IProject[]>{
const cacheKey = CacheKey.PROJECTS;
if(this.cache.has(cacheKey)){
return this.cache.get(cacheKey);
}
const url = `${this.endpoint}/api/v1/projects`;
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/json',
}
const config = {headers};
const response = await this.httpClient.get(url,config);
this.cache.set(cacheKey,response.data);
return response.data;
}
/**
* Get project by name.
* @param projectName
*/
public async getProjectByName(projectName : string) : Promise<IProject | undefined>{
const totalProjects = await this.getProjects();
return _.find(totalProjects,p => p.name === projectName);
}
/**
* Get project id by name.
* @param projectName
*/
private async getProjectIdByName(projectName : string) : Promise<any>{
const project = await this.getProjectByName(projectName);
if(!project){
throw new Error(`Project not found : ${projectName}.` );
}
return project['id'];
}
/**
* Get project by project id.
* @param projectId
*/
public async getProjectById(projectId : number): Promise<IProjectInfo>{
const cacheKey = `${CacheKey.PROJECT} : ${projectId}`;
if (this.cache.has(cacheKey)){
return this.cache.get(cacheKey);
}
const url = `${this.endpoint}/api/v1/project/${projectId}`;
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/json',
};
const config = {headers};
const response = await this.httpClient.get(url,config);
//update : response total data of project.
this.cache.set(cacheKey,response.data);
return response.data;
}
/**
* Get keywords by project id.
* 【Error】Project doesn't include keywords!Not really go.
* @param projectId
*/
public async getKeywordsByProjectId(projectId : number) : Promise<IProjectKeyword[]>{
const cacheKey = `${CacheKey.KEYWORDS} : ${projectId}`;
if(this.cache.has(cacheKey)){
return this.cache.get(cacheKey);
}
const url = `${this.endpoint}/api/v1/project/${projectId}`;
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/json',
};
const config = { headers };
const response = await this.httpClient.get(url,config);
this.cache.set(cacheKey,response.data);
return response.data;
}
/**
* Get project tree by project id.
* @param projectId
*/
public async getProjectTreeById(projectId : number) : Promise<ISuite[]>{
const cacheKey = `${CacheKey.PROJECT_TREE} : ${projectId}`;
if(this.cache.has(cacheKey)){
return this.cache.get(cacheKey);
}
const url = `${this.endpoint}/api/v1/project/${projectId}/tree`;
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/json',
};
const config = {headers};
const response = await this.httpClient.get(url,config);
this.cache.set(cacheKey,response.data);
return response.data;
}
/**
* Get section by section id.
* @param sectionId
*/
public async getSectionById(sectionId : number) : Promise<ISectionInfo>{
const cacheKey = `${CacheKey.SECTION} : ${sectionId}`;
if(this.cache.has(cacheKey)){
return this.cache.get(cacheKey);
}
const url = `${this.endpoint}/api/v1/section/${sectionId}`;
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/json',
};
const config = { headers };
const response = await this.httpClient.get(url,config);
this.cache.set(cacheKey,response.data);
return response.data;
}
/**
* Get test case by test case id. - 17
* @param testCaseId
*/
public async getTestCaseById(testCaseId : number) : Promise<ITestCase>{
try{
const url = `${this.endpoint}/api/v1/case/${testCaseId}`;
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/json',
};
const config = {headers};
const response = await this.httpClient.get(url,config);
return response.data;
}catch(err){
throw new Error('404 Not Found.Please make sure the right testCaseId');
}
}
/**
* Get many test cases by test case ids.
* @param testCaseIds
*/
public async getTestCasesByIds(testCaseIds : number[]) : Promise<ITestCase[]>{
var prefix = `${this.endpoint}/api/v1/cases?`;
testCaseIds.forEach(function(value){
prefix = `${prefix}id=${value}&`;
});
const url = prefix.substring(0,prefix.length - 1);
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/json',
};
const config = { headers };
const response = await this.httpClient.get(url,config);
return response.data;
}
/**
* Get test plans from test case by test case id.
* @param testCaseId
*/
public async getTestPlansByTestCaseId(testCaseId : number) : Promise<ITestPlan[]>{
const cacheKey = `${CacheKey.TEST_PLAN} : ${testCaseId}`;
if(this.cache.has(cacheKey)){
return this.cache.get(cacheKey);
}
const url = `${this.endpoint}/api/v1/case/${testCaseId}/testplans`;
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/json',
};
const config = { headers };
const response = await this.httpClient.get(url,config);
this.cache.set(cacheKey,response.data);
return response.data;
}
/**
* Get test plans by project ids.
* @param projectIds
*/
public async getTestPlansByProjectIds(projectIds : number[]) : Promise<ITestPlan[]>{
var prefix = `${this.endpoint}/api/v1/testplans?`;
projectIds.forEach(function(value){
prefix = `${prefix}projectId=${value}&`;
});
const url = prefix.substring(0,prefix.length - 1);
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/json',
};
const config = { headers };
const response = await this.httpClient.get(url,config);
return response.data;
}
/**
* Get execution-history by test case id.
* @param testCaseId
*/
public async getExecutionHistoryByTestCaseId(testCaseId : number) : Promise<ITestExecution>{
const url = `${this.endpoint}/api/v1/case/${testCaseId}/execution-history`;
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/json',
};
const config = {headers};
const response = await this.httpClient.get(url,config);
return response.data;
}
/**
* Get test case version by version id.
* @param versionId
*/
public async getCaseVersionByVersionId(versionId : number) : Promise<IVersion>{
const url = `${this.endpoint}/api/v1/case/version/${versionId}`;
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/json',
};
const config = {headers};
const response = await this.httpClient.get(url,config);
return response.data;
}
/**
* Get test case by key.
* 【Example】key = JPT-3166
* @param key
*/
public async getTestCaseByKey(key : string) : Promise<ITestCase>{
const url = `${this.endpoint}/api/v1/case/${key}`;
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'applicaiton/json',
};
const config = { headers };
const response = await this.httpClient.get(url,config);
return response.data;
}
/**
* Get builds by test plan id.
* @param testPlanId
*/
public async getBuildsByTestPlanId(testPlanId: number): Promise<IBuild[]> {
const url = `${this.endpoint}/api/v1/testplan/${testPlanId}/builds`;
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/json',
};
const config = { headers };
const response = await this.httpClient.get(url, config);
return response.data;
}
/**
* Get test plan by test plan id.
* @param testPlanId
*/
public async getTestPlanById(testPlanId : number) : Promise<ITestPlan>{
const url = `${this.endpoint}/api/v1/testplan/${testPlanId}`;
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/json',
};
const config = { headers };
const response = await this.httpClient.get(url,config);
return response.data;
}
/**
* Get tree by test plan id.
* @param testPlanId
*/
public async getTreeByTestPlanId(testPlanId : number) : Promise<ITestPlan>{
const url = `${this.endpoint}/api/v1/testplan/${testPlanId}/tree`;
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/json',
};
const config = { headers };
const response = await this.httpClient.get(url,config);
return response.data;
}
/**
* Get execution progress by test plan id.
* @param testPlanId
*/
public async getExecutionProgressByTestPlanId(testPlanId : number) : Promise<ITestExecution>{
const url = `${this.endpoint}/api/v1/testplan/${testPlanId}/execution-progress`;
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/json',
};
const config = { headers };
const response = await this.httpClient.get(url,config);
return response.data;
}
/**
* Get build by build id.
* @param buildId
*/
public async getBuildById(buildId : number) : Promise<IBuild>{
const url = `${this.endpoint}/api/v1/build/${buildId}`;
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/json',
};
const config = { headers };
const response = await this.httpClient.get(url,config);
return response.data;
}
/**
* Get suite by suite id.
* @param suiteId
*/
public async getSuiteById(suiteId : number) : Promise<ISuite>{
const cacheKey = `${CacheKey.SUITES}:${suiteId}`;
if(this.cache.has(cacheKey)){
return this.cache.get(cacheKey);
}
const url = `${this.endpoint}/api/v1/suite/${suiteId}`;
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/json',
};
const config = { headers };
const response = await this.httpClient.get(url,config);
this.cache.set(cacheKey,response.data);
return response.data;
}
/**
* Get suite tree by suite id.
* @param suiteId
*/
public async getSuiteTreeById(suiteId : number):Promise<ISuite[]>{
const cacheKey = `${CacheKey.SUITE_TREE}:${suiteId}`;
if(this.cache.has(cacheKey)){
return this.cache.get(cacheKey);
}
const url = `${this.endpoint}/api/v1/suite/${suiteId}/tree`;
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/json',
};
const config = {headers};
const response = await this.httpClient.get(url,config);
this.cache.set(cacheKey,response.data);
return response.data;
}
/* Search API use in cases */
/**
* Search test cases by json query.
* @param query
* @param scope
*/
private async searchTestCasesByJsonQuery(query : any,scope : Scope = 'TEST_SUITES'):Promise<any>{
const criterionJson = query;/* JSON.stringify(query); */
const url = `${this.endpoint}/testCases/search`;
const data = {
type : 'search',
scope,
criterionJson
};
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8',
}
const config = {
headers,
data : qs.stringify(data),
}
const response = await this.httpClient.post(url,config);
return response.data;
}
/**
* Flatten response data.
* @param root
*/
private flat(root: any) {
const cases: any[] = [];
const fifo: any[] = [root];
while(fifo.length > 0) {
const node = fifo.shift();
if ('case' !== node.type) {
if (node.children && node.children.length > 0) {
node.children.forEach((child: { path: any[]; }) => {
if (!child.path) {
child.path = []
}
child.path.push(node.name);
});
fifo.push(...node.children);
}
} else {
cases.push(node);
}
}
return cases;
}
/**
* Search and generate template data from cases by project name、keywords and subtype.
* @param query
*/
public async generateTemplateInfo(projectName : string ,keywords : string[], subtype : string[]) : Promise<any>{
const query = await this.generateQuery(projectName,keywords,subtype);
const response = await this.searchTestCasesByQuery(query);
const flatResponse = this.flat(response);
const flatLength = flatResponse.length;
const resultData = [];
for(var i = 0 ; i < flatLength;i++){
var tempKey = `${flatResponse[i].prefix}-${flatResponse[i].externalId}`;
resultData.push(await this.generateTemplatesInfoByKey(tempKey));
}
return resultData;
}
/**
* Store file that we search to path.
* @param projectName
* @param keywords
* @param subtype
* @param path
*/
public async storeTemplateFile(projectName : string ,keywords : string[], subtype : string[],path : string) : Promise<any>{
const query = await this.generateQuery(projectName,keywords,subtype);
const response = await this.searchTestCasesByQuery(query);
const flatResponse = this.flat(response);
const flatLength = flatResponse.length;
for(var i = 0 ; i < flatLength;i++){
var tempKey = `${flatResponse[i].prefix}-${flatResponse[i].externalId}`;
var fileName = `${path}${tempKey}.test.ts`;
var info = await this.generateTemplatesInfoByKey(tempKey);
this.writeTemplateInfo(info,fileName);
}
console.log('Store Successfully');
}
/**
* Search test cases by query.
* 【Query Example】const query = `version eq "active" and project_id in "[1311]" and field.5371560 in "[6234174]" and field.224 in "[11949947]"`;
* @param query
* @param scope
*/
public async searchTestCasesByQuery(query : string,scope : Scope = 'TEST_SUITES') : Promise<any>{
const queryParse = Parser.parse(query);
var queryJson = await JSON.stringify(queryParse);
//Handle the queryJson.
const s1 = "\\\"";
queryJson = queryJson.replace(s1,"").replace(s1,"");
queryJson = queryJson.replace(/\"\\\"/g,"").replace(/\\\"\"/g,"");
return this.searchTestCasesByJsonQuery(queryJson,scope);
}
/**
* Search testcases by project name、keywords and subtype.
* @param projectName
* @param keywords
* @param subtype
*/
public async searchCasesInProjectByKeywordsAndSubtype(projectName : string ,keywords : string[], subtype : string[]):Promise<any>{
//ToQuery
const query = await this.generateQuery(projectName,keywords,subtype);
const searchRes = await this.searchTestCasesByQuery(query,'TEST_SUITES');
return searchRes;
}
/**
* Generate search query by project name、keywords and suite.
* @param projectName
* @param keywords
* @param subtype
*/
private async generateQuery(projectName : string ,keywords : string[], subtype : string[]) : Promise<string>{
const projectId = await this.getProjectIdByName(projectName);
//Fetch fields info
const response = await this.fetchFieldsInfoById(projectId);
//Generate map
const keyworsMap = await this.getFieldsInfoMapByName(response,'Keywords');
const subtypeMap = await this.getFieldsInfoMapByName(response,'Subtype');
const fieldsIdMap = await this.getFieldsIdMap(response);
//For key Map
var keywordsArr = [];
for(var i = 0 ; i < keywords.length;i++){
keywordsArr.push(keyworsMap.get(keywords[i]));
}
//For Suite Map
var subtypeArr = [];
for(var i = 0 ; i < keywords.length;i++){
subtypeArr.push(subtypeMap.get(subtype[i]));
}
//ToQuery
const query = `version eq "active" and project_id in "[${projectId}]"
and field.${fieldsIdMap.get('Subtype')} in "[${subtypeArr}]"
and field.${fieldsIdMap.get('Keywords')} in "[${keywordsArr}]"`;
return query;
}
/* Sync API */
/**
* Get sync projects.
*/
public async getSyncProjects():Promise<any>{
const url = `${this.endpoint}/api/internal/sync/projects`;
const headers = {
Authorization : this.accessToken,
'Content-type': 'application/json',
};
const config = { headers };
const response = await this.httpClient.get(url,config);
return response.data;
}
/**
* Get sync cases.
*/
public async getSyncCases():Promise<any>{
const url = `${this.endpoint}/api/internal/sync/cases`;
const headers = {
Authorization : this.accessToken,
'Content-type': 'application/json',
};
const config = { headers };
const response = this.httpClient.get(url,config);
return response;
}
/* Get Store API */
/**
* Get store project by project id.
* @param projectId
*/
public async getStoreProjectById(projectId : number):Promise<any>{
const url = `${this.endpoint}/api/internal/storage/project/${projectId}`;
const headers = {
Authorization : this.accessToken,
'Content-type': 'application/json',
};
const config = { headers };
const response = await this.httpClient.get(url,config);
return response.data;
}
/**
* Get global data.
* @return {Promise<IGlobalData>}
*/
public async getGlobalData() : Promise<IGlobalData>{
const url = `${this.endpoint}/projects/static`;
const headers = {
Authorization: this.accessToken,
'Content-Type' : 'application/json',
};
const config = {headers};
const response = await this.httpClient.get(url,config);
return response.data;
}
/**
* Search for suggest cases by query.
* @param pattern
* @param limit
*/
public async getSuggestTestCases(pattern : string,limit : number = 10) : Promise<IGetSuggestTestCasesResponseDTO>{
const url = `${this.endpoint}/api/v1/suggest/cases?search=${pattern}&limit=${limit}`;
const headers = {
Authorization : this.accessToken,
'Content-Type' : 'application/json',
};
const config = { headers };
const response = await this.httpClient.get(url,config);
return response.data;
}
/**
* Generate template information by key.
* @param key Case key
*/
public async generateTemplatesInfoByKey(key : string) : Promise<string>{
const responseData = await this.getTestCaseByKey(key);
const ascendantsLen = responseData.ascendants.length;
const suite = responseData.ascendants[ascendantsLen - 1].name;
const nameInfo = `${key}:${responseData.name}`;
const casePrioriy = `P${responseData.priority}`;
const skip = true; //default
const skipReason = 'waiting for E2E deliver'; //default
const keywords = [];
const maintainers = [];
const valueLen = responseData.values.length;
//Refer to field id.
for(var i = 0; i < valueLen ; i++){
if(responseData.values[i].fieldId == 224){
keywords.push(responseData.values[i].name);
}
else if(responseData.values[i].fieldId == 6615030){
maintainers.push(responseData.values[i].name);
}
}
//Handle the test steps info.
var childrenLen;
var steps = [];
var expectedResult = [];
if((childrenLen = responseData.children.length) != 0){
for(var i = 0;i < childrenLen;i++){
steps[i] = await this.stringFilter(responseData.children[i].name);
expectedResult[i] = await this.stringFilter(responseData.children[i].expectedResult);
}
}
//some str to connect the data.
const importInfo = `import { h, runTest } from '@src/init';\nimport { App } from "@src/pageModels/app";\nimport { StepWrapper } from "@tests/stepWrapper";\nimport { HomePageController } from "@src/pageControllers/app/homePage";\nimport MeetingRoomController from "@src/pageControllers/app/homePage/meetingRoom";\nimport { WebphoneSession } from "ultron-client";\nimport { LeftRailController } from "@src/pageControllers/app/homePage/meetTab";\nimport MeetingPageController from '@src/pageControllers/app/homePage/meetingPage';\nimport { sleep } from "@src/libs/utils";\n`;
const runTestInfo = 'runTest({\n';
const asyncInfo = '},async(t:any)=>{\n'
const preStep = "\tawait h(t).When_(\"";
const afterStep = ',async()=>{\n\t});\n';
const preExpect = "\tawait h(t).Then_(\"";
const afterExpect = ",async() => {\n\t});\n";
const end = "\th(t).finish();\n});";
//storage template info.
var resInfo:TemplateInfo = {
suite:suite,
name:[nameInfo],
priority:casePrioriy,
skip:skip,
skipReason:skipReason,
keywords:keywords,
maintainers:maintainers
};
// handle resInfo
var resInfoStr = JSON.stringify(resInfo);
const resInfoKeys = Object.keys(resInfo);//get keys
for(var i = 0;i < resInfoKeys.length;i++){
resInfoStr = resInfoStr.replace(`"${resInfoKeys[i]}"`,resInfoKeys[i]);
resInfoStr = resInfoStr.replace(`,${resInfoKeys[i]}`,`,\n${resInfoKeys[i]}`);
}
// delete the character of start and end
resInfoStr = resInfoStr.replace(resInfoStr.charAt(0),"");
resInfoStr = resInfoStr.replace(resInfoStr.charAt(resInfoStr.length - 1),"");
// add tab
for(var i = 0;i < resInfoKeys.length;i++){
resInfoStr = resInfoStr.replace(`${resInfoKeys[i]}`,`\t${resInfoKeys[i]}`);
}
// put together
var resultInfo = `${importInfo}${runTestInfo}${resInfoStr}\n${asyncInfo}`;
for(var i = 0; i < childrenLen;i++){
resultInfo = `${resultInfo}${preStep}${steps[i]}"${afterStep}${preExpect}${expectedResult[i]}"${afterExpect}`;
}
resultInfo = `${resultInfo}${end}`;
return resultInfo;
}
/**
* Write info to ouputstream and storage to file path.
* @param info
* @param filePath
*/
public async writeTemplateInfo(info : string,filePath : string):Promise<any>{
var fs = require('fs');
var infoWriteStream = fs.createWriteStream(filePath);
infoWriteStream.write(info,'UTF-8');
infoWriteStream.end();
infoWriteStream.on(`${filePath}--Done`,()=>{
console.log('${filePath}--Done')
});
// infoWriteStream.on('error',function(err:any){
// console.log(err.stack);
// });
}
/**
* Store a template file to file path by case key.
* @param key
* @param filePath
*/
public async storeTemplateInfoByCaseKey(key : string , filePath : string){
const info = await this.generateTemplatesInfoByKey(key);
filePath = `${filePath}${key}.test.ts`;
this.writeTemplateInfo(info,filePath);
}
/**
* Store template info for file tree by case key.
* @param key
* @param filePath
*/
public async storeFileTreeByCaseKey(key : string , filePath : string){
const response = await this.getTestCaseByKey(key);
const ascendants = response.ascendants;
var suiteTree = "";
// var suiteArr = [];
for(var i = 0;i < ascendants.length;i++){
suiteTree = `${suiteTree}/${ascendants[i].name}`;
// suiteArr[i] = ascendants[i].name;
}
suiteTree = suiteTree.replace(suiteTree.charAt(0),"");
filePath = `${filePath}${suiteTree}`;
this.writeInfoByCreateDir(key,filePath);
}
/**
* Write info by create dir.
* @param info
* @param filePath
*/
private async writeInfoByCreateDir(key : string,filePath : string):Promise<any>{
//get template info
const info = await this.generateTemplatesInfoByKey(key);
const mkdirp = require('mkdirp');
await mkdirp(filePath).then((made: any) => console.log(`Create in ${made}`));
var fs = require('fs');
// this.mkdir('test/templateFiles/Jupiter');
const testFile = `${filePath}${key}.test.ts`;
var infoWriteStream = await fs.createWriteStream(testFile);
infoWriteStream.write(info,'UTF-8');
infoWriteStream.end();
infoWriteStream.on(`${filePath}--Done`,()=>{
console.log('${filePath}--Done')
});
infoWriteStream.on('error',function(err:any){
console.log(err.stack);
});
}
// /**
// * Create suite directory.
// * @param sourcePath
// * @param suiteArr
// */
// private async createSuiteDir(sourcePath : string,suiteArr : string[]) : Promise<any>{
// const fs = require('fs');
// var filePath = sourcePath;
// for(var i = 0;i < suiteArr.length;i++){
// filePath = `${filePath}${suiteArr[i]}`;
// fs.stat(filePath,(err:any,data:any)=>{
// if(err){
// this.mkdir(filePath);
// return;
// }
// if(data.isDirectory()){
// }else{
// fs.unlink(filePath,(err:any) =>{
// if(!err){
// this.mkdir(filePath);
// }
// })
// }
// });
// }
// }
/**
* Make directory.
* @param dir
*/
private async mkdir(dir : any) {
const fs = require('fs');
fs.mkdir(dir, (err:any) => {
if(err) {
console.log(err);
return
}
})
}
/**
* Filter string with special character.
* @param str
*/
private async stringFilter(str : string) : Promise<string>{
if(str != null){
const nbsp = ' ';
const newLine = "\n";
const quota = "\"";
str = await str.replace(new RegExp(nbsp,"g"),"")
.replace(new RegExp("<.*?>","g"),"")
.replace(new RegExp(newLine,"g")," ")
.replace(new RegExp(quota,"g"),"\'");// RegExp = "<.*?>" all block
str = str.trim();
}
return str;
}
}
// /**
// * Test Modules
// */
// async function testitDemo(){
// /* Login require information */
// const TESTIT_ENDPOINT = 'https://testit.ringcentral.com';
// const testItSdk = new TestItSDK(TESTIT_ENDPOINT);
// const username : string = 'margin.xu';
// const password : string = 'First1214';
// /* 1、Test login function. */
// await testItSdk.login(username,password);
// console.log('----Welcome! Login Successfully!-----');
// /* Test storage files to templateFiles directory.*/
// const projectName = "Jupiter";
// const keywords = ['R20.4.30'];
// const subtype = ['E2E'];
// const filePath = '../templateFiles/';
// testItSdk.storeTemplateFile(projectName,keywords,subtype,filePath);
// // 1.Storage template file to filepath by case key.
// // const key = "JPT-7244";
// // const path = `../templateFiles/`;
// // await testItSdk.storeTemplateInfoByCaseKey(key,path);
// }
// testitDemo();
/*testit search json
criterionJson: {
"type":"and",
"left":{"type":"eq","property":"version","value":"active"},
"right":
{"type":"and",
"left":{"type":"in","property":"project_id","value":[1311]},
"right":{"type":"and",
"left":{"type":"in","property":"field.5371560","value":[6234174]},
"right":{"type":"in","property":"field.224","value":[11949947]}
}
}
} */
/*einstein search json
{"type":"and",
"left":{"type":"and",
"left":{"type":"and",
"left":{"type":"in","property":"execution_field.224","value":[11949947]},
"right":{"type":"and",
"left":{"type":"in","property":"field.5371560","value":[6234174]},
"right":{"type":"in","property":"project_id","value":[1311]}
}
},
"right":{"type":"eq","property":"version","value":"active"}
},
"right":{"type":"eq","property":"project_id","value":1311}
} */
//若多添加了project则json中必然存在多条project_id
|