/
ScenarioEngine.java
2147 lines (1967 loc) · 81.9 KB
/
ScenarioEngine.java
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
/*
* The MIT License
*
* Copyright 2020 Intuit Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.intuit.karate.core;
import com.intuit.karate.ImageComparison;
import com.intuit.karate.FileUtils;
import com.intuit.karate.Json;
import com.intuit.karate.JsonUtils;
import com.intuit.karate.KarateException;
import com.intuit.karate.Logger;
import com.intuit.karate.Match;
import com.intuit.karate.RuntimeHook;
import com.intuit.karate.StringUtils;
import com.intuit.karate.XmlUtils;
import com.intuit.karate.driver.Driver;
import com.intuit.karate.driver.DriverOptions;
import com.intuit.karate.driver.Key;
import com.intuit.karate.graal.JsEngine;
import com.intuit.karate.graal.JsLambda;
import com.intuit.karate.graal.JsValue;
import com.intuit.karate.http.*;
import com.intuit.karate.resource.Resource;
import com.intuit.karate.resource.ResourceResolver;
import com.intuit.karate.shell.Command;
import com.intuit.karate.template.KarateTemplateEngine;
import com.intuit.karate.template.TemplateUtils;
import com.jayway.jsonpath.PathNotFoundException;
import org.graalvm.polyglot.Value;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.File;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.graalvm.polyglot.proxy.ProxyExecutable;
import org.slf4j.LoggerFactory;
/**
*
* @author pthomas3
*/
public class ScenarioEngine {
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ScenarioEngine.class);
private static final String KARATE = "karate";
private static final String READ = "read";
private static final String DRIVER = "driver";
private static final String ROBOT = "robot";
private static final String KEY = "Key";
public static final String RESPONSE = "response";
public static final String RESPONSE_HEADERS = "responseHeaders";
public static final String RESPONSE_STATUS = "responseStatus";
private static final String RESPONSE_BYTES = "responseBytes";
private static final String RESPONSE_COOKIES = "responseCookies";
private static final String RESPONSE_TIME = "responseTime";
private static final String RESPONSE_TYPE = "responseType";
private static final String LISTEN_RESULT = "listenResult";
public static final String REQUEST = "request";
public static final String REQUEST_URL_BASE = "requestUrlBase";
public static final String REQUEST_URI = "requestUri";
private static final String REQUEST_PARAMS = "requestParams";
public static final String REQUEST_METHOD = "requestMethod";
public static final String REQUEST_HEADERS = "requestHeaders";
private static final String REQUEST_TIME_STAMP = "requestTimeStamp";
public final ScenarioRuntime runtime;
public final ScenarioFileReader fileReader;
public final Map<String, Variable> vars;
public final Logger logger;
private final Function<String, Object> readFunction;
private final ScenarioBridge bridge;
private final Collection<RuntimeHook> hooks;
private boolean aborted;
private Throwable failedReason;
protected JsEngine JS;
public ScenarioEngine(Config config, ScenarioRuntime runtime, Map<String, Variable> vars, Logger logger) {
this.config = config;
this.runtime = runtime;
hooks = runtime.featureRuntime.suite.hooks;
fileReader = new ScenarioFileReader(this, runtime.featureRuntime);
readFunction = s -> JsValue.fromJava(fileReader.readFile(s));
bridge = new ScenarioBridge(this);
this.vars = vars;
this.logger = logger;
}
public static ScenarioEngine forTempUse(HttpClientFactory hcf) {
FeatureRuntime fr = FeatureRuntime.forTempUse(hcf);
ScenarioRuntime sr = new ScenarioIterator(fr).first();
sr.engine.init();
return sr.engine;
}
private static final ThreadLocal<ScenarioEngine> THREAD_LOCAL = new ThreadLocal<ScenarioEngine>();
public static ScenarioEngine get() {
return THREAD_LOCAL.get();
}
public static void set(ScenarioEngine se) {
THREAD_LOCAL.set(se);
}
protected static void remove() {
THREAD_LOCAL.remove();
}
// engine ==================================================================
//
public boolean isAborted() {
return aborted;
}
public void setAborted(boolean aborted) {
this.aborted = aborted;
}
public boolean isFailed() {
return failedReason != null;
}
public boolean isIgnoringStepErrors() {
return !config.getContinueOnStepFailureMethods().isEmpty();
}
public void setFailedReason(Throwable failedReason) {
this.failedReason = failedReason;
}
public Throwable getFailedReason() {
return failedReason;
}
public void matchResult(Match.Type matchType, String expression, String path, String expected) {
Match.Result mr = match(matchType, expression, path, expected);
if (!mr.pass) {
setFailedReason(new KarateException(mr.message));
}
}
public void set(String name, String path, String exp) {
set(name, path, exp, false, false);
}
public void remove(String name, String path) {
try {
set(name, path, null, true, false);
} catch (Exception e) {
logger.warn("remove failed: {}", e.getMessage());
}
}
public void table(String name, List<Map<String, String>> rows) {
name = StringUtils.trimToEmpty(name);
validateVariableName(name);
List<Map<String, Object>> result = new ArrayList<>(rows.size());
for (Map<String, String> map : rows) {
Map<String, Object> row = new LinkedHashMap<>(map);
List<String> toRemove = new ArrayList(map.size());
for (Map.Entry<String, Object> entry : row.entrySet()) {
String exp = (String) entry.getValue();
Variable sv = evalKarateExpression(exp);
if (sv.isNull() && !isWithinParentheses(exp)) { // by default empty / null will be stripped, force null like this: '(null)'
toRemove.add(entry.getKey());
} else {
if (sv.isString()) {
entry.setValue(sv.getAsString());
} else { // map, list etc
entry.setValue(sv.getValue());
}
}
}
for (String keyToRemove : toRemove) {
row.remove(keyToRemove);
}
result.add(row);
}
setVariable(name, result);
}
public void replace(String name, String token, String value) {
name = name.trim();
Variable v = vars.get(name);
if (v == null) {
throw new RuntimeException("no variable found with name: " + name);
}
String text = v.getAsString();
String replaced = replacePlaceholderText(text, token, value);
setVariable(name, replaced);
}
public void assertTrue(String expression) {
if (!evalJs(expression).isTrue()) {
String message = "did not evaluate to 'true': " + expression;
setFailedReason(new KarateException(message));
}
}
public void print(String exp) {
if (!config.isPrintEnabled()) {
return;
}
evalJs("karate.log('[print]'," + exp + ")");
}
public void invokeAfterHookIfConfigured(boolean afterFeature) {
if (runtime.caller.depth > 0) {
return;
}
Variable v = afterFeature ? config.getAfterFeature() : config.getAfterScenario();
if (v.isJsOrJavaFunction()) {
if (afterFeature) {
ScenarioEngine.set(this); // for any bridge / js to work
}
try {
executeFunction(v);
} catch (Exception e) {
String prefix = afterFeature ? "afterFeature" : "afterScenario";
logger.warn("{} hook failed: {}", prefix, e + "");
}
}
}
// gatling =================================================================
//
private PerfEvent prevPerfEvent;
public void logLastPerfEvent(String failureMessage) {
if (prevPerfEvent != null && runtime.perfMode) {
if (failureMessage != null) {
prevPerfEvent.setFailed(true);
prevPerfEvent.setMessage(failureMessage);
}
runtime.featureRuntime.perfHook.reportPerfEvent(prevPerfEvent);
}
prevPerfEvent = null;
}
public void capturePerfEvent(PerfEvent event) {
logLastPerfEvent(null);
prevPerfEvent = event;
}
// http ====================================================================
//
protected HttpRequestBuilder requestBuilder; // see init() method
private HttpRequest httpRequest;
private Request request; // used only for mocks
private Response response;
private Config config;
public Config getConfig() {
return config;
}
// important: use this to trigger client re-config
// callonce routine is one example
public void setConfig(Config config) {
this.config = config;
if (requestBuilder != null) {
requestBuilder.client.setConfig(config);
}
}
public void setRequest(Request request) {
this.request = request;
}
public Request getRequest() {
if (request != null) {
return request;
}
if (httpRequest != null) {
request = httpRequest.toRequest();
request.processBody();
return request;
}
return null;
}
public HttpRequest getHttpRequest() {
return httpRequest;
}
public Response getResponse() {
return response;
}
public HttpRequestBuilder getRequestBuilder() {
return requestBuilder;
}
public void configure(String key, String exp) {
Variable v = evalKarateExpression(exp);
configure(key, v);
}
public void configure(String key, Variable v) {
key = StringUtils.trimToEmpty(key);
// if next line returns true, config is http-client related
if (config.configure(key, v)) {
if (requestBuilder != null) {
requestBuilder.client.setConfig(config);
}
}
}
private void evalAsMap(String exp, BiConsumer<String, List<String>> fun) {
Variable var = evalKarateExpression(exp);
if (!var.isMap()) {
logger.warn("did not evaluate to map {}: {}", exp, var);
return;
}
Map<String, Object> map = var.getValue();
map.forEach((k, v) -> {
if (v instanceof List) {
List list = (List) v;
List<String> values = new ArrayList(list.size());
for (Object o : list) { // support non-string values, e.g. numbers
if (o != null) {
values.add(o.toString());
}
}
fun.accept(k, values);
} else if (v != null) {
fun.accept(k, Collections.singletonList(v.toString()));
}
});
}
public void url(String exp) {
Variable var = evalKarateExpression(exp);
requestBuilder.url(var.getAsString());
}
public void path(String exp) {
if (exp.contains(",")) {
exp = "[" + exp + "]";
}
Variable v = evalJs(exp);
List<?> list;
if (v.isList()) {
list = v.getValue();
} else {
list = Collections.singletonList(v.getValue());
}
for (Object o : list) {
if (o != null) {
requestBuilder.path(o.toString());
}
}
}
public void param(String name, String exp) {
Variable var = evalJs(exp);
if (var.isList()) {
requestBuilder.param(name, var.<List>getValue());
} else {
requestBuilder.param(name, var.getAsString());
}
}
public void params(String expr) {
evalAsMap(expr, (k, v) -> requestBuilder.param(k, v));
}
public void header(String name, String exp) {
Variable var = evalKarateExpression(exp);
if (var.isList()) {
requestBuilder.header(name, var.<List>getValue());
} else {
requestBuilder.header(name, var.getAsString());
}
}
public void headers(String expr) {
evalAsMap(expr, (k, v) -> requestBuilder.header(k, v));
}
public void cookie(String name, String exp) {
Variable var = evalKarateExpression(exp);
if (var.isString()) {
requestBuilder.cookie(name, var.getAsString());
} else if (var.isMap()) {
Map<String, Object> map = var.getValue();
map.put("name", name);
requestBuilder.cookie(map);
}
}
public void cookies(String exp) {
Variable var = evalKarateExpression(exp);
Map<String, Map> cookies = Cookies.normalize(var.getValue());
requestBuilder.cookies(cookies.values());
}
private void updateConfigCookies(Map<String, Map> cookies) {
if (cookies == null) {
return;
}
if (config.getCookies().isNull()) {
config.setCookies(new Variable(cookies));
} else {
Map<String, Map> map = getOrEvalAsMap(config.getCookies());
map.putAll(cookies);
config.setCookies(new Variable(map));
}
}
public void formField(String name, String exp) {
Variable var = evalKarateExpression(exp);
if (var.isList()) {
requestBuilder.formField(name, var.<List>getValue());
} else {
requestBuilder.formField(name, var.getAsString());
}
}
public void formFields(String exp) {
Variable var = evalKarateExpression(exp);
if (var.isMap()) {
Map<String, Object> map = var.getValue();
map.forEach((k, v) -> {
requestBuilder.formField(k, v);
});
} else {
logger.warn("did not evaluate to map {}: {}", exp, var);
}
}
public void multipartField(String name, String value) {
Variable v = evalKarateExpression(value);
Map map = new HashMap();
map.put("value", v.getValue());
multiPartInternal(name, map);
}
public void multipartFields(String exp) {
multipartFiles(exp);
}
private void multiPartInternal(String name, Object value) {
Map<String, Object> map = new HashMap();
if (name != null) {
map.put("name", name);
}
if (value instanceof Map) {
map.putAll((Map) value);
String toRead = (String) map.get("read");
if (toRead != null) {
Resource resource = fileReader.toResource(toRead);
if (resource.isFile()) {
File file = resource.getFile();
map.put("value", file);
} else {
map.put("value", FileUtils.toBytes(resource.getStream()));
}
}
requestBuilder.multiPart(map);
} else if (value instanceof String) {
map.put("value", (String) value);
multiPartInternal(name, map);
} else if (value instanceof List) {
List list = (List) value;
for (Object o : list) {
multiPartInternal(null, o);
}
} else if (logger.isTraceEnabled()) {
logger.trace("did not evaluate to string, map or list {}: {}", name, value);
}
}
public void multipartFile(String name, String exp) {
Variable var = evalKarateExpression(exp);
multiPartInternal(name, var.getValue());
}
public void multipartFiles(String exp) {
Variable var = evalKarateExpression(exp);
if (var.isMap()) {
Map<String, Object> map = var.getValue();
map.forEach((k, v) -> multiPartInternal(k, v));
} else if (var.isList()) {
List<Map> list = var.getValue();
for (Map map : list) {
multiPartInternal(null, map);
}
} else {
logger.warn("did not evaluate to map or list {}: {}", exp, var);
}
}
public void request(String body) {
Variable v = evalKarateExpression(body);
requestBuilder.body(v.getValue());
}
public void soapAction(String exp) {
String action = evalKarateExpression(exp).getAsString();
if (action == null) {
action = "";
}
requestBuilder.header("SOAPAction", action);
requestBuilder.contentType("text/xml");
method("POST");
}
public void retry(String condition) {
requestBuilder.setRetryUntil(condition);
}
public void method(String method) {
if (!HttpConstants.HTTP_METHODS.contains(method.toUpperCase())) { // support expressions also
method = evalKarateExpression(method).getAsString();
}
requestBuilder.method(method);
httpInvoke();
}
// extracted for mock proceed()
public Response httpInvoke() {
if (requestBuilder.isRetry()) {
httpInvokeWithRetries();
} else {
httpInvokeOnce();
}
requestBuilder.reset();
return response;
}
private void httpInvokeOnce() {
Map<String, Map> cookies = getOrEvalAsMap(config.getCookies());
if (cookies != null) {
requestBuilder.cookies(cookies.values());
}
Map<String, Object> headers;
if (config.getHeaders().isJsOrJavaFunction()) {
headers = getOrEvalAsMap(config.getHeaders(), requestBuilder.build());
} else {
headers = getOrEvalAsMap(config.getHeaders()); // avoid an extra http request build
}
if (headers != null) {
requestBuilder.headers(headers);
}
httpRequest = requestBuilder.build();
String perfEventName = null; // acts as a flag to report perf if not null
if (runtime.perfMode) {
perfEventName = runtime.featureRuntime.perfHook.getPerfEventName(httpRequest, runtime);
}
long startTime = System.currentTimeMillis();
httpRequest.setStartTime(startTime); // this may be fine-adjusted by actual http client
if (hooks != null) {
hooks.forEach(h -> h.beforeHttpCall(httpRequest, runtime));
}
try {
response = requestBuilder.client.invoke(httpRequest);
} catch (Exception e) {
long endTime = System.currentTimeMillis();
long responseTime = endTime - startTime;
String message = "http call failed after " + responseTime + " milliseconds for url: " + httpRequest.getUrl();
logger.error(e.getMessage() + ", " + message);
if (logger.isTraceEnabled()) {
String stacktrace = StringUtils.throwableToString(e);
if (stacktrace != null) {
logger.trace(stacktrace);
}
}
if (perfEventName != null) {
PerfEvent pe = new PerfEvent(startTime, endTime, perfEventName, 0);
capturePerfEvent(pe); // failure flag and message should be set by logLastPerfEvent()
}
throw new KarateException(message, e);
}
if (hooks != null) {
hooks.forEach(h -> h.afterHttpCall(httpRequest, response, runtime));
}
byte[] bytes = response.getBody();
Object body;
String responseType;
ResourceType resourceType = response.getResourceType();
if (resourceType != null && resourceType.isBinary()) {
responseType = "binary";
body = bytes;
} else {
try {
body = JsValue.fromBytes(bytes, true, resourceType);
} catch (Exception e) {
body = FileUtils.toString(bytes);
logger.warn("auto-conversion of response failed: {}", e.getMessage());
}
if (body instanceof Map || body instanceof List) {
responseType = "json";
} else if (body instanceof Node) {
responseType = "xml";
} else {
responseType = "string";
}
}
setVariable(RESPONSE_STATUS, response.getStatus());
setVariable(RESPONSE, body);
if (config.isLowerCaseResponseHeaders()) {
setVariable(RESPONSE_HEADERS, response.getHeadersWithLowerCaseNames());
} else {
setVariable(RESPONSE_HEADERS, response.getHeaders());
}
setHiddenVariable(RESPONSE_BYTES, bytes);
setHiddenVariable(RESPONSE_TYPE, responseType);
cookies = response.getCookies();
updateConfigCookies(cookies);
setHiddenVariable(RESPONSE_COOKIES, cookies);
startTime = httpRequest.getStartTime(); // in case it was re-adjusted by http client
final long endTime = httpRequest.getEndTime();
final long responseTime = endTime - startTime;
setHiddenVariable(REQUEST_TIME_STAMP, startTime);
setVariable(RESPONSE_TIME, responseTime);
response.setResponseTime(responseTime);
if (perfEventName != null) {
PerfEvent pe = new PerfEvent(startTime, endTime, perfEventName, response.getStatus());
capturePerfEvent(pe);
}
}
private void httpInvokeWithRetries() {
int maxRetries = config.getRetryCount();
int sleep = config.getRetryInterval();
int retryCount = 0;
while (true) {
if (retryCount == maxRetries) {
throw new KarateException("too many retry attempts: " + maxRetries);
}
if (retryCount > 0) {
try {
logger.debug("sleeping before retry #{}", retryCount);
Thread.sleep(sleep);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
httpInvokeOnce();
Variable v;
try {
v = evalKarateExpression(requestBuilder.getRetryUntil());
} catch (Exception e) {
logger.warn("retry condition evaluation failed: {}", e.getMessage());
v = Variable.NULL;
}
if (v.isTrue()) {
if (retryCount > 0) {
logger.debug("retry condition satisfied");
}
break;
} else {
logger.debug("retry condition not satisfied: {}", requestBuilder.getRetryUntil());
}
retryCount++;
}
}
public void status(int status) {
if (status != response.getStatus()) {
// make sure log masking is applied
String message = HttpLogger.getStatusFailureMessage(status, config, httpRequest, response);
setFailedReason(new KarateException(message));
}
}
public KeyStore getKeyStore(String trustStoreFile, String password, String type) {
if (trustStoreFile == null) {
return null;
}
char[] passwordChars = password == null ? null : password.toCharArray();
if (type == null) {
type = KeyStore.getDefaultType();
}
try {
KeyStore keyStore = KeyStore.getInstance(type);
InputStream is = fileReader.readFileAsStream(trustStoreFile);
keyStore.load(is, passwordChars);
logger.debug("key store key count for {}: {}", trustStoreFile, keyStore.size());
return keyStore;
} catch (Exception e) {
logger.error("key store init failed: {}", e.getMessage());
throw new RuntimeException(e);
}
}
// http mock ===============================================================
//
public void mockProceed(String requestUrlBase) {
String urlBase = requestUrlBase == null ? vars.get(REQUEST_URL_BASE).getValue() : requestUrlBase;
String uri = vars.get(REQUEST_URI).getValue();
String url = uri == null ? urlBase : urlBase + "/" + uri;
requestBuilder.url(url);
requestBuilder.params(vars.get(REQUEST_PARAMS).getValue());
requestBuilder.method(vars.get(REQUEST_METHOD).getValue());
requestBuilder.headers(vars.get(REQUEST_HEADERS).<Map>getValue());
requestBuilder.removeHeader(HttpConstants.HDR_CONTENT_LENGTH);
requestBuilder.body(vars.get(REQUEST).getValue());
if (requestBuilder.client instanceof ArmeriaHttpClient) {
Request mockRequest = MockHandler.LOCAL_REQUEST.get();
if (mockRequest != null) {
ArmeriaHttpClient client = (ArmeriaHttpClient) requestBuilder.client;
client.setRequestContext(mockRequest.getRequestContext());
}
}
httpInvoke();
}
public Map<String, Object> mockConfigureHeaders() {
return getOrEvalAsMap(config.getResponseHeaders());
}
public void mockAfterScenario() {
if (config.getAfterScenario().isJsOrJavaFunction()) {
executeFunction(config.getAfterScenario());
}
}
// websocket / async =======================================================
//
private List<WebSocketClient> webSocketClients;
private CompletableFuture SIGNAL = new CompletableFuture();
public WebSocketClient webSocket(WebSocketOptions options) {
WebSocketClient webSocketClient = new WebSocketClient(options, logger);
webSocketClient.setEngine(this);
if (webSocketClients == null) {
webSocketClients = new ArrayList();
}
webSocketClients.add(webSocketClient);
return webSocketClient;
}
public void signal(Object result) {
SIGNAL.complete(result);
}
public void listen(String exp) {
Variable v = evalKarateExpression(exp);
int timeout = v.getAsInt();
logger.debug("entered listen state with timeout: {}", timeout);
Object listenResult = null;
try {
listenResult = SIGNAL.get(timeout, TimeUnit.MILLISECONDS);
Thread.sleep(100); // IMPORTANT, else graal js complains
} catch (Exception e) {
logger.error("listen timed out: {}", e + "");
}
synchronized (JsValue.LOCK) {
setHiddenVariable(LISTEN_RESULT, listenResult);
logger.debug("exit listen state with result: {}", listenResult);
SIGNAL = new CompletableFuture();
}
}
public Command fork(boolean useLineFeed, List<String> args) {
return fork(useLineFeed, Collections.singletonMap("args", args));
}
public Command fork(boolean useLineFeed, String line) {
return fork(useLineFeed, Collections.singletonMap("line", line));
}
public Command fork(boolean useLineFeed, Map<String, Object> options) {
Boolean useShell = (Boolean) options.get("useShell");
if (useShell == null) {
useShell = false;
}
List<String> list = (List) options.get("args");
String[] args;
if (list == null) {
String line = (String) options.get("line");
if (line == null) {
throw new RuntimeException("'line' or 'args' is required");
}
args = Command.tokenize(line);
} else {
args = list.toArray(new String[list.size()]);
}
if (useShell) {
args = Command.prefixShellArgs(args);
}
String workingDir = (String) options.get("workingDir");
File workingFile = workingDir == null ? null : new File(workingDir);
Command command = new Command(useLineFeed, logger, null, null, workingFile, args);
Map env = (Map) options.get("env");
if (env != null) {
command.setEnvironment(env);
}
Boolean redirectErrorStream = (Boolean) options.get("redirectErrorStream");
if (redirectErrorStream != null) {
command.setRedirectErrorStream(redirectErrorStream);
}
Value funOut = (Value) options.get("listener");
if (funOut != null && funOut.canExecute()) {
command.setListener(new JsLambda(funOut));
}
Value funErr = (Value) options.get("errorListener");
if (funErr != null && funErr.canExecute()) {
command.setErrorListener(new JsLambda(funErr));
}
Boolean start = (Boolean) options.get("start");
if (start == null) {
start = true;
}
if (start) {
command.start();
}
return command;
}
// ui driver / robot =======================================================
//
protected Driver driver;
protected Plugin robot;
private void autoDef(Plugin plugin, String instanceName) {
for (String methodName : plugin.methodNames()) {
String invoke = instanceName + "." + methodName;
StringBuilder sb = new StringBuilder();
sb.append("(function(){ if (arguments.length == 0) return ").append(invoke).append("();")
.append(" if (arguments.length == 1) return ").append(invoke).append("(arguments[0]);")
.append(" if (arguments.length == 2) return ").append(invoke).append("(arguments[0], arguments[1]);")
.append(" return ").append(invoke).append("(arguments[0], arguments[1], arguments[2]) })");
setHiddenVariable(methodName, evalJs(sb.toString()));
}
}
public void driver(String exp) {
Variable v = evalKarateExpression(exp);
// re-create driver within a test if needed
// but user is expected to call quit() OR use the driver keyword with a JSON argument
if (driver == null || driver.isTerminated() || v.isMap()) {
Map<String, Object> options = config.getDriverOptions();
if (options == null) {
options = new HashMap();
}
options.put("target", config.getDriverTarget());
if (v.isMap()) {
options.putAll(v.getValue());
}
setDriver(DriverOptions.start(options, runtime));
}
if (v.isString()) {
driver.setUrl(v.getAsString());
}
}
public void robot(String exp) {
Variable v = evalKarateExpression(exp);
if (robot == null) {
Map<String, Object> options = config.getRobotOptions();
if (options == null) {
options = new HashMap();
}
if (v.isMap()) {
options.putAll(v.getValue());
} else if (v.isString()) {
options.put("window", v.getAsString());
}
try {
Class clazz = Class.forName("com.intuit.karate.robot.RobotFactory");
PluginFactory factory = (PluginFactory) clazz.newInstance();
robot = factory.create(runtime, options);
} catch (KarateException ke) {
throw ke;
} catch (Exception e) {
String message = "cannot instantiate robot, is 'karate-robot' included as a maven / gradle dependency ? " + e.getMessage();
logger.error(message);
throw new RuntimeException(message, e);
}
setRobot(robot);
}
}
public void setDriverToNull() {
this.driver = null;
}
public void setDriver(Driver driver) {
this.driver = driver;
setHiddenVariable(DRIVER, driver);
if (robot != null) {
logger.warn("'robot' is active, use 'driver.' prefix for driver methods");
return;
}
autoDef(driver, DRIVER);
setHiddenVariable(KEY, Key.INSTANCE);
}
public void setRobot(Plugin robot) { // TODO unify
this.robot = robot;
// robot.setContext(this);
setHiddenVariable(ROBOT, robot);
if (driver != null) {
logger.warn("'driver' is active, use 'robot.' prefix for robot methods");
return;
}
autoDef(robot, ROBOT);
setHiddenVariable(KEY, Key.INSTANCE);
}
public void stop(StepResult lastStepResult) {
if (runtime.caller.isSharedScope()) {
// TODO life-cycle this hand off
ScenarioEngine caller = runtime.caller.parentRuntime.engine;
if (driver != null) { // a called feature inited the driver
caller.setDriver(driver);
}
if (robot != null) {
caller.setRobot(robot);
}
caller.webSocketClients = webSocketClients;
// return, don't kill driver just yet
} else if (runtime.caller.depth == 0) { // end of top-level scenario (no caller)
if (webSocketClients != null) {
webSocketClients.forEach(WebSocketClient::close);
}
if (driver != null) { // TODO move this to Plugin.afterScenario()
DriverOptions options = driver.getOptions();
if (options.stop) {
driver.quit();
}
if (options.target != null) {
logger.debug("custom target configured, attempting stop()");
Map<String, Object> map = options.target.stop(runtime);
String video = (String) map.get("video");
embedVideo(video);
} else {
if (options.afterStop != null) {
Command.execLine(null, options.afterStop);
}
embedVideo(options.videoFile);
}
}
if (robot != null) {
robot.afterScenario();
}
}
}
private void embedVideo(String path) {
if (path != null) {
File videoFile = new File(path);
if (videoFile.exists()) {
Embed embed = runtime.embedVideo(videoFile);
logger.debug("appended video to report: {}", embed);
}
}
}
// doc =====================================================================
//
private KarateTemplateEngine templateEngine;
private ResourceResolver resourceResolver;
public void setResourceResolver(ResourceResolver resourceResolver) {
this.resourceResolver = resourceResolver;
}