How to use ParameterNameUtil class of com.tngtech.jgiven.impl.util package

Best JGiven code snippet using com.tngtech.jgiven.impl.util.ParameterNameUtil

Source:StepInterceptorImpl.java Github

copy

Full Screen

...13import com.tngtech.jgiven.annotation.Hidden;14import com.tngtech.jgiven.annotation.NestedSteps;15import com.tngtech.jgiven.annotation.Pending;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 );60 try {61 stageTransitionHandler.enterStage( parentStage, receiver );62 return doIntercept( receiver, method, parameters, invoker, currentStackDepth );63 } finally {64 stageStack.pop();65 stageTransitionHandler.leaveStage( parentStage, receiver );66 }67 }68 private Object doIntercept(Object receiver, Method method, Object[] parameters, Invoker invoker, int currentStackDepth )69 throws Throwable {70 long started = System.nanoTime();71 InvocationMode mode = getInvocationMode( receiver, method );72 boolean hasNestedSteps = method.isAnnotationPresent( NestedSteps.class );73 boolean handleMethod = shouldHandleMethod( method );74 if( handleMethod ) {75 handleMethod( receiver, method, parameters, mode, hasNestedSteps );76 }77 if( mode == SKIPPED || mode == PENDING ) {78 return returnReceiverOrNull( receiver, method );79 }80 if( hasNestedSteps ) {81 maxStepDepth++;82 }83 try {84 return invoker.proceed();85 } catch( Exception e ) {86 return handleThrowable( receiver, method, e, System.nanoTime() - started, handleMethod );87 } catch( AssertionError e ) {88 return handleThrowable( receiver, method, e, System.nanoTime() - started, handleMethod );89 } finally {90 if( hasNestedSteps ) {91 maxStepDepth--;92 }93 if( handleMethod ) {94 handleMethodFinished( System.nanoTime() - started, hasNestedSteps );95 }96 }97 }98 private boolean shouldHandleMethod( Method method ) {99 if( method.isSynthetic() && !method.isBridge() ) {100 return false;101 }102 if( method.isAnnotationPresent( Hidden.class ) ) {103 return false;104 }105 if( stageStack.size() > maxStepDepth ) {106 return false;107 }108 return true;109 }110 private boolean shouldInterceptMethod( Method method ) {111 return interceptingEnabled112 && method.getDeclaringClass() != Object.class113 && !method.isAnnotationPresent(DoNotIntercept.class);114 }115 protected Object handleThrowable( Object receiver, Method method, Throwable t, long durationInNanos, boolean handleMethod )116 throws Throwable {117 if( handleMethod ) {118 handleThrowable( t );119 return returnReceiverOrNull( receiver, method );120 }121 throw t;122 }123 protected Object returnReceiverOrNull( Object receiver, Method method ) {124 // we assume here that the implementation follows the fluent interface125 // convention and returns the receiver object. If not, we fall back to null126 // and hope for the best.127 if( !method.getReturnType().isAssignableFrom( receiver.getClass() ) ) {128 if( method.getReturnType() != Void.class ) {129 log.warn( "The step method " + method.getName()130 + " of class " + method.getDeclaringClass().getSimpleName()131 + " does not follow the fluent interface convention of returning "132 + "the receiver object. Please change the return type to the SELF type parameter." );133 }134 return null;135 }136 return receiver;137 }138 protected InvocationMode getInvocationMode( Object receiver, Method method ) {139 if( !methodExecutionEnabled ) {140 return SKIPPED;141 }142 if( method.isAnnotationPresent( Pending.class )143 || method.getDeclaringClass().isAnnotationPresent( Pending.class )144 || receiver.getClass().isAnnotationPresent( Pending.class ) ) {145 return PENDING;146 }147 return defaultInvocationMode;148 }149 public void enableMethodInterception(boolean b ) {150 interceptingEnabled = b;151 }152 public void disableMethodExecution() {153 methodExecutionEnabled = false;154 }155 public boolean enableMethodExecution( boolean b ) {156 boolean previousMethodExecution = methodExecutionEnabled;157 methodExecutionEnabled = b;158 return previousMethodExecution;159 }160 public void setSuppressExceptions(boolean b) {161 suppressExceptions = b;162 }163 public void setDefaultInvocationMode(InvocationMode defaultInvocationMode) {164 this.defaultInvocationMode = defaultInvocationMode;165 }166 private void handleMethod(Object stageInstance, Method paramMethod, Object[] arguments, InvocationMode mode,167 boolean hasNestedSteps ) throws Throwable {168 List<NamedArgument> namedArguments = ParameterNameUtil.mapArgumentsWithParameterNames( paramMethod,169 Arrays.asList( arguments ) );170 listener.stepMethodInvoked( paramMethod, namedArguments, mode, hasNestedSteps );171 }172 private void handleThrowable( Throwable t ) throws Throwable {173 if( ThrowableUtil.isAssumptionException(t) ) {174 throw t;175 }176 listener.stepMethodFailed( t );177 scenarioExecutor.failed( t );178 if (!suppressExceptions) {179 throw t;180 }181 }182 private void handleMethodFinished( long durationInNanos, boolean hasNestedSteps ) {...

Full Screen

Full Screen

Source:ScenarioTestListener.java Github

copy

Full Screen

...4import com.tngtech.jgiven.exception.FailIfPassedException;5import com.tngtech.jgiven.impl.ScenarioBase;6import com.tngtech.jgiven.impl.ScenarioHolder;7import com.tngtech.jgiven.impl.util.AssertionUtil;8import com.tngtech.jgiven.impl.util.ParameterNameUtil;9import com.tngtech.jgiven.report.impl.CommonReportHelper;10import com.tngtech.jgiven.report.model.NamedArgument;11import com.tngtech.jgiven.report.model.ReportModel;12import java.lang.reflect.Method;13import java.util.List;14import java.util.concurrent.ConcurrentHashMap;15import org.testng.ITestContext;16import org.testng.ITestListener;17import org.testng.ITestResult;18/**19 * TestNG Test listener to enable JGiven for a test class.20 */21@SuppressWarnings("checkstyle:AbbreviationAsWordInName")22public class ScenarioTestListener implements ITestListener {23 public static final String SCENARIO_ATTRIBUTE = "jgiven::scenario";24 public static final String REPORT_MODELS_ATTRIBUTE = "jgiven::reportModels";25 @Override26 public void onTestStart(ITestResult paramITestResult) {27 Object instance = paramITestResult.getInstance();28 ScenarioBase scenario;29 if (instance instanceof ScenarioTestBase<?, ?, ?>) {30 ScenarioTestBase<?, ?, ?> testInstance = (ScenarioTestBase<?, ?, ?>) instance;31 scenario = testInstance.createNewScenario();32 } else {33 scenario = new ScenarioBase();34 }35 ScenarioHolder.get().setScenarioOfCurrentThread(scenario);36 paramITestResult.setAttribute(SCENARIO_ATTRIBUTE, scenario);37 ReportModel reportModel = getReportModel(paramITestResult, instance.getClass());38 scenario.setModel(reportModel);39 //TestNG cannot run in parallel if stages are to be injected, because then multiple scenarios40 //will attempt to inject into a single test instance at the same time.41 new IncompatibleMultithreadingChecker().checkIncompatibleMultiThreading(paramITestResult);42 // TestNG does not work well when catching step exceptions, so we have to disable that feature43 // this mainly means that steps following a failing step are not reported in JGiven44 scenario.getExecutor().setSuppressStepExceptions(false);45 // avoid rethrowing exceptions as they are already thrown by the steps46 scenario.getExecutor().setSuppressExceptions(true);47 scenario.getExecutor().injectStages(instance);48 Method method = paramITestResult.getMethod().getConstructorOrMethod().getMethod();49 scenario.startScenario(instance.getClass(), method, getArgumentsFrom(method, paramITestResult));50 // inject state from the test itself51 scenario.getExecutor().readScenarioState(instance);52 }53 private ScenarioBase getScenario(ITestResult paramITestResult) {54 return (ScenarioBase) paramITestResult.getAttribute(SCENARIO_ATTRIBUTE);55 }56 private ReportModel getReportModel(ITestResult testResult, Class<?> clazz) {57 ConcurrentHashMap<String, ReportModel> reportModels = getReportModels(testResult.getTestContext());58 ReportModel model = reportModels.get(clazz.getName());59 if (model == null) {60 model = new ReportModel();61 model.setTestClass(clazz);62 ReportModel previousModel = reportModels.putIfAbsent(clazz.getName(), model);63 if (previousModel != null) {64 model = previousModel;65 }66 }67 AssertionUtil.assertNotNull(model, "Report model is null");68 return model;69 }70 @Override71 public void onTestSuccess(ITestResult paramITestResult) {72 testFinished(paramITestResult);73 }74 @Override75 public void onTestFailure(ITestResult paramITestResult) {76 ScenarioBase scenario = getScenario(paramITestResult);77 if (scenario != null) {78 scenario.getExecutor().failed(paramITestResult.getThrowable());79 testFinished(paramITestResult);80 }81 }82 @Override83 public void onTestSkipped(ITestResult testResult) {84 }85 private void testFinished(ITestResult testResult) {86 try {87 ScenarioBase scenario = getScenario(testResult);88 scenario.finished();89 } catch (FailIfPassedException ex) {90 testResult.setStatus(ITestResult.FAILURE);91 testResult.setThrowable(ex);92 testResult.getTestContext().getPassedTests().removeResult(testResult);93 testResult.getTestContext().getFailedTests().addResult(testResult);94 } catch (Throwable throwable) {95 throw new RuntimeException(throwable);96 } finally {97 ScenarioHolder.get().removeScenarioOfCurrentThread();98 }99 }100 @Override101 public void onTestFailedButWithinSuccessPercentage(ITestResult paramITestResult) {102 }103 @Override104 public void onStart(ITestContext paramITestContext) {105 paramITestContext.setAttribute(REPORT_MODELS_ATTRIBUTE, new ConcurrentHashMap<String, ReportModel>());106 }107 @Override108 public void onFinish(ITestContext paramITestContext) {109 ConcurrentHashMap<String, ReportModel> reportModels = getReportModels(paramITestContext);110 for (ReportModel reportModel : reportModels.values()) {111 new CommonReportHelper().finishReport(reportModel);112 }113 }114 private ConcurrentHashMap<String, ReportModel> getReportModels(ITestContext paramITestContext) {115 return (ConcurrentHashMap<String, ReportModel>)116 paramITestContext.getAttribute(REPORT_MODELS_ATTRIBUTE);117 }118 private List<NamedArgument> getArgumentsFrom(Method method, ITestResult paramITestResult) {119 return ParameterNameUtil.mapArgumentsWithParameterNames(method, asList(paramITestResult.getParameters()));120 }121}...

Full Screen

Full Screen

Source:ArgumentReflectionUtil.java Github

copy

Full Screen

...5import java.util.List;6import org.junit.jupiter.api.extension.ExtensionContext;7import org.slf4j.Logger;8import org.slf4j.LoggerFactory;9import com.tngtech.jgiven.impl.util.ParameterNameUtil;10import com.tngtech.jgiven.impl.util.ReflectionUtil;11import com.tngtech.jgiven.report.model.NamedArgument;12class ArgumentReflectionUtil {13 private static final Logger log = LoggerFactory.getLogger( ArgumentReflectionUtil.class );14 static final String METHOD_EXTENSION_CONTEXT = "org.junit.jupiter.engine.descriptor.MethodExtensionContext";15 static final String TEST_TEMPLATE_INVOCATION_TEST_DESCRIPTOR = "org.junit.jupiter.engine.descriptor.TestTemplateInvocationTestDescriptor";16 static final String PARAMETERIZED_TEST_INVOCATION_CONTEXT = "org.junit.jupiter.params.ParameterizedTestInvocationContext";17 static final String ERROR = "Not able to access field containing test method arguments. " +18 "Probably the internal representation has changed. Consider writing a bug report.";19 /**20 * This is a very ugly workaround to get the method arguments from the JUnit 5 context via reflection.21 */22 static List<NamedArgument> getNamedArgs( ExtensionContext context ) {23 List<NamedArgument> namedArgs = new ArrayList<>();24 if( context.getTestMethod().get().getParameterCount() > 0 ) {25 try {26 if( context.getClass().getCanonicalName().equals( METHOD_EXTENSION_CONTEXT ) ) {27 Field field = context.getClass().getSuperclass().getDeclaredField( "testDescriptor" );28 Object testDescriptor = ReflectionUtil.getFieldValueOrNull( field, context, ERROR );29 if( testDescriptor != null30 && testDescriptor.getClass().getCanonicalName().equals( TEST_TEMPLATE_INVOCATION_TEST_DESCRIPTOR ) ) {31 Object invocationContext = ReflectionUtil.getFieldValueOrNull( "invocationContext", testDescriptor, ERROR );32 if( invocationContext != null33 && invocationContext.getClass().getCanonicalName().equals( PARAMETERIZED_TEST_INVOCATION_CONTEXT ) ) {34 Object arguments = ReflectionUtil.getFieldValueOrNull( "arguments", invocationContext, ERROR );35 List<Object> args = Arrays.asList( (Object[]) arguments );36 namedArgs = ParameterNameUtil.mapArgumentsWithParameterNames( context.getTestMethod().get(), args );37 }38 }39 }40 } catch( Exception e ) {41 log.warn( ERROR, e );42 }43 }44 return namedArgs;45 }46}...

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.

Run JGiven automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful