How to use StageState method of com.tngtech.jgiven.impl.ScenarioExecutor class

Best JGiven code snippet using com.tngtech.jgiven.impl.ScenarioExecutor.StageState

Source:ScenarioExecutor.java Github

copy

Full Screen

...49 * Whether life cycle methods should be executed.50 * This is only false for scenarios that are annotated with @NotImplementedYet51 */52 private boolean executeLifeCycleMethods = true;53 protected final Map<Class<?>, StageState> stages = new LinkedHashMap<>();54 private final List<Object> scenarioRules = new ArrayList<>();55 private final ValueInjector injector = new ValueInjector();56 private StageCreator stageCreator = createStageCreator(new ByteBuddyStageClassCreator());57 private ScenarioListener listener = new NoOpScenarioListener();58 protected final StageTransitionHandler stageTransitionHandler = new StageTransitionHandlerImpl();59 protected final StepInterceptorImpl methodInterceptor =60 new StepInterceptorImpl(this, listener, stageTransitionHandler);61 /**62 * Set if an exception was thrown during the execution of the scenario and63 * suppressStepExceptions is true.64 */65 private Throwable failedException;66 private boolean failIfPass;67 /**68 * Whether exceptions caught while executing steps should be thrown at the end69 * of the scenario. Only relevant if suppressStepExceptions is true, because otherwise70 * the exceptions are not caught at all.71 */72 private boolean suppressExceptions;73 /**74 * Whether exceptions thrown while executing steps should be suppressed or not.75 * Only relevant for normal executions of scenarios.76 */77 private boolean suppressStepExceptions = true;78 /**79 * Create a new ScenarioExecutor instance.80 */81 public ScenarioExecutor() {82 injector.injectValueByType(ScenarioExecutor.class, this);83 injector.injectValueByType(CurrentStep.class, new StepAccessImpl());84 injector.injectValueByType(CurrentScenario.class, new ScenarioAccessImpl());85 }86 class StepAccessImpl implements CurrentStep {87 @Override88 public void addAttachment(Attachment attachment) {89 listener.attachmentAdded(attachment);90 }91 @Override92 public void setExtendedDescription(String extendedDescription) {93 listener.extendedDescriptionUpdated(extendedDescription);94 }95 @Override96 public void setName(String name) {97 listener.stepNameUpdated(name);98 }99 @Override100 public void setComment(String comment) {101 listener.stepCommentUpdated(comment);102 }103 }104 class ScenarioAccessImpl implements CurrentScenario {105 @Override106 public void addTag(Class<? extends Annotation> annotationClass, String... values) {107 listener.tagAdded(annotationClass, values);108 }109 }110 class StageTransitionHandlerImpl implements StageTransitionHandler {111 @Override112 public void enterStage(Object parentStage, Object childStage) throws Throwable {113 if (parentStage == childStage || currentTopLevelStage == childStage) { // NOSONAR: reference comparison OK114 return;115 }116 // if currentStage == null, this means that no stage at117 // all has been executed, thus we call all beforeScenarioMethods118 if (currentTopLevelStage == null) {119 ensureBeforeScenarioMethodsAreExecuted();120 } else {121 // in case parentStage == null, this is the first top-level122 // call on this stage, thus we have to call the afterStage methods123 // from the current top level stage124 if (parentStage == null) {125 executeAfterStageMethods(currentTopLevelStage);126 readScenarioState(currentTopLevelStage);127 } else {128 // as the parent stage is not null, we have a true child call129 // thus we have to read the state from the parent stage130 readScenarioState(parentStage);131 // if there has been a child stage that was executed before132 // and the new child stage is different, we have to execute133 // the after stage methods of the previous child stage134 StageState stageState = getStageState(parentStage);135 if (stageState.currentChildStage != null && stageState.currentChildStage != childStage136 && !afterStageMethodsCalled(stageState.currentChildStage)) {137 updateScenarioState(stageState.currentChildStage);138 executeAfterStageMethods(stageState.currentChildStage);139 readScenarioState(stageState.currentChildStage);140 }141 stageState.currentChildStage = childStage;142 }143 }144 updateScenarioState(childStage);145 executeBeforeStageMethods(childStage);146 if (parentStage == null) {147 currentTopLevelStage = childStage;148 }149 }150 @Override151 public void leaveStage(Object parentStage, Object childStage) throws Throwable {152 if (parentStage == childStage || parentStage == null) {153 return;154 }155 readScenarioState(childStage);156 // in case we leave a child stage that itself had a child stage157 // we have to execute the after stage method of that transitive child158 StageState childState = getStageState(childStage);159 if (childState.currentChildStage != null) {160 updateScenarioState(childState.currentChildStage);161 if (!getStageState(childState.currentChildStage).allAfterStageMethodsHaveBeenExecuted()) {162 executeAfterStageMethods(childState.currentChildStage);163 readScenarioState(childState.currentChildStage);164 updateScenarioState(childStage);165 }166 childState.currentChildStage = null;167 }168 updateScenarioState(parentStage);169 }170 }171 @SuppressWarnings("unchecked")172 <T> T addStage(Class<T> stageClass) {173 if (stages.containsKey(stageClass)) {174 return (T) stages.get(stageClass).instance;175 }176 T result = stageCreator.createStage(stageClass, methodInterceptor);177 methodInterceptor.enableMethodInterception(true);178 stages.put(stageClass, new StageState(result, methodInterceptor));179 gatherRules(result);180 injectStages(result);181 return result;182 }183 public void addIntroWord(String word) {184 listener.introWordAdded(word);185 }186 @SuppressWarnings("unchecked")187 private void gatherRules(Object stage) {188 for (Field field : FieldCache.get(stage.getClass()).getFieldsWithAnnotation(ScenarioRule.class)) {189 log.debug("Found rule in field {} ", field);190 try {191 scenarioRules.add(field.get(stage));192 } catch (IllegalAccessException e) {193 throw new RuntimeException("Error while reading field " + field, e);194 }195 }196 }197 private <T> void updateScenarioState(T t) {198 try {199 injector.updateValues(t);200 } catch (JGivenMissingRequiredScenarioStateException e) {201 if (!suppressExceptions) {202 throw e;203 }204 }205 }206 private boolean afterStageMethodsCalled(Object stage) {207 return getStageState(stage).allAfterStageMethodsHaveBeenExecuted();208 }209 //TODO: nicer stage search?210 // What may happen if there is a common superclass to two distinct implementations? Is that even possible?211 StageState getStageState(Object stage) {212 Class<?> stageClass = stage.getClass();213 StageState stageState = stages.get(stageClass);214 while (stageState == null && stageClass != stageClass.getSuperclass()) {215 stageState = stages.get(stageClass);216 stageClass = stageClass.getSuperclass();217 }218 return stageState;219 }220 private void ensureBeforeScenarioMethodsAreExecuted() throws Throwable {221 if (state != State.INIT) {222 return;223 }224 state = STARTED;225 methodInterceptor.enableMethodInterception(false);226 try {227 for (Object rule : scenarioRules) {228 invokeRuleMethod(rule, "before");229 }230 beforeScenarioMethodsExecuted = true;231 for (StageState stage : stages.values()) {232 executeBeforeScenarioMethods(stage.instance);233 }234 } catch (Throwable e) {235 failed(e);236 finished();237 throw e;238 }239 methodInterceptor.enableMethodInterception(true);240 }241 private void invokeRuleMethod(Object rule, String methodName) throws Throwable {242 if (!executeLifeCycleMethods) {243 return;244 }245 Optional<Method> optionalMethod = ReflectionUtil.findMethodTransitively(rule.getClass(), methodName);246 if (!optionalMethod.isPresent()) {247 log.debug("Class {} has no {} method, but was used as ScenarioRule!", rule.getClass(), methodName);248 return;249 }250 try {251 ReflectionUtil.invokeMethod(rule, optionalMethod.get(), " of rule class " + rule.getClass().getName());252 } catch (JGivenUserException e) {253 throw e.getCause();254 }255 }256 private void executeBeforeScenarioMethods(Object stage) throws Throwable {257 getStageState(stage).executeBeforeScenarioMethods(!executeLifeCycleMethods);258 }259 private void executeBeforeStageMethods(Object stage) throws Throwable {260 getStageState(stage).executeBeforeStageMethods(!executeLifeCycleMethods);261 }262 private void executeAfterStageMethods(Object stage) throws Throwable {263 getStageState(stage).executeAfterStageMethods(!executeLifeCycleMethods);264 }265 private void executeAfterScenarioMethods(Object stage) throws Throwable {266 getStageState(stage).executeAfterScenarioMethods(!executeLifeCycleMethods);267 }268 public void readScenarioState(Object object) {269 injector.readValues(object);270 }271 /**272 * Used for DI frameworks to inject values into stages.273 */274 public void wireSteps(CanWire canWire) {275 for (StageState steps : stages.values()) {276 canWire.wire(steps.instance);277 }278 }279 /**280 * Has to be called when the scenario is finished in order to execute after methods.281 */282 public void finished() throws Throwable {283 if (state == FINISHED) {284 return;285 }286 State previousState = state;287 state = FINISHED;288 methodInterceptor.enableMethodInterception(false);289 try {290 if (previousState == STARTED) {291 callFinishLifeCycleMethods();292 }293 } finally {294 listener.scenarioFinished();295 }296 }297 private void callFinishLifeCycleMethods() throws Throwable {298 Throwable firstThrownException = failedException;299 if (beforeScenarioMethodsExecuted) {300 try {301 if (currentTopLevelStage != null) {302 executeAfterStageMethods(currentTopLevelStage);303 }304 } catch (Exception e) {305 firstThrownException = logAndGetFirstException(firstThrownException, e);306 }307 for (StageState stage : reverse(newArrayList(stages.values()))) {308 try {309 executeAfterScenarioMethods(stage.instance);310 } catch (Exception e) {311 firstThrownException = logAndGetFirstException(firstThrownException, e);312 }313 }314 }315 for (Object rule : reverse(scenarioRules)) {316 try {317 invokeRuleMethod(rule, "after");318 } catch (Exception e) {319 firstThrownException = logAndGetFirstException(firstThrownException, e);320 }321 }322 failedException = firstThrownException;323 if (!suppressExceptions && failedException != null) {324 throw failedException;325 }326 if (failIfPass && failedException == null) {327 throw new FailIfPassedException();328 }329 }330 private Throwable logAndGetFirstException(Throwable firstThrownException, Throwable newException) {331 log.error(newException.getMessage(), newException);332 return firstThrownException == null ? newException : firstThrownException;333 }334 /**335 * Initialize the fields annotated with {@link ScenarioStage} in the test class.336 */337 @SuppressWarnings("unchecked")338 public void injectStages(Object stage) {339 for (Field field : FieldCache.get(stage.getClass()).getFieldsWithAnnotation(ScenarioStage.class)) {340 Object steps = addStage(field.getType());341 ReflectionUtil.setField(field, stage, steps, ", annotated with @ScenarioStage");342 }343 }344 public boolean hasFailed() {345 return failedException != null;346 }347 public Throwable getFailedException() {348 return failedException;349 }350 public void setFailedException(Exception e) {351 failedException = e;352 }353 /**354 * Handle ocurred exception and continue.355 */356 public void failed(Throwable e) {357 if (hasFailed()) {358 log.error(e.getMessage(), e);359 } else {360 if (!failIfPass) {361 listener.scenarioFailed(e);362 }363 methodInterceptor.disableMethodExecution();364 failedException = e;365 }366 }367 /**368 * Starts a scenario with the given description.369 *370 * @param description the description of the scenario371 */372 public void startScenario(String description) {373 listener.scenarioStarted(description);374 }375 /**376 * Starts the scenario with the given method and arguments.377 * Derives the description from the method name.378 *379 * @param method the method that started the scenario380 * @param arguments the test arguments with their parameter names381 */382 public void startScenario(Class<?> testClass, Method method, List<NamedArgument> arguments) {383 listener.scenarioStarted(testClass, method, arguments);384 if (Config.config().dryRun()) {385 methodInterceptor.setDefaultInvocationMode(InvocationMode.PENDING);386 methodInterceptor.disableMethodExecution();387 executeLifeCycleMethods = false;388 suppressExceptions = true;389 } else {390 Pending annotation = extractPendingAnnotation(method);391 if (annotation == null) {392 methodInterceptor.setSuppressExceptions(suppressStepExceptions);393 } else {394 if (annotation.failIfPass()) {395 failIfPass();396 } else {397 methodInterceptor.setDefaultInvocationMode(InvocationMode.PENDING);398 if (!annotation.executeSteps()) {399 methodInterceptor.disableMethodExecution();400 executeLifeCycleMethods = false;401 }402 }403 suppressExceptions = true;404 }405 }406 }407 private Pending extractPendingAnnotation(Method method) {408 if (method.isAnnotationPresent(Pending.class)) {409 return method.getAnnotation(Pending.class);410 }411 if (method.getDeclaringClass().isAnnotationPresent(Pending.class)) {412 return method.getDeclaringClass().getAnnotation(Pending.class);413 }414 return null;415 }416 public void setListener(ScenarioListener listener) {417 this.listener = listener;418 methodInterceptor.setScenarioListener(listener);419 }420 public void failIfPass() {421 failIfPass = true;422 }423 public void setSuppressStepExceptions(boolean suppressStepExceptions) {424 this.suppressStepExceptions = suppressStepExceptions;425 }426 public void setSuppressExceptions(boolean suppressExceptions) {427 this.suppressExceptions = suppressExceptions;428 }429 public void addSection(String sectionTitle) {430 listener.sectionAdded(sectionTitle);431 }432 public void setStageCreator(StageCreator stageCreator) {433 this.stageCreator = stageCreator;434 }435 public void setStageClassCreator(StageClassCreator stageClassCreator) {436 this.stageCreator = createStageCreator(stageClassCreator);437 }438 private StageCreator createStageCreator(StageClassCreator stageClassCreator) {439 return new DefaultStageCreator(new CachingStageClassCreator(stageClassCreator));440 }441 private static class StageState extends StageLifecycleManager {442 final Object instance;443 Object currentChildStage;444 private StageState(Object instance, StepInterceptorImpl methodInterceptor) {445 super(instance, methodInterceptor);446 this.instance = instance;447 }448 }449}...

Full Screen

Full Screen

Source:MockScenarioExecutor.java Github

copy

Full Screen

...26 result = (T) constructor.newInstance(constructorParam);27 }28 }29 setStepInterceptor(result, methodInterceptor);30 stages.put(type, createStageState(result));31 return result;32 } catch (Error e) {33 throw e;34 } catch (Exception e) {35 throw new RuntimeException("Error while trying to create an instance of class " + type, e);36 }37 }38 protected StageState createStageState(Object instance) throws IllegalAccessException, InvocationTargetException, InstantiationException {39 Constructor<?> constructor = StageState.class.getDeclaredConstructors()[0];40 constructor.setAccessible(true);41 return (StageState) constructor.newInstance(instance);42 }43 protected <T> void setStepInterceptor(44 T result,45 StepInterceptor stepInterceptor46 ) {47 ((StageInterceptorInternal) result).__jgiven_setStepInterceptor(stepInterceptor);48 }49 @SuppressWarnings("unchecked")50 public void injectStages(Object stage) {51 for (Field field : FieldCache.get(stage.getClass())52 .getFieldsWithAnnotation(ScenarioStage.class)) {53 Object steps = addStage(field.getType());54 ReflectionUtil.setField(field, stage, steps, ", annotated with @ScenarioStage");55 }...

Full Screen

Full Screen

StageState

Using AI Code Generation

copy

Full Screen

1import com.tngtech.jgiven.Stage;2import com.tngtech.jgiven.annotation.As;3import com.tngtech.jgiven.annotation.ExpectedScenarioState;4import com.tngtech.jgiven.annotation.ProvidedScenarioState;5import com.tngtech.jgiven.impl.ScenarioExecutor;6public class WhenSomeAction extends Stage<WhenSomeAction> {7 ScenarioExecutor scenarioExecutor;8 String state;9 @As("I do something")10 public WhenSomeAction i_do_something() {11 state = scenarioExecutor.getStageState(StageOne.class);12 return self();13 }14}15import com.tngtech.jgiven.Stage;16import com.tngtech.jgiven.annotation.As;17import com.tngtech.jgiven.annotation.ExpectedScenarioState;18import com.tngtech.jgiven.annotation.ProvidedScenarioState;19import com.tngtech.jgiven.impl.ScenarioExecutor;20public class ThenSomeOutcome extends Stage<ThenSomeOutcome> {21 ScenarioExecutor scenarioExecutor;22 String state;23 @As("I see the outcome")24 public ThenSomeOutcome i_see_the_outcome() {25 state = scenarioExecutor.getStageState(StageOne.class);26 return self();27 }28}29import com.tngtech.jgiven.Stage;30import com.tngtech.jgiven.annotation.As;31import com.tngtech.jgiven.annotation.ExpectedScenarioState;32import com.tngtech.jgiven.annotation.ProvidedScenarioState;33import com.tngtech.jgiven.impl.ScenarioExecutor;34public class StageOne extends Stage<StageOne> {35 ScenarioExecutor scenarioExecutor;36 String state;37 @As("I am in stage one")38 public StageOne i_am_in_stage_one() {39 state = "stage one";40 return self();41 }42}

Full Screen

Full Screen

StageState

Using AI Code Generation

copy

Full Screen

1package com.tngtech.jgiven.examples;2import com.tngtech.jgiven.Stage;3import com.tngtech.jgiven.annotation.ExpectedScenarioState;4import com.tngtech.jgiven.annotation.ProvidedScenarioState;5import com.tngtech.jgiven.impl.ScenarioExecutor;6import com.tngtech.jgiven.impl.StageState;7public class StageStateExample extends Stage<StageStateExample> {8 int result;9 int a;10 int b;11 public StageStateExample I_add_$_and_$_( int a, int b ) {12 result = a + b;13 return self();14 }15 public StageStateExample the_result_is( int result ) {16 assertThat( this.result ).isEqualTo( result );17 return self();18 }19 public StageStateExample state_of_stage_is( StageState state ) {20 assertThat( ScenarioExecutor.getStageState( self() ) ).isEqualTo( state );21 return self();22 }23}24package com.tngtech.jgiven.examples;25import com.tngtech.jgiven.junit5.SimpleScenarioTest;26import org.junit.jupiter.api.Test;27public class StageStateExampleTest extends SimpleScenarioTest<StageStateExample> {28 public void the_state_of_a_stage_can_be_found_out() {29 given().a_$_and_$( 1, 2 )30 .and().state_of_stage_is( StageState.UNSTARTED )31 .when().I_add_$_and_$( 1, 2 )32 .and().state_of_stage_is( StageState.FINISHED )33 .then().the_result_is( 4 )34 .and().state_of_stage_is( StageState.FINISHED );35 }36}37package com.tngtech.jgiven.examples;38import com.tngtech.jgiven.Stage;39import com.tngtech.jgiven.annotation.ExpectedScenarioState;40import com.tngtech.jgiven.annotation.ProvidedScenarioState;41import com.tngtech

Full Screen

Full Screen

StageState

Using AI Code Generation

copy

Full Screen

1package com.jgiven.test;2import org.junit.Test;3import com.tngtech.jgiven.Stage;4import com.tngtech.jgiven.StageState;5import com.tngtech.jgiven.annotation.Hidden;6import com.tngtech.jgiven.annotation.Quoted;7import com.tngtech.jgiven.annotation.ScenarioState;8import com.tngtech.jgiven.annotation.ScenarioStage;9import com.tngtech.jgiven.impl.ScenarioExecutor;10import com.tngtech.jgiven.junit.ScenarioTest;11public class JGivenTest extends ScenarioTest<GivenTest, WhenTest, ThenTest> {12 public void test() {13 GivenTest given = given();14 WhenTest when = when();15 ThenTest then = then();16 given.a_string("Test");17 when.the_string_is_reversed();18 then.the_result_should_be("tseT");19 }20 public static class GivenTest extends Stage<GivenTest> {21 String string;22 public GivenTest a_string(@Quoted String string) {23 this.string = string;24 return self();25 }26 }27 public static class WhenTest extends Stage<WhenTest> {28 ThenTest then;29 String string;30 public WhenTest the_string_is_reversed() {31 then.the_result_should_be(new StringBuilder(string).reverse().toString());32 return self();33 }34 }35 public static class ThenTest extends Stage<ThenTest> {36 String result;37 public ThenTest the_result_should_be(@Quoted String result) {38 assertThat(this.result).isEqualTo(result);39 return self();40 }41 }42}43package com.jgiven.test;44import org.junit.Test;45import com.tngtech.jgiven.Stage;46import com.tngtech.jgiven.StageState;47import com.tngtech.jgiven.annotation.Hidden;48import com.tngtech.jgiven.annotation.Quoted;49import com.tngtech.jgiven.annotation.ScenarioState;50import com.tngtech.jgiven.annotation.ScenarioStage;51import com.tngtech.jgiven.impl.ScenarioExecutor;52import

Full Screen

Full Screen

StageState

Using AI Code Generation

copy

Full Screen

1public class StageStateTest {2 public void test() {3 ScenarioExecutor executor = new ScenarioExecutor();4 ScenarioState state = executor.getScenarioState();5 System.out.println("State:" + state);6 }7}

Full Screen

Full Screen

StageState

Using AI Code Generation

copy

Full Screen

1package com.tngtech.jgiven.tests;2import java.lang.reflect.InvocationTargetException;3import java.lang.reflect.Method;4import org.junit.Test;5import com.tngtech.jgiven.Stage;6import com.tngtech.jgiven.annotation.Hidden;7import com.tngtech.jgiven.annotation.ProvidedScenarioState;8import com.tngtech.jgiven.annotation.ScenarioState;9import com.tngtech.jgiven.impl.ScenarioExecutor;10import com.tngtech.jgiven.junit.SimpleScenarioTest;11public class Test1 extends SimpleScenarioTest<GivenTest1, WhenTest1, ThenTest1> {12public void test1() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {13 given().a_given_step();14 when().a_when_step();15 then().a_then_step();16 ScenarioExecutor executor = (ScenarioExecutor) getScenario();17 Method stageState = executor.getClass().getDeclaredMethod("stageState");18 stageState.setAccessible(true);19 String state = (String) stageState.invoke(executor);20 System.out.println("Current stage state is " + state);21}22}23package com.tngtech.jgiven.tests;24import java.lang.reflect.InvocationTargetException;25import java.lang.reflect.Method;26import org.junit.Test;27import com.tngtech.jgiven.Stage;28import com.tngtech.jgiven.annotation.Hidden;29import com.tngtech.jgiven.annotation.ProvidedScenarioState;30import com.tngtech.jgiven.annotation.ScenarioState;31import com.tngtech.jgiven.impl.ScenarioExecutor;32import com.tngtech.jgiven.junit.SimpleScenarioTest;33public class Test2 extends SimpleScenarioTest<GivenTest2, WhenTest2, ThenTest2> {34public void test2() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {35 given().a_given_step();36 when().a_when_step();37 then().a

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