How to use isDynamicBackground method of com.intuit.karate.core.ScenarioRuntime class

Best Karate code snippet using com.intuit.karate.core.ScenarioRuntime.isDynamicBackground

Source:ScenarioRuntime.java Github

copy

Full Screen

...102 this.background = background; // used only to check which steps remain103 magicVariables = initMagicVariables();104 result = new ScenarioResult(scenario);105 if (background != null) {106 if (!background.isDynamicBackground()) {107 HttpClient client = featureRuntime.suite.clientFactory.create(engine);108 engine.requestBuilder = background.engine.requestBuilder.copy(client);109 }110 result.addStepResults(background.result.getStepResults());111 Map<String, Variable> detached = background.engine.detachVariables();112 detached.forEach((k, v) -> engine.vars.put(k, v));113 }114 dryRun = featureRuntime.suite.dryRun;115 tags = scenario.getTagsEffective();116 reportDisabled = perfMode ? true : tags.valuesFor("report").isAnyOf("false");117 selectedForExecution = isSelectedForExecution(featureRuntime, scenario, tags);118 }119 public boolean isFailed() {120 return error != null || result.isFailed();121 }122 public boolean isIgnoringFailureSteps() {123 return ignoringFailureSteps;124 }125 public Step getCurrentStep() {126 return currentStep;127 }128 public boolean isStopped() {129 return stopped;130 }131 public boolean isDynamicBackground() {132 return scenario.isDynamic() && background == null;133 }134 public String getEmbedFileName(ResourceType resourceType) {135 String extension = resourceType == null ? null : resourceType.getExtension();136 return scenario.getUniqueId() + "_" + System.currentTimeMillis() + (extension == null ? "" : "." + extension);137 }138 public Embed saveToFileAndCreateEmbed(byte[] bytes, ResourceType resourceType) {139 File file = new File(featureRuntime.suite.reportDir + File.separator + getEmbedFileName(resourceType));140 FileUtils.writeToFile(file, bytes);141 return new Embed(file, resourceType);142 }143 public Embed embed(byte[] bytes, ResourceType resourceType) {144 if (embeds == null) {145 embeds = new ArrayList();146 }147 Embed embed = saveToFileAndCreateEmbed(bytes, resourceType);148 embeds.add(embed);149 return embed;150 }151 public Embed embedVideo(File file) {152 StepResult stepResult = result.addFakeStepResult("[video]", null);153 Embed embed = saveToFileAndCreateEmbed(FileUtils.toBytes(file), ResourceType.MP4);154 stepResult.addEmbed(embed);155 return embed;156 }157 private List<FeatureResult> callResults;158 public void addCallResult(FeatureResult fr) {159 if (callResults == null) {160 callResults = new ArrayList();161 }162 callResults.add(fr);163 }164 public LogAppender getLogAppender() {165 return logAppender;166 }167 private List<Step> steps;168 private List<Embed> embeds;169 private StepResult currentStepResult;170 private Step currentStep;171 private Throwable error;172 private boolean configFailed;173 private boolean skipped; // beforeScenario hook only174 private boolean stopped;175 private boolean aborted;176 private int stepIndex;177 public void stepBack() {178 stopped = false;179 stepIndex -= 2;180 if (stepIndex < 0) {181 stepIndex = 0;182 }183 }184 public void stepReset() {185 stopped = false;186 stepIndex--;187 if (stepIndex < 0) { // maybe not required188 stepIndex = 0;189 }190 }191 public void stepProceed() {192 stopped = false;193 }194 private int nextStepIndex() {195 return stepIndex++;196 }197 public Result evalAsStep(String expression) {198 Step evalStep = new Step(scenario, -1);199 try {200 evalStep.parseAndUpdateFrom(expression);201 } catch (Exception e) {202 return Result.failed(0, e, evalStep);203 }204 return StepRuntime.execute(evalStep, actions);205 }206 public boolean hotReload() {207 boolean success = false;208 Feature feature = scenario.getFeature();209 feature = Feature.read(feature.getResource());210 for (Step oldStep : steps) {211 Step newStep = feature.findStepByLine(oldStep.getLine());212 if (newStep == null) {213 continue;214 }215 String oldText = oldStep.getText();216 String newText = newStep.getText();217 if (!oldText.equals(newText)) {218 try {219 oldStep.parseAndUpdateFrom(newStep.getText());220 logger.info("hot reloaded line: {} - {}", newStep.getLine(), newStep.getText());221 success = true;222 } catch (Exception e) {223 logger.warn("failed to hot reload step: {}", e.getMessage());224 }225 }226 }227 return success;228 }229 public Map<String, Object> getScenarioInfo() {230 Map<String, Object> info = new HashMap(5);231 File featureFile = featureRuntime.feature.getResource().getFile();232 if (featureFile != null) {233 info.put("featureDir", featureFile.getParent());234 info.put("featureFileName", featureFile.getName());235 }236 info.put("scenarioName", scenario.getName());237 info.put("scenarioDescription", scenario.getDescription());238 String errorMessage = error == null ? null : error.getMessage();239 info.put("errorMessage", errorMessage);240 return info;241 }242 protected void logError(String message) {243 if (currentStep != null) {244 message = currentStep.getDebugInfo()245 + "\n" + currentStep.toString()246 + "\n" + message;247 }248 logger.error("{}", message);249 }250 private Map<String, Object> initMagicVariables() {251 Map<String, Object> map = new HashMap();252 if (!caller.isNone()) {253 // karate principle: parent variables are always "visible"254 // so we inject the parent variables255 // but they will be over-written by what is local to this scenario256 if (caller.isSharedScope()) {257 map.putAll(caller.parentRuntime.magicVariables);258 } else {259 // the shallow clone of variables is important260 // otherwise graal / js functions in calling context get corrupted261 caller.parentRuntime.engine.vars.forEach((k, v) -> map.put(k, v == null ? null : v.copy(false).getValue()));262 // shallow copy magicVariables263 map.putAll((Map<String, Object>) caller.parentRuntime.engine.shallowClone(caller.parentRuntime.magicVariables));264 }265 map.put("__arg", caller.arg == null ? null : caller.arg.getValue());266 map.put("__loop", caller.getLoopIndex());267 }268 if (scenario.isOutlineExample() && !this.isDynamicBackground()) { // init examples row magic variables269 Map<String, Object> exampleData = scenario.getExampleData();270 map.putAll(exampleData);271 map.put("__row", exampleData);272 map.put("__num", scenario.getExampleIndex());273 }274 return map;275 }276 private void evalConfigJs(String js, String displayName) {277 if (js == null || configFailed) {278 return;279 }280 try {281 Variable fun = engine.evalJs("(" + js + ")");282 if (!fun.isJsFunction()) {283 logger.warn("not a valid js function: {}", displayName);284 return;285 }286 Map<String, Object> map = engine.getOrEvalAsMap(fun);287 engine.setVariables(map);288 } catch (Exception e) {289 String message = ">> " + scenario.getDebugInfo() + "\n>> " + displayName + " failed\n>> " + e.getMessage();290 error = JsEngine.fromJsEvalException(js, e, message);291 stopped = true;292 configFailed = true;293 }294 }295 private static boolean isSelectedForExecution(FeatureRuntime fr, Scenario scenario, Tags tags) {296 Feature feature = scenario.getFeature();297 int callLine = feature.getCallLine();298 if (callLine != -1) {299 int sectionLine = scenario.getSection().getLine();300 int scenarioLine = scenario.getLine();301 if (callLine == sectionLine || callLine == scenarioLine) {302 fr.logger.info("found scenario at line: {}", callLine);303 return true;304 }305 fr.logger.trace("skipping scenario at line: {}, needed: {}", scenario.getLine(), callLine);306 return false;307 }308 String callName = feature.getCallName();309 if (callName != null) {310 if (scenario.getName().matches(callName)) {311 fr.logger.info("found scenario at line: {} - {}", scenario.getLine(), callName);312 return true;313 }314 fr.logger.trace("skipping scenario at line: {} - {}, needed: {}", scenario.getLine(), scenario.getName(), callName);315 return false;316 }317 String callTag = feature.getCallTag();318 if (callTag != null && (!fr.caller.isNone() || fr.perfHook != null)) {319 // only if this is a legit "call" or a gatling "call by tag"320 if (tags.contains(callTag)) {321 fr.logger.info("{} - call by tag at line {}: {}", fr, scenario.getLine(), callTag);322 return true;323 }324 fr.logger.trace("skipping scenario at line: {} with call by tag effective: {}", scenario.getLine(), callTag);325 return false;326 }327 if (fr.caller.isNone()) {328 if (tags.evaluate(fr.suite.tagSelector, fr.suite.env)) {329 fr.logger.trace("matched scenario at line: {} with tags effective: {}", scenario.getLine(), tags.getTags());330 return true;331 }332 fr.logger.trace("skipping scenario at line: {} with tags effective: {}", scenario.getLine(), tags.getTags());333 return false;334 } else {335 return true; // when called, tags are ignored, all scenarios will be run336 }337 }338 //==========================================================================339 //340 public void beforeRun() {341 if (isDynamicBackground()) {342 steps = scenario.getBackgroundSteps();343 } else {344 steps = background == null ? scenario.getStepsIncludingBackground() : scenario.getSteps();345 }346 ScenarioEngine.set(engine);347 engine.init();348 engine.getConfig().attach(engine.JS);349 if (this.background != null) {350 ScenarioEngine backgroundEngine = background.engine;351 if (backgroundEngine.driver != null) {352 engine.setDriver(backgroundEngine.driver);353 }354 if (backgroundEngine.robot != null) {355 engine.setRobot(backgroundEngine.robot);356 }357 }358 result.setExecutorName(Thread.currentThread().getName());359 result.setStartTime(System.currentTimeMillis());360 if (!dryRun) {361 if (caller.isNone() && !caller.isKarateConfigDisabled()) {362 // evaluate config js, variables above will apply !363 evalConfigJs(featureRuntime.suite.karateBase, "karate-base.js");364 evalConfigJs(featureRuntime.suite.karateConfig, "karate-config.js");365 evalConfigJs(featureRuntime.suite.karateConfigEnv, "karate-config-" + featureRuntime.suite.env + ".js");366 }367 if (isDynamicBackground()) {368 featureRuntime.suite.hooks.forEach(h -> h.beforeBackground(this));369 if (featureRuntime.suite.debugMode) {370 skipped = !featureRuntime.suite.hooks.stream()371 .filter(DebugThread.class::isInstance)372 .map(h -> h.beforeScenario(this))373 .reduce(Boolean.TRUE, Boolean::logicalAnd);374 }375 } else {376 skipped = !featureRuntime.suite.hooks.stream()377 .map(h -> h.beforeScenario(this))378 .reduce(Boolean.TRUE, Boolean::logicalAnd);379 }380 if (skipped) {381 logger.debug("beforeScenario hook returned false, will skip scenario: {}", scenario);382 }383 }384 if (!skipped && !isDynamicBackground()) {385 // don't evaluate names when running the background section386 evaluateScenarioName();387 }388 }389 @Override390 public void run() {391 boolean reRun = false;392 try { // make sure we call afterRun() even on crashes393 // and operate countdown latches, else we may hang the parallel runner394 if (steps == null) {395 beforeRun();396 }397 if (skipped) {398 return;399 }400 int count = steps.size();401 int index = 0;402 reRun = stepIndex >= count;403 while ((index = nextStepIndex()) < count) {404 currentStep = steps.get(index);405 execute(currentStep);406 if (currentStepResult != null) { // can be null if debug step-back or hook skip407 result.addStepResult(currentStepResult);408 }409 }410 } catch (Exception e) {411 if (currentStepResult != null) {412 result.addStepResult(currentStepResult);413 }414 logError("scenario [run] failed\n" + StringUtils.throwableToString(e));415 currentStepResult = result.addFakeStepResult("scenario [run] failed", e);416 } finally {417 if (isDynamicBackground() && !reRun && !skipped) {418 featureRuntime.suite.hooks.forEach(h -> h.afterBackground(this));419 // if it's a dynamic scenario running under the debugger420 // we still want to execute the afterScenario() hook of the debugger server421 // in the background section422 if (featureRuntime.suite.debugMode) {423 // allow debugging background section424 featureRuntime.suite.hooks.stream()425 .filter(DebugThread.class::isInstance)426 .forEach(h -> h.afterScenario(this));427 }428 } else if (!isDynamicBackground() && !skipped) { // don't add "fake" scenario to feature results429 afterRun();430 }431 if (caller.isNone()) {432 logAppender.close(); // reclaim memory433 }434 }435 }436 public StepResult execute(Step step) {437 if (!stopped && !dryRun) {438 boolean shouldExecute = true;439 for (RuntimeHook hook : featureRuntime.suite.hooks) {440 if (!hook.beforeStep(step, this)) {441 shouldExecute = false;442 }...

Full Screen

Full Screen

isDynamicBackground

Using AI Code Generation

copy

Full Screen

1* def isDynamicBackground = com.intuit.karate.core.ScenarioRuntime.isDynamicBackground()2* def isDynamicBackground = com.intuit.karate.core.ScenarioRuntime.isDynamicBackground()3* def isDynamicBackground = com.intuit.karate.core.ScenarioRuntime.isDynamicBackground()4* def isDynamicBackground = com.intuit.karate.core.ScenarioRuntime.isDynamicBackground()5* def isDynamicBackground = com.intuit.karate.core.ScenarioRuntime.isDynamicBackground()6* def isDynamicBackground = com.intuit.karate.core.ScenarioRuntime.isDynamicBackground()7* def isDynamicBackground = com.intuit.karate.core.ScenarioRuntime.isDynamicBackground()8* def isDynamicBackground = com.intuit.karate.core.ScenarioRuntime.isDynamicBackground()9* def isDynamicBackground = com.intuit.karate.core.ScenarioRuntime.isDynamicBackground()10* def isDynamicBackground = com.intuit.karate.core.ScenarioRuntime.isDynamicBackground()11* def isDynamicBackground = com.intuit.karate.core.ScenarioRuntime.isDynamicBackground()

Full Screen

Full Screen

isDynamicBackground

Using AI Code Generation

copy

Full Screen

1def config = karate.getConfig()2karate.configure(config)3karate.isDynamicBackground(true)4karate.isDynamicBackground(false)5karate.isDynamicBackground()6karate.isDynamicBackground()

Full Screen

Full Screen

isDynamicBackground

Using AI Code Generation

copy

Full Screen

1* def runtime = karate.get('runtime')2* def isDynamic = runtime.isDynamicBackground()3* def backgroundSteps = runtime.getBackgroundSteps()4* def background = runtime.getBackground()5* def backgroundSteps2 = background.getSteps()6* def firstBackgroundStep = backgroundSteps2.get(0)

Full Screen

Full Screen

isDynamicBackground

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.core.ScenarioRuntime2import com.intuit.karate.core.FeatureRuntime3import com.intuit.karate.core.FeatureRuntimeBuilder4import com.intuit.karate.core.Feature5import com.intuit.karate.core.FeatureParser6import com.intuit.karate.core.FeatureBuilder7import com.intuit.karate.core.FeatureContext8import com.intuit.karate.core.FeatureInfo9import com.intuit.karate.core.FeatureResult10import com.intuit.karate.core.FeatureWrapper11import com.intuit.karate.core.FeatureWrapperBuilder12import com.intuit.karate.core.FeatureWrapperResult13import com.intuit.karate.core.FeatureWrapperResultBuilder14import com.intuit.karate.core.FeatureWrapperResultBuilder.*15import com.intuit.karate.core.FeatureWr

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful