com.consol.citrus.context.TestContext Java Examples

The following examples show how to use com.consol.citrus.context.TestContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InboundXmlDataDictionary.java    From citrus-simulator with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T translate(Node node, T value, TestContext context) {
    for (Map.Entry<String, String> expressionEntry : mappings.entrySet()) {
        String expression = expressionEntry.getKey();

        SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext();
        namespaceContext.setBindings(context.getNamespaceContextBuilder().getNamespaceMappings());

        NodeList findings = (NodeList) XPathUtils.evaluateExpression(node.getOwnerDocument(), expression, namespaceContext, XPathConstants.NODESET);

        if (findings != null && containsNode(findings, node)) {
            return convertIfNecessary(context.replaceDynamicContentInString(expressionEntry.getValue()), value);
        }
    }

    return value;
}
 
Example #2
Source File: InjectEnvVarsHookTest.java    From yaks with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("CucumberJavaStepDefClassIsPublic")
public void shouldInjectEnvVarsDefaultValues() {
    InjectEnvVarsHook hook = new InjectEnvVarsHook() {
        @Override
        protected Optional<String> getEnvSetting(String name) {
            if (name.equals(InjectEnvVarsHook.YAKS_NAMESPACE)) {
                return Optional.of("foo");
            }

            return Optional.empty();
        }
    };

    TestContext context = TestContextFactory.newInstance().getObject();
    TestCaseRunner runner = new DefaultTestCaseRunner(context);
    CitrusAnnotations.injectTestRunner(hook, runner);

    hook.injectEnvVars(null);

    Assertions.assertThat(context.getVariable(InjectEnvVarsHook.YAKS_NAMESPACE)).isEqualTo("foo");
    Assertions.assertThat(context.getVariable(InjectEnvVarsHook.CLUSTER_WILDCARD_DOMAIN)).isEqualTo("foo" + InjectEnvVarsHook.DEFAULT_DOMAIN_SUFFIX);
}
 
Example #3
Source File: InjectEnvVarsHookTest.java    From yaks with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("CucumberJavaStepDefClassIsPublic")
public void shouldInjectEnvVars() {
    InjectEnvVarsHook hook = new InjectEnvVarsHook() {
        @Override
        protected Optional<String> getEnvSetting(String name) {
            return Optional.of("foo");
        }
    };

    TestContext context = TestContextFactory.newInstance().getObject();
    TestCaseRunner runner = new DefaultTestCaseRunner(context);
    CitrusAnnotations.injectTestRunner(hook, runner);

    hook.injectEnvVars(null);

    Assertions.assertThat(context.getVariable(InjectEnvVarsHook.YAKS_NAMESPACE)).isEqualTo("foo");
    Assertions.assertThat(context.getVariable(InjectEnvVarsHook.CLUSTER_WILDCARD_DOMAIN)).isEqualTo("foo");
}
 
Example #4
Source File: InjectEnvVarsHook.java    From yaks with Apache License 2.0 6 votes vote down vote up
@Before
public void injectEnvVars(Scenario scenario) {
    runner.run(new AbstractTestAction() {
        @Override
        public void doExecute(TestContext context) {
            if (scenario != null) {
                context.setVariable("SCENARIO_ID", scenario.getId());
                context.setVariable("SCENARIO_NAME", scenario.getName());
            }

            Optional<String> namespaceEnv = getEnvSetting(YAKS_NAMESPACE);
            Optional<String> domainEnv = getEnvSetting(CLUSTER_WILDCARD_DOMAIN);

            if (namespaceEnv.isPresent()) {
                context.setVariable(YAKS_NAMESPACE, namespaceEnv.get());

                if (!domainEnv.isPresent()) {
                    context.setVariable(CLUSTER_WILDCARD_DOMAIN, namespaceEnv.get() + DEFAULT_DOMAIN_SUFFIX);
                }
            }

            domainEnv.ifPresent(var -> context.setVariable(CLUSTER_WILDCARD_DOMAIN, var));
        }
    });
}
 
Example #5
Source File: CompleteAPIExportTestIT.java    From apimanager-swagger-promote with Apache License 2.0 6 votes vote down vote up
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, InterruptedException {
	description("Import an API, export it afterwards and validate it equals to the imported API");
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/api/test/"+this.getClass().getSimpleName()+"-${apiNumber}");
	variable("apiName", this.getClass().getSimpleName()+"-${apiNumber}");
	variable("state", "published");
	
	echo("####### Importing the API, which should exported in the second step #######");
	createVariable(ImportTestAction.API_DEFINITION,  "/test/export/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/test/export/files/basic/complete-config.json");
	createVariable("image", "/com/axway/apim/test/files/basic/API-Logo.jpg");
	createVariable("expectedReturnCode", "0");
	
	swaggerImport.doExecute(context);
	if(APIManagerAdapter.hasAPIManagerVersion("7.7.20200130")) {
		Thread.sleep(1000); // Starting with this version, we need to wait a few milliseconds, otherwise the REST-API doesn't return the complete set of quotas
	}
	
	exportAPI(context, false);
	exportAPI(context, true);
}
 
Example #6
Source File: MethodLevelInvalidProfileTestIT.java    From apimanager-swagger-promote with Apache License 2.0 6 votes vote down vote up
@CitrusTest
@Test @Parameters("context")
public void runInboundCorsProfileValidation(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	description("Is the CORS-Profile not know - Error must be handled");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/basic-method-level-api-${apiNumber}");
	variable("apiName", "Basic Method-Level-API-${apiNumber}");
	
	echo("####### Try to replicate an API having invalid profiles referenced #######");		
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/methodLevel/method-level-inbound-invalidCorsProfileRefercence.json");
	createVariable("state", "unpublished");
	createVariable("expectedReturnCode", "73");
	swaggerImport.doExecute(context);
}
 
Example #7
Source File: InboundMethodLevelInvalidOperationTestIT.java    From apimanager-swagger-promote with Apache License 2.0 6 votes vote down vote up
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	description("Make sure, the error that an invalid operationId is given is properly handled.");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/basic-method-level-api-${apiNumber}");
	variable("apiName", "Basic Method-Level-API-${apiNumber}");
	
	echo("####### Try to replicate an API having Method-Level settings declared #######");		
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/methodLevel/method-level-inbound-invalidOperation.json");
	createVariable("state", "unpublished");
	createVariable("expectedReturnCode", "72");
	createVariable("securityProfileName", "APIKeyBased${apiNumber}");
	swaggerImport.doExecute(context);
}
 
Example #8
Source File: OrgAdminTriesToPublishTestIT.java    From apimanager-swagger-promote with Apache License 2.0 6 votes vote down vote up
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	
	description("But OrgAdmins should not being allowed to register published APIs.");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/org-admin-published-${apiNumber}");
	variable("apiName", "OrgAdmin-Published-${apiNumber}");
	variable("ignoreAdminAccount", "true"); // This tests simulate to use only an Org-Admin-Account
	variable("allowOrgAdminsToPublish", "false"); // Disable OrgAdmins to publish APIs

	echo("####### Calling the tool with a Non-Admin-User. #######");
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/basic/2_initially_published.json");
	createVariable("expectedReturnCode", "17");
	createVariable("apiManagerUser", "${oadminUsername1}"); // This is an org-admin user
	createVariable("apiManagerPass", "${oadminPassword1}");
	swaggerImport.doExecute(context);
}
 
Example #9
Source File: NoAPIDefinitionConfiguredIT.java    From apimanager-swagger-promote with Apache License 2.0 6 votes vote down vote up
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	description("If no api-definition is passed as argument and no apiDefinition attribute is found in configuration file, the tool must fail with a dedicated return code.");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/my-no-api-def-${apiNumber}");
	variable("apiName", "No-API-DEF-CONFIGURED-${apiNumber}");

	echo("####### Calling the tool with a Non-Admin-User. #######");
	createVariable(ImportTestAction.API_DEFINITION,  "");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/basic/minimal-config.json");
	createVariable("status", "unpublished");
	createVariable("expectedReturnCode", String.valueOf(ErrorCode.NO_API_DEFINITION_CONFIGURED.getCode()));
	swaggerImport.doExecute(context);
}
 
Example #10
Source File: InvalidQuotaConfigTestIT.java    From apimanager-swagger-promote with Apache License 2.0 6 votes vote down vote up
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	description("Try to import an API with invalid quota configuration.");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/invalid-quota-api-${apiNumber}");
	variable("apiName", "Invalid Quota-API-${apiNumber}");

	echo("####### Trying to import API: '${apiName}' on path: '${apiPath}' with invalid quota config #######");		
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/quota/issue-109-invalid-quota-config-1.json");
	createVariable("state", "unpublished");
	createVariable("expectedReturnCode", "71");
	swaggerImport.doExecute(context);
	
	echo("####### Trying to import API: '${apiName}' on path: '${apiPath}' with invalid quota config #######");		
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/quota/issue-109-invalid-quota-config-2.json");
	createVariable("state", "unpublished");
	createVariable("expectedReturnCode", "71");
	swaggerImport.doExecute(context);
}
 
Example #11
Source File: AllureCitrusTest.java    From allure-java with Apache License 2.0 6 votes vote down vote up
@AllureFeatures.FailedTests
@Test
void shouldSetFailedStatus() {
    final DefaultTestDesigner designer = new DefaultTestDesigner();
    designer.name("Simple test");
    designer.action(new AbstractTestAction() {
        @Override
        public void doExecute(final TestContext context) {
            assertThat(true).isFalse();
        }
    });

    final AllureResults results = run(designer);
    assertThat(results.getTestResults())
            .extracting(TestResult::getStatus)
            .containsExactly(Status.FAILED);
}
 
Example #12
Source File: WebHookToFtp_IT.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public void doExecute(TestContext testContext) {
    Path publicUserDir = getFtpUserHome().resolve("public");
    Assert.assertTrue( "Missing ftp user home directory", publicUserDir.toFile().exists());

    File ftpUploadFile = publicUserDir.resolve(UPLOAD_FILENAME).toFile();
    Assert.assertTrue(String.format("Missing ftp upload file '%s'", UPLOAD_FILENAME), ftpUploadFile.exists());
    try {
        JsonTextMessageValidator validator = new JsonTextMessageValidator();
        validator.validateMessage(new DefaultMessage(FileUtils.readToString(ftpUploadFile)),
                                    new DefaultMessage("{\"message\" : \"${first_name},${company},${email}\"}"),
                                    testContext,
                                    new JsonMessageValidationContext());
    } catch (IOException e) {
        throw new CitrusRuntimeException(String.format("Failed to verify ftp upload file '%s'", UPLOAD_FILENAME), e);
    }
}
 
Example #13
Source File: Verify.java    From dew with Apache License 2.0 6 votes vote down vote up
/**
 * Verify resource descriptors.
 *
 * @param message      the message
 * @param expectedText the expected text
 * @param actualText   the actual text
 * @throws IOException    the io exception
 * @throws ParseException the parse exception
 */
default void verifyResourceDescriptors(String message, String expectedText, String actualText) throws IOException, ParseException {
    JsonTextMessageValidator validator = new JsonTextMessageValidator();
    validator.setStrict(false);

    TestContext context = new TestContext();
    context.getValidationMatcherRegistry()
            .getValidationMatcherLibraries()
            .add(new ValidationMatcherConfig().getValidationMatcherLibrary());

    validator.validateJson(message,
            (JSONObject) new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE).parse(toJson(actualText)),
            (JSONObject) new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE).parse(toJson(expectedText)),
            new JsonMessageValidationContext(),
            context,
            JsonPath.parse(actualText));
}
 
Example #14
Source File: OutboundXmlDataDictionary.java    From citrus-simulator with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T translate(Node node, T value, TestContext context) {
    if (value instanceof String) {
        String toTranslate;
        if (!mappings.isEmpty()) {
            toTranslate = (String) super.translate(node, value, context);
        } else {
            toTranslate = (String) value;
        }

        if (toTranslate.equals(value)) {
            if (toTranslate.equals("true") || toTranslate.equals("false")) {
                return (T) toTranslate;
            } else if (Character.isDigit(toTranslate.charAt(0))) {
                return (T) (context.replaceDynamicContentInString("citrus:randomNumber(" + toTranslate.length() + ")"));
            } else if (toTranslate.startsWith("string")) {
                return (T) (context.replaceDynamicContentInString("citrus:randomString(" + toTranslate.length() + ")"));
            }
        } else {
            return (T) toTranslate;
        }
    }

    return super.translate(node, value, context);
}
 
Example #15
Source File: EndpointConsumerInterceptor.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    Object result = methodInvocation.proceed();
    if (isReceiveMethod(methodInvocation)) {
        final Optional<TestContext> testContext = getTestContext(methodInvocation);
        if (testContext.isPresent()) {
            final Optional<Message> message = getMessage(result);
            message.ifPresent(msg -> endpointMessageHandler.handleReceivedMessage(msg, testContext.get()));
        }
    }
    return result;
}
 
Example #16
Source File: WSDLFromURLRefFileTestIT.java    From apimanager-swagger-promote with Apache License 2.0 5 votes vote down vote up
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	description("Validates a WSDL-File can be taken from a URL using a REF-File.");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/ref-file-wsdl-${apiNumber}");
	variable("apiName", "Ref-File-WSDL from URL-${apiNumber}");
	

	
	echo("####### Importing API: '${apiName}' on path: '${apiPath}' for the first time from URL #######");
	createVariable(ImportTestAction.API_DEFINITION, "/com/axway/apim/test/files/wsdl/wsdl-file-with-username.url");
	createVariable(ImportTestAction.API_CONFIG, "/com/axway/apim/test/files/wsdl/wsdl-minimal-config.json");
	createVariable("status", "unpublished");
	createVariable("expectedReturnCode", "0");
	swaggerImport.doExecute(context);
	
	echo("####### Validate API: '${apiName}' on path: '${apiPath}' has been imported #######");
	http(builder -> builder.client("apiManager").send().get("/proxies").name("api").header("Content-Type", "application/json"));

	http(builder -> builder.client("apiManager").receive().response(HttpStatus.OK).messageType(MessageType.JSON)
		.validate("$.[?(@.path=='${apiPath}')].name", "${apiName}")
		.validate("$.[?(@.path=='${apiPath}')].state", "unpublished")
		.extractFromPayload("$.[?(@.path=='${apiPath}')].id", "apiId"));
	
	echo("####### Re-Import API from URL without a change #######");
	createVariable(ImportTestAction.API_DEFINITION, "/com/axway/apim/test/files/wsdl/wsdl-file-with-username.url");
	createVariable(ImportTestAction.API_CONFIG, "/com/axway/apim/test/files/wsdl/wsdl-minimal-config.json");
	createVariable("status", "unpublished");
	createVariable("expectedReturnCode", "10");
	swaggerImport.doExecute(context);
}
 
Example #17
Source File: CorrelationHandlerRegistry.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
/**
 * Finds handler in registered handlers that is able to handle given message. When handler is found return true
 * otherwise false.
 * @param request
 * @return
 */
public CorrelationHandler findHandlerFor(Message request) {
    for (Map.Entry<CorrelationHandler, TestContext> handlerEntry : registeredHandlers.entrySet()) {
        if (handlerEntry.getKey().isHandlerFor(request, handlerEntry.getValue())) {
            return handlerEntry.getKey();
        }
    }

    return null;
}
 
Example #18
Source File: EndpointProducerInterceptor.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    Object result = methodInvocation.proceed();
    if (isSendMethod(methodInvocation)) {
        final Optional<TestContext> testContext = getArgument(methodInvocation, TestContext.class);
        final Optional<Message> message = getArgument(methodInvocation, Message.class);
        if (testContext.isPresent() && message.isPresent()) {
            endpointMessageHandler.handleSentMessage(message.get(), testContext.get());
        }
    }
    return result;
}
 
Example #19
Source File: FtpSplitToDB_IT.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
@CitrusTest
public void testFtpSplitToDB(@CitrusResource TestCaseRunner runner) {
    cleanupDatabase(runner);

    runner.given(receive()
            .endpoint(ftpTestServer)
            .timeout(Duration.ofSeconds(SyndesisTestEnvironment.getDefaultTimeout()).toMillis())
            .message(FtpMessage.command(FTPCmd.RETR).arguments("todo.json")));

    runner.when(send()
            .endpoint(ftpTestServer)
            .message(FtpMessage.success()));

    runner.then(repeatOnError()
            .startsWith(1)
            .autoSleep(1000L)
            .until(new IteratingConditionExpression() {
                @Override
                public boolean evaluate(int index, TestContext context) {
                    return index > 10;
                }
            })
            .actions(query(sampleDb)
                    .statement("select count(*) as found_records from todo")
                    .validate("found_records", String.valueOf(3))));

    runner.then(query(sampleDb)
            .statement("select task, completed from todo")
            .validate("task", "FTP task #1", "FTP task #2", "FTP task #3")
            .validate("completed", "0", "1", "0"));
}
 
Example #20
Source File: UnpublishDeleteMustBeBreakingTestIT.java    From apimanager-swagger-promote with Apache License 2.0 5 votes vote down vote up
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	echo("####### This test makes sure, once an API is published, unpublishing or deleting it requires a force #######");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(4, true));
	variable("apiPath", "/check-is-breaking-${apiNumber}");
	variable("apiName", "Check-is-Breaking-${apiNumber}");

	
	echo("####### Importing API: '${apiName}' on path: '${apiPath}' as Published #######");
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/basic/4_flexible-status-config.json");
	createVariable("state", "published");
	createVariable("expectedReturnCode", "0");
	swaggerImport.doExecute(context);
	
	echo("####### Validate unpublishing it, will fail, with the need to enforce it #######");
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/basic/4_flexible-status-config.json");
	createVariable("state", "unpublished");
	createVariable("expectedReturnCode", "15");
	swaggerImport.doExecute(context);
	
	echo("####### Validate deleting it, will fail, with the need to enforce it #######");
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/basic/4_flexible-status-config.json");
	createVariable("state", "deleted");
	createVariable("expectedReturnCode", "15");
	swaggerImport.doExecute(context);
}
 
Example #21
Source File: WSDLFromURLRefFileInConfigurationTestIT.java    From apimanager-swagger-promote with Apache License 2.0 5 votes vote down vote up
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	description("Validates a WSDL-File can be taken from a URL using a REF-File described in API json configuration");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/ref-file-wsdl-in-configuration-${apiNumber}");
	variable("apiName", "Ref-File-WSDL in configuration from URL-${apiNumber}");
	

	
	echo("####### Importing API: '${apiName}' on path: '${apiPath}' for the first time from URL #######");
	createVariable(ImportTestAction.API_DEFINITION, "");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/basic/minimal-config-with-api-definition.json");
	createVariable("testAPIDefinition","./src/test/resources/com/axway/apim/test/files/wsdl/wsdl-file-with-username.url");
	createVariable("status", "unpublished");
	createVariable("expectedReturnCode", "0");
	swaggerImport.doExecute(context);
	
	echo("####### Validate API: '${apiName}' on path: '${apiPath}' has been imported #######");
	http(builder -> builder.client("apiManager").send().get("/proxies").name("api").header("Content-Type", "application/json"));

	http(builder -> builder.client("apiManager").receive().response(HttpStatus.OK).messageType(MessageType.JSON)
		.validate("$.[?(@.path=='${apiPath}')].name", "${apiName}")
		.validate("$.[?(@.path=='${apiPath}')].state", "unpublished")
		.extractFromPayload("$.[?(@.path=='${apiPath}')].id", "apiId"));
	
	echo("####### Re-Import API from URL without a change #######");
	createVariable(ImportTestAction.API_DEFINITION, "");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/basic/minimal-config-with-api-definition.json");
	createVariable("testAPIDefinition","./src/test/resources/com/axway/apim/test/files/wsdl/wsdl-file-with-username.url");
	createVariable("status", "unpublished");
	createVariable("expectedReturnCode", "10");
	swaggerImport.doExecute(context);
}
 
Example #22
Source File: CalculateIban.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
private TestAction calculateIban() {
    return new AbstractTestAction() {
        @Override
        public void doExecute(TestContext context) {
            final String queryParams = context.getVariable(QUERY_PARAMS.name(), String.class);
            final String sortCode = queryParameterService.getSortCode(queryParams);
            final String bankAccountNumber = queryParameterService.getBankAccountNumber(queryParams);
            final String jsonResponse = bankService.calculate(sortCode, bankAccountNumber).asJson();
            context.setVariable(JSON_RESPONSE.name(), jsonResponse);
        }
    };
}
 
Example #23
Source File: CorrelationHandlerRegistry.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
/**
 * Add new correlation manager to registry.
 * @param handler
 */
public void register(CorrelationHandler handler, TestContext context) {
    if (!registeredHandlers.keySet().contains(handler)) {
        registeredHandlers.put(handler, context);
    }

    while (registeredHandlers.size() > queueCapacity) {
        Stream.of(registeredHandlers.keySet()).limit(queueCapacity / 10)
                .collect(Collectors.toList())
                .parallelStream()
                .forEach(toDelete -> registeredHandlers.remove(toDelete));
    }
}
 
Example #24
Source File: EndpointMessageHandler.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
private void saveScenarioMessage(Message message, TestContext context, Direction direction) {
    Optional<Long> executionId = extractExecutionId(context);
    Optional<String> citrusMessageId = extractCitrusMessageId(message);
    if (executionId.isPresent() && citrusMessageId.isPresent()) {
        activityService.saveScenarioMessage(executionId.get(), direction,
                message.getPayload(String.class), citrusMessageId.get(), message.getHeaders());
    }
}
 
Example #25
Source File: XPathPayloadCorrelationHandler.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isHandlerFor(Message message, TestContext context) {
    boolean isIntermediateMessage;
    try {
        isIntermediateMessage = xPathPayloadMappingKeyExtractor.extractMappingKey(message).equals(context.replaceDynamicContentInString(value));
    } catch (RuntimeException e) {
        LOG.debug("Error checking whether message({}) is an intermediate message: {}", message.getId(), e.getMessage());
        isIntermediateMessage = false;
    }
    LOG.debug("Intermediate message({}): {}", message.getId(), isIntermediateMessage);
    return isIntermediateMessage;
}
 
Example #26
Source File: ScenarioEndpoint.java    From citrus-simulator with Apache License 2.0 5 votes vote down vote up
@Override
public void send(Message message, TestContext context) {
    messageSent(message, context);
    if (responseFutures.isEmpty()) {
        throw new SimulatorException("Failed to process scenario response message - missing response consumer");
    } else {
        responseFutures.pop().complete(message);
    }
}
 
Example #27
Source File: NoChangedOrgsUnpublishedAPI.java    From apimanager-swagger-promote with Apache License 2.0 5 votes vote down vote up
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	description("Making sure, organization are not conisdered as changes if desired state is Unpublished");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/no-change-org-unpublished-${apiNumber}");
	variable("apiName", "No-Change-Org-Unpublished-${apiNumber}");

	// Replication must fail, is Query-String option is enabled, but API-Manager hasn't configured it 
	echo("####### API-Config without queryString option - Must fail #######");		
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/organizations/1_api-with-client-orgs.json");
	createVariable("state", "unpublished");
	createVariable("orgName", "${orgName}");
	createVariable("orgName2", "${orgName2}");
	createVariable("expectedReturnCode", "0");
	swaggerImport.doExecute(context);
	
	echo("####### Re-Import the same - Must lead to a No-Change! #######");
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/organizations/1_api-with-client-orgs.json");
	createVariable("state", "unpublished");
	createVariable("orgName", "${orgName}");
	createVariable("orgName2", "${orgName2}");
	createVariable("expectedReturnCode", "10"); // No-Change is expected!
	swaggerImport.doExecute(context);
}
 
Example #28
Source File: IntiallyPublishedAPITestIT.java    From apimanager-swagger-promote with Apache License 2.0 5 votes vote down vote up
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	description("Import an API which initially has the status published.");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/initially-published-${apiNumber}");
	variable("apiName", "Initially-Published-API-${apiNumber}");

	
	echo("####### Importing API: '${apiName}' on path: '${apiPath}' for the first time #######");
	
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/basic/2_initially_published.json");
	createVariable("expectedReturnCode", "0");
	swaggerImport.doExecute(context);
	
	echo("####### Validate API: '${apiName}' on path: '${apiPath}' has been imported #######");
	http(builder -> builder.client("apiManager").send().get("/proxies").header("Content-Type", "application/json"));

	http(builder -> builder.client("apiManager").receive().response(HttpStatus.OK).messageType(MessageType.JSON)
		.validate("$.[?(@.path=='${apiPath}')].name", "${apiName}")
		.validate("$.[?(@.path=='${apiPath}')].state", "published")
		.validate("$.[?(@.path=='${apiPath}')].securityProfiles[0].devices[0].type", "apiKey")
		.extractFromPayload("$.[?(@.path=='${apiPath}')].id", "apiId"));
}
 
Example #29
Source File: RoutingPolicyTestIT.java    From apimanager-swagger-promote with Apache License 2.0 5 votes vote down vote up
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();	
	description("Test a Routing-Policy");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/routing-policy-test-${apiNumber}");
	variable("apiName", "Routing Policy Test ${apiNumber}");
	variable("status", "unpublished");
	

	echo("####### Importing API: '${apiName}' on path: '${apiPath}' with following settings: #######");
	createVariable("routePolicy", "Routing policy 1");
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/security/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/policies/1_routing-policy.json");
	createVariable("expectedReturnCode", "0");
	swaggerImport.doExecute(context);
	
	echo("####### Validate API: '${apiName}' on path: '${apiPath}' has correct settings #######");
	http(builder -> builder.client("apiManager").send()	.get("/proxies").header("Content-Type", "application/json"));

	http(builder -> builder.client("apiManager")
		.receive()
		.response(HttpStatus.OK)
		.messageType(MessageType.JSON)
		.validate("$.[?(@.path=='${apiPath}')].name", "${apiName}")
		.validate("$.[?(@.path=='${apiPath}')].state", "unpublished")
		.validate("$.[?(@.path=='${apiPath}')].outboundProfiles._default.routePolicy", "@assertThat(containsString(Routing policy 1))@")
		.extractFromPayload("$.[?(@.path=='${apiPath}')].id", "apiId"));
}
 
Example #30
Source File: SwaggerFromURLRefFileInConfigurationTestIT.java    From apimanager-swagger-promote with Apache License 2.0 5 votes vote down vote up
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	description("Validates a Swagger-File can be taken from a URL using a REF-File described in API json configuration");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/ref-file-swagger-in-configuration-${apiNumber}");
	variable("apiName", "Ref-File-Swagger in configuration from URL-${apiNumber}");
	

	
	echo("####### Importing API: '${apiName}' on path: '${apiPath}' for the first time from URL #######");
	createVariable(ImportTestAction.API_DEFINITION,  "");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/basic/minimal-config-with-api-definition.json");
	createVariable("testAPIDefinition","./src/test/resources/com/axway/apim/test/files/basic/swagger-file-with-username.url");
	createVariable("status", "unpublished");
	createVariable("expectedReturnCode", "0");
	swaggerImport.doExecute(context);
	
	echo("####### Validate API: '${apiName}' on path: '${apiPath}' has been imported #######");
	http(builder -> builder.client("apiManager").send().get("/proxies").header("Content-Type", "application/json"));

	http(builder -> builder.client("apiManager").receive().response(HttpStatus.OK).messageType(MessageType.JSON)
		.validate("$.[?(@.path=='${apiPath}')].name", "${apiName}")
		.validate("$.[?(@.path=='${apiPath}')].state", "unpublished")
		.extractFromPayload("$.[?(@.path=='${apiPath}')].id", "apiId"));
	
	echo("####### Re-Import API from URL without a change #######");
	createVariable(ImportTestAction.API_DEFINITION,  "");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/basic/minimal-config-with-api-definition.json");
	createVariable("testAPIDefinition","./src/test/resources/com/axway/apim/test/files/basic/swagger-file-with-username.url");
	createVariable("status", "unpublished");
	createVariable("expectedReturnCode", "10");
	swaggerImport.doExecute(context);
}