How to use StepInterceptorImpl class of com.tngtech.jgiven.impl.intercept package

Best JGiven code snippet using com.tngtech.jgiven.impl.intercept.StepInterceptorImpl

Source:ScenarioExecutor.java Github

copy

Full Screen

...15import com.tngtech.jgiven.impl.inject.ValueInjector;16import com.tngtech.jgiven.impl.intercept.NoOpScenarioListener;17import com.tngtech.jgiven.impl.intercept.ScenarioListener;18import com.tngtech.jgiven.impl.intercept.StageTransitionHandler;19import com.tngtech.jgiven.impl.intercept.StepInterceptorImpl;20import com.tngtech.jgiven.impl.util.FieldCache;21import com.tngtech.jgiven.impl.util.ReflectionUtil;22import com.tngtech.jgiven.integration.CanWire;23import com.tngtech.jgiven.report.model.InvocationMode;24import com.tngtech.jgiven.report.model.NamedArgument;25import java.lang.annotation.Annotation;26import java.lang.reflect.Field;27import java.lang.reflect.Method;28import java.util.ArrayList;29import java.util.LinkedHashMap;30import java.util.List;31import java.util.Map;32import java.util.Optional;33import org.slf4j.Logger;34import org.slf4j.LoggerFactory;35/**36 * Main class of JGiven for executing scenarios.37 */38public class ScenarioExecutor {39 private static final Logger log = LoggerFactory.getLogger(ScenarioExecutor.class);40 enum State {41 INIT,42 STARTED,43 FINISHED44 }45 private Object currentTopLevelStage;46 private State state = State.INIT;47 private boolean beforeScenarioMethodsExecuted;48 /**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:StepInterceptorImpl.java Github

copy

Full Screen

...16import com.tngtech.jgiven.impl.ScenarioExecutor;17import com.tngtech.jgiven.impl.util.ParameterNameUtil;18import com.tngtech.jgiven.report.model.InvocationMode;19import com.tngtech.jgiven.report.model.NamedArgument;20public class StepInterceptorImpl implements StepInterceptor {21 private static final Logger log = LoggerFactory.getLogger( StepInterceptorImpl.class );22 private static final int INITIAL_MAX_STEP_DEPTH = 1;23 private ScenarioExecutor scenarioExecutor;24 private StageTransitionHandler stageTransitionHandler;25 private ScenarioListener listener;26 /**27 * Contains the stack of call receivers. This is used to update28 * the state of a parent stage after a call to a child stage has returned29 */30 protected final Stack<Object> stageStack = new Stack<Object>();31 private int maxStepDepth = INITIAL_MAX_STEP_DEPTH;32 private InvocationMode defaultInvocationMode = InvocationMode.NORMAL;33 /**34 * Whether methods should be intercepted or not35 */36 private boolean interceptingEnabled;37 /**38 * Whether step methods are actually executed or just skipped39 */40 private boolean methodExecutionEnabled = true;41 /**42 * Whether all exceptions should be suppressed and not be rethrown43 */44 private boolean suppressExceptions = true;45 public StepInterceptorImpl(ScenarioExecutor scenarioExecutor, ScenarioListener listener, StageTransitionHandler stageTransitionHandler) {46 this.scenarioExecutor = scenarioExecutor;47 this.listener = listener;48 this.stageTransitionHandler = stageTransitionHandler;49 }50 public final Object intercept( final Object receiver, Method method, final Object[] parameters, Invoker invoker ) throws Throwable {51 if( !shouldInterceptMethod( method ) ) {52 return invoker.proceed();53 }54 int currentStackDepth = stageStack.size();55 Object parentStage = null;56 if( !stageStack.isEmpty() ) {57 parentStage = stageStack.peek();58 }59 stageStack.push( receiver );...

Full Screen

Full Screen

Source:StageLifecycleManagerTest.java Github

copy

Full Screen

...3import com.tngtech.jgiven.annotation.AfterScenario;4import com.tngtech.jgiven.annotation.AfterStage;5import com.tngtech.jgiven.annotation.BeforeScenario;6import com.tngtech.jgiven.annotation.BeforeStage;7import com.tngtech.jgiven.impl.intercept.StepInterceptorImpl;8import org.junit.Test;9public class StageLifecycleManagerTest {10 private final StepInterceptorImpl mockInterceptor = new StepInterceptorImpl(null, null, null);11 private LifecycleMethodContainer methodContainer = new LifecycleMethodContainer();12 private StageLifecycleManager underTest = new StageLifecycleManager(methodContainer, mockInterceptor);13 @Test14 public void exectuesAnnotatedMethodRepeatedly() throws Throwable {15 executeAllLifecycleMethods(underTest, false);16 executeAllLifecycleMethods(underTest, false);17 assertThat(methodContainer.repeatableBeforeMethodInvoked).isEqualTo(2);18 assertThat(methodContainer.repeatableAfterMethodInvoked).isEqualTo(2);19 }20 @Test21 public void exectuesNonAnnotatedMethodOnlyOnce() throws Throwable {22 executeAllLifecycleMethods(underTest, false);23 executeAllLifecycleMethods(underTest, false);24 assertThat(methodContainer.beforeScenarioMethodInvoked).isEqualTo(1);...

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