Best EvoMaster code snippet using org.evomaster.client.java.controller.internal.SutController.customizeRPCTestOutput
Source:SutController.java
...539 public void postSearchAction(PostSearchActionDto dto){540 try{541 if (dto != null && dto.rpcTests != null && !dto.rpcTests.isEmpty()){542 dto.rpcTests.forEach(s->543 customizeRPCTestOutput(s.externalServiceDtos, s.sqlInsertions, s.actions)544 );545 }546 }catch (Exception e){547 throw new RuntimeException("fail to customize RPC Test outputs:", e);548 }549 }550 /**551 * Re-initialize some internal data needed before running a new test552 */553 public final void newTest() {554 actionIndex = -1;555 resetExtraHeuristics();556 extras.clear();557 //clean all accessed table in a test558 accessedTables.clear();559 newTestSpecificHandler();560 // set executingAction state false for newTest561 setExecutingAction(false);562 }563 /**564 * As some heuristics are based on which action (eg HTTP call, or click of button)565 * in the test sequence is executed, and their order, we need to keep track of which566 * action does cover what.567 *568 * @param dto the DTO with the information about the action (eg its index in the test)569 */570 public final void newAction(ActionDto dto) {571 if (dto.index > extras.size()) {572 extras.add(computeExtraHeuristics());573 }574 this.actionIndex = dto.index;575 resetExtraHeuristics();576 newActionSpecificHandler(dto);577 }578 public final void executeHandleLocalAuthenticationSetup(RPCActionDto dto, ActionResponseDto responseDto){579 LocalAuthSetupSchema endpointSchema = new LocalAuthSetupSchema();580 endpointSchema.setValue(dto);581 handleLocalAuthenticationSetup(endpointSchema.getAuthenticationInfo());582 if (dto.responseVariable != null && dto.doGenerateTestScript){583 responseDto.testScript = endpointSchema.newInvocationWithJava(dto.responseVariable, dto.controllerVariable,dto.clientVariable);584 }585 }586 /**587 * execute a RPC request based on the specified dto588 * @param dto is the action DTO to be executed589 */590 public final void executeAction(RPCActionDto dto, ActionResponseDto responseDto) {591 EndpointSchema endpointSchema = getEndpointSchema(dto);592 if (dto.responseVariable != null && dto.doGenerateTestScript){593 try{594 responseDto.testScript = endpointSchema.newInvocationWithJava(dto.responseVariable, dto.controllerVariable,dto.clientVariable);595 }catch (Exception e){596 SimpleLogger.warn("Fail to generate test script"+e.getMessage());597 }598 if (responseDto.testScript ==null)599 SimpleLogger.warn("Null test script for action "+dto.actionName);600 }601 Object response;602 try {603 response = executeRPCEndpoint(dto, false);604 } catch (Exception e) {605 throw new RuntimeException("ERROR: target exception should be caught, but "+ e.getMessage());606 }607 //handle exception608 if (response instanceof Exception){609 try{610 RPCExceptionHandler.handle(response, responseDto, endpointSchema, getRPCType(dto));611 return;612 } catch (Exception e){613 SimpleLogger.error("ERROR: fail to handle exception instance to dto "+ e.getMessage());614 //throw new RuntimeException("ERROR: fail to handle exception instance to dto "+ e.getMessage());615 }616 }617 if (endpointSchema.getResponse() != null){618 // successful execution619 NamedTypedValue resSchema = endpointSchema.getResponse().copyStructureWithProperties();620 if (response != null){621 try{622 resSchema.setValueBasedOnInstance(response);623 responseDto.rpcResponse = resSchema.getDto();624 if (dto.doGenerateAssertions && dto.responseVariable != null)625 responseDto.assertionScript = resSchema.newAssertionWithJava(dto.responseVariable, dto.maxAssertionForDataInCollection);626 else627 responseDto.jsonResponse = objectMapper.writeValueAsString(response);628 } catch (Exception e){629 SimpleLogger.error("ERROR: fail to set successful response instance value to dto "+ e.getMessage());630 //throw new RuntimeException("ERROR: fail to set successful response instance value to dto "+ e.getMessage());631 }632 try {633 responseDto.customizedCallResultCode = categorizeBasedOnResponse(response);634 } catch (Exception e){635 SimpleLogger.error("ERROR: fail to categorize result with implemented categorizeBasedOnResponse "+ e.getMessage());636 //throw new RuntimeException("ERROR: fail to categorize result with implemented categorizeBasedOnResponse "+ e.getMessage());637 }638 } else {639 if (dto.doGenerateAssertions && dto.responseVariable != null)640 responseDto.assertionScript = resSchema.newAssertionWithJava(dto.responseVariable, dto.maxAssertionForDataInCollection);641 }642 }643 }644 private Object executeRPCEndpoint(RPCActionDto dto, boolean throwTargetException) throws Exception {645 Object client = ((RPCProblem)getProblemInfo()).getClient(dto.interfaceId);646 EndpointSchema endpointSchema = getEndpointSchema(dto);647 return executeRPCEndpointCatchTargetException(client, endpointSchema, throwTargetException);648 }649 private Object executeRPCEndpointCatchTargetException(Object client, EndpointSchema endpoint, boolean throwTargetException) throws Exception {650 Object res;651 try {652 res = executeRPCEndpoint(client, endpoint);653 } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException e) {654 throw new RuntimeException("EM RPC REQUEST EXECUTION ERROR: fail to process a RPC request with "+ e.getMessage());655 } catch (InvocationTargetException e) {656 if (throwTargetException)657 throw (Exception) e.getTargetException();658 else659 res = e.getTargetException();660 } catch (Exception e){661 SimpleLogger.error("ERROR: other exception exists "+ e.getMessage());662 if (throwTargetException) throw e;663 else res = e;664 }665 return res;666 }667 @Override668 public Object executeRPCEndpoint(String json) throws Exception{669 try {670 RPCActionDto dto = objectMapper.readValue(json, RPCActionDto.class);671 return executeRPCEndpoint(dto, true);672 } catch (JsonProcessingException e) {673 SimpleLogger.error("Failed to extract the json: " + e.getMessage());674 }675 return null;676 }677 /**678 * execute a RPC request with specified client679 * @param client is the client to execute the endpoint680 * @param endpoint is the endpoint to be executed681 */682 private final Object executeRPCEndpoint(Object client, EndpointSchema endpoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, ClassNotFoundException {683 if (endpoint.getRequestParams().isEmpty()){684 Method method = client.getClass().getDeclaredMethod(endpoint.getName());685 return method.invoke(client);686 }687 Object[] params = new Object[endpoint.getRequestParams().size()];688 Class<?>[] types = new Class<?>[endpoint.getRequestParams().size()];689 try{690 for (int i = 0; i < params.length; i++){691 NamedTypedValue param = endpoint.getRequestParams().get(i);692 params[i] = param.newInstance();693 types[i] = param.getType().getClazz();694 }695 } catch (Exception e){696 throw new RuntimeException("ERROR: fail to instance value of input parameters based on dto/schema, msg error:"+e.getMessage());697 }698 Method method = client.getClass().getDeclaredMethod(endpoint.getName(), types);699 return method.invoke(client, params);700 }701 private EndpointSchema getEndpointSchema(RPCActionDto dto){702 InterfaceSchema interfaceSchema = rpcInterfaceSchema.get(dto.interfaceId);703 EndpointSchema endpointSchema = interfaceSchema.getOneEndpoint(dto).copyStructure();704 endpointSchema.setValue(dto);705 return endpointSchema;706 }707 private RPCType getRPCType(RPCActionDto dto){708 return rpcInterfaceSchema.get(dto.interfaceId).getRpcType();709 }710 public abstract void newTestSpecificHandler();711 public abstract void newActionSpecificHandler(ActionDto dto);712 /**713 * Check if bytecode instrumentation is on.714 *715 * @return true if the instrumentation is on716 */717 public abstract boolean isInstrumentationActivated();718 /**719 * <p>720 * Check if the system under test (SUT) is running and fully initialized721 * </p>722 *723 * <p>724 * How to implement this method depends on the library/framework used725 * to build the application.726 * In Spring applications, this can be done with something like:727 * {@code ctx != null && ctx.isRunning()}, where {@code ctx} is a field where728 * {@code ConfigurableApplicationContext} should be stored when starting729 * the application.730 * </p>731 * @return true if the SUT is running732 */733 public abstract boolean isSutRunning();734 /**735 * <p>736 * A "," separated list of package prefixes or class names.737 * For example, "com.foo.,com.bar.Bar".738 * This is used to specify for which classes we want to measure739 * code coverage.740 * </p>741 *742 * <p>743 * Note: be careful of using something as general as "com."744 * or "org.", as most likely ALL your third-party libraries745 * would be instrumented as well, which could have a severe746 * impact on performance.747 * </p>748 *749 * @return a String representing the packages to cover750 */751 public abstract String getPackagePrefixesToCover();752 /**753 * <p>754 * If the application uses some sort of authentication, these details755 * need to be provided here.756 * Even if EvoMaster can have access to the database, it would not be able757 * to recover hashed passwords.758 * </p>759 *760 * <p>761 * To test the application, there is the need to provide auth for at least 1 user762 * (and more if they have different authorization roles).763 * When EvoMaster generates test cases, it can decide to use the credential of764 * any user provided by this method.765 * </p>766 *767 * <p>768 * What type of info to provide here depends on the auth mechanism, e.g.,769 * Basic or cookie-based (using {@link CookieLoginDto}).770 * To simplify the creation of these DTOs with auth info, you can look771 * at {@link org.evomaster.client.java.controller.AuthUtils}.772 * </p>773 *774 * <p>775 * If the credential are stored in a database, be careful on how the776 * method {@code resetStateOfSUT} is implemented.777 * If you delete all data with {@link DbCleaner}, then you will need as well to778 * recreate the auth details.779 * This can be put in a script, executed then with {@link SqlScriptRunner}.780 * </p>781 *782 * @return a list of valid authentication credentials, or {@code null} if783 * * none is necessary784 */785 public abstract List<AuthenticationDto> getInfoForAuthentication();786 /**787 * <p>788 * If the system under test (SUT) uses a SQL database, we need to have a789 * configured connection to access it.790 * </p>791 *792 * <p>793 * This method is related to {@link SutHandler#resetStateOfSUT}.794 * When accessing a {@code Connection} object to reset the state of795 * the application, we suggest to save it to field (eg when starting the796 * application), and return such field here, e.g., {@code return connection;}.797 * This connection object will be used by EvoMaster to analyze the state of798 * the database to create better test cases.799 * </p>800 *801 * @return {@code null} if the SUT does not use any SQL database802 * @deprecated this is now set in DbSpecification803 */804 @Deprecated805 public final Connection getConnection(){806 throw new IllegalStateException("This deprecated method should never be called");807 }808 /**809 * If the system under test (SUT) uses a SQL database, we need to specify810 * the driver used to connect, eg. {@code org.h2.Driver}.811 * This is needed for when we intercept SQL commands with P6Spy812 *813 * @return {@code null} if the SUT does not use any SQL database814 * @deprecated this method is no longer needed815 */816 @Deprecated817 public final String getDatabaseDriverName(){818 throw new IllegalStateException("This deprecated method should never be called");819 }820 public abstract List<TargetInfo> getTargetInfos(Collection<Integer> ids);821 /**822 * @return additional info for each action in the test.823 * The list is ordered based on the action index.824 */825 public abstract List<AdditionalInfo> getAdditionalInfoList();826 /**827 * <p>828 * Depending of which kind of SUT we are dealing with (eg, REST, GraphQL or SPA frontend),829 * there is different info that must be provided.830 * For example, in a RESTful API, you need to speficy where the OpenAPI/Swagger schema831 * is located.832 * </p>833 *834 * <p>835 * The interface {@link ProblemInfo} provides different implementations, like836 * {@code RestProblem}.837 * You will need to instantiate one of such classes, and return it here in this method.838 * </p>839 * @return an instance of object with all the needed data for the specific addressed problem840 */841 public abstract ProblemInfo getProblemInfo();842 /**843 * Test cases could be outputted in different language (e.g., Java and Kotlin),844 * using different testing libraries (e.g., JUnit 4 or 5).845 * Here, need to specify the default option.846 *847 * @return the format in which the test cases should be generated848 */849 public abstract SutInfoDto.OutputFormat getPreferredOutputFormat();850 public abstract UnitsInfoDto getUnitsInfoDto();851 public abstract void setKillSwitch(boolean b);852 public abstract void setExecutingInitSql(boolean executingInitSql);853 public abstract void setExecutingAction(boolean executingAction);854 public abstract BootTimeInfoDto getBootTimeInfoDto();855 protected BootTimeInfoDto getBootTimeInfoDto(BootTimeObjectiveInfo info){856 if (info == null)857 return null;858 BootTimeInfoDto infoDto = new BootTimeInfoDto();859 infoDto.targets = info.getObjectiveCoverageAtSutBootTime()860 .entrySet().stream().map(e-> new TargetInfoDto(){{861 descriptiveId = e.getKey();862 value = e.getValue();863 }}).collect(Collectors.toList());864 infoDto.externalServicesDto = info.getExternalServiceInfo().stream()865 .map(e -> new ExternalServiceInfoDto(e.getProtocol(), e.getHostname(), e.getRemotePort()))866 .collect(Collectors.toList());867 return infoDto;868 }869 public abstract String getExecutableFullPath();870 protected UnitsInfoDto getUnitsInfoDto(UnitsInfoRecorder recorder){871 if(recorder == null){872 return null;873 }874 UnitsInfoDto dto = new UnitsInfoDto();875 dto.numberOfBranches = recorder.getNumberOfBranches();876 dto.numberOfLines = recorder.getNumberOfLines();877 dto.numberOfReplacedMethodsInSut = recorder.getNumberOfReplacedMethodsInSut();878 dto.numberOfReplacedMethodsInThirdParty = recorder.getNumberOfReplacedMethodsInThirdParty();879 dto.numberOfTrackedMethods = recorder.getNumberOfTrackedMethods();880 dto.unitNames = recorder.getUnitNames();881 dto.parsedDtos = recorder.getParsedDtos();882 dto.numberOfInstrumentedNumberComparisons = recorder.getNumberOfInstrumentedNumberComparisons();883 return dto;884 }885 @Override886 public Object getRPCClient(String interfaceName) {887 if (!(getProblemInfo() instanceof RPCProblem))888 throw new RuntimeException("ERROR: the problem should be RPC but it is "+ getProblemInfo().getClass().getSimpleName());889 Object client = ((RPCProblem) getProblemInfo()).getClient(interfaceName);890 if (client == null)891 throw new RuntimeException("ERROR: cannot find any client with the name :"+ interfaceName);892 return client;893 }894 @Override895 public CustomizedCallResultCode categorizeBasedOnResponse(Object response) {896 return null;897 }898 @Override899 public List<CustomizedRequestValueDto> getCustomizedValueInRequests() {900 return null;901 }902 @Override903 public List<CustomizedNotNullAnnotationForRPCDto> specifyCustomizedNotNullAnnotation() {904 return null;905 }906 @Override907 public List<SeededRPCTestDto> seedRPCTests() {908 return null;909 }910 @Override911 public boolean customizeRPCTestOutput(List<MockRPCExternalServiceDto> externalServiceDtos, List<String> sqlInsertions, List<EvaluatedRPCActionDto> actions) {912 return false;913 }914 @Override915 public boolean customizeMockingRPCExternalService(List<MockRPCExternalServiceDto> externalServiceDtos) {916 return false;917 }918 @Override919 public void resetDatabase(List<String> tablesToClean) {920 if (getDbSpecifications()!= null && !getDbSpecifications().isEmpty()){921 getDbSpecifications().forEach(spec->{922 if (spec==null || spec.connection == null || !spec.employSmartDbClean){923 return;924 }925 if (spec.schemaNames == null || spec.schemaNames.isEmpty())...
customizeRPCTestOutput
Using AI Code Generation
1package org.evomaster.client.java.controller.internal;2import org.evomaster.client.java.controller.api.dto.SutInfoDto;3import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseExecutionDto;4import org.evomaster.client.java.controller.api.dto.database.schema.DbSchemaDto;5import org.evomaster.client.java.controller.api.dto.database.schema.TableDto;6import org.evomaster.client.java.controller.api.dto.database.schema.TableIndexDto;7import org.evomaster.client.java.controller.api.dto.database.schema.TableIndexType;8import org.evomaster.client.java.controller.api.dto.database.schema.TableType;9import org.evomaster.client.java.controller.api.dto.database.schema.ViewDto;10import org.evomaster.client.java.controller.api.dto.database.schema.ViewType;11import org.evomaster.client.java.controller.api.dto.database.operations.InsertionDto;12import org.evomaster.client.java.controller.api.dto.database.operations.UpdateDto;13import org.evomaster.client.java.controller.api.dto.database.operations.DeletionDto;14import org.evomaster.client.java.controller.api.dto.database.operations.SelectionDto;15import org.evomaster.client.java.controller.api.dto.database.operations.SqlScriptDto;16import org.evomaster.client.java.controller.api.dto.database.operations.SqlTransactionDto;17import org.evomaster.client.java.controller.a
customizeRPCTestOutput
Using AI Code Generation
1import org.evomaster.client.java.controller.api.dto.SutInfoDto;2import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseInitializationDto;3import org.evomaster.client.java.controller.api.dto.database.operations.DatabaseRowDto;4import org.evomaster.client.java.controller.api.dto.database.operations.SqlScriptDto;5import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType;6import org.evomaster.client.java.controller.api.dto.database.schema.TableDto;7import org.evomaster.client.java.controller.api.dto.database.schema.TableIndexDto;8import org.evomaster.client.java.controller.api.dto.database.schema.TableIndexType;9import org.evomaster.client.java.controller.api.dto.database.schema.TableSchemaDto;10import org.evomaster.client.java.controller.api.dto.database.schema.TableType;11import org.evomaster.client.java.controller.api.dto.database.schema.ViewDto;12import org.evomaster.client.java.controller.api.dto.database.schema.ViewSchemaDto;13import org.evomaster.client.java.controller.api.dto.database.schema.ViewType;14import org.evomaster.client.java.controller.api.dto.problem.ProblemInfoDto;15import org.evomaster.client.java.controller.api.dto.problem.RestProblemDto;16import org.evomaster.client.java.controller.api.dto.problem.SqlProblemDto;17import org.evomaster.client.java.controller.api.dto.problem.TestResultsDto;18import org.evomaster.client.java.controller.api.dto.problem.TestResultsStatusDto;19import org.evomaster.client.java.controller.api.dto.problem.TestRunResultDto;20import org.evomaster.client.java.controller.api.dto.sut.SutInfoDto;21import org.evomaster.client.java.controller.api.dto.sut.auth.AuthenticationDto;22import org.evomaster.client.java.controller.api.dto.sut.auth.AuthenticationInfoDto;23import org.evomaster.client.java.controller.api.dto.sut.auth.AuthenticationType;24import org.evomaster.client.java.controller.api.dto.sut.auth.OAuth2Dto;25import org.evomaster.client.java.controller.api.dto.sut.auth.OAuth2Flow;26import org.evomaster.client.java.controller.api.dto.sut.auth.OAuth2InfoDto;27import org.evomaster.client.java.controller.api.dto.sut.auth.OAuth2ScopeDto;28import org.evomaster.client.java.controller.api.dto.sut.auth.OAuth2SecuritySchemeDto;29import org.evomaster.client.java.controller.api.dto.sut.auth.OAuth2Type;30import org.evomaster.client.java.controller.api.dto.sut.auth.SecurityRequirementDto;31import org.evomaster.client.java.controller
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!