com.thoughtworks.go.plugin.api.response.validation.ValidationResult Java Examples

The following examples show how to use com.thoughtworks.go.plugin.api.response.validation.ValidationResult. 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: PackageRepositoryServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInvokePluginValidationsBeforeSavingPackageRepository() throws Exception {
    String pluginId = "yum";
    PackageRepository packageRepository = new PackageRepository();
    RepositoryMetadataStore.getInstance().addMetadataFor(pluginId, new PackageConfigurations());
    packageRepository.setPluginConfiguration(new PluginConfiguration(pluginId, "1.0"));
    packageRepository.getConfiguration().add(ConfigurationPropertyMother.create("url", false, "junk-url"));

    ArgumentCaptor<RepositoryConfiguration> packageConfigurationsArgumentCaptor = ArgumentCaptor.forClass(RepositoryConfiguration.class);
    ValidationResult expectedValidationResult = new ValidationResult();
    expectedValidationResult.addError(new ValidationError("url", "url format incorrect"));

    when(pluginManager.getPluginDescriptorFor(pluginId)).thenReturn(getPluginDescriptor("yum"));
    when(packageRepositoryExtension.isRepositoryConfigurationValid(eq(pluginId), packageConfigurationsArgumentCaptor.capture())).thenReturn(expectedValidationResult);

    service = new PackageRepositoryService(pluginManager, packageRepositoryExtension, goConfigService, securityService, entityHashingService);
    service.performPluginValidationsFor(packageRepository);
    assertThat(packageRepository.getConfiguration().get(0).getConfigurationValue().errors().getAllOn("value"), is(Arrays.asList("url format incorrect")));
}
 
Example #2
Source File: PluginServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void createPluginSettings_shouldValidatePluginSettingUsingExtensionAndReturnUnprocessableEntityWhenThereIsAValidationError() {
    setUpElasticPluginForTheTest(true);
    when(pluginDao.findPlugin(elasticAgentPluginId)).thenReturn(new NullPlugin());

    final ValidationResult validationResult = new ValidationResult();
    validationResult.addError(new ValidationError("key-1", "error-message"));
    when(elasticAgentExtension.validatePluginSettings(eq(elasticAgentPluginId), any(PluginSettingsConfiguration.class))).thenReturn(validationResult);
    when(pluginSettings.hasErrors()).thenReturn(true);

    pluginService.createPluginSettings(pluginSettings, currentUser, result);

    verify(pluginDao, times(0)).saveOrUpdate(any());
    verify(elasticAgentExtension, times(0)).notifyPluginSettingsChange(eq(elasticAgentPluginId), anyMap());
    verify(result, times(1)).unprocessableEntity("Save failed. There are errors in the plugin settings. Please fix them and resubmit.");
    verifyNoMoreInteractions(result);
}
 
Example #3
Source File: PackageDefinitionService.java    From gocd with Apache License 2.0 6 votes vote down vote up
public void performPluginValidationsFor(final PackageDefinition packageDefinition) {
    String pluginId = packageDefinition.getRepository().getPluginConfiguration().getId();


    ValidationResult validationResult = packageRepositoryExtension.isPackageConfigurationValid(pluginId, buildPackageConfigurations(packageDefinition), buildRepositoryConfigurations(packageDefinition.getRepository()));
    for (ValidationError error : validationResult.getErrors()) {
        packageDefinition.addConfigurationErrorFor(error.getKey(), error.getMessage());
    }
    for (ConfigurationProperty configurationProperty : packageDefinition.getConfiguration()) {
        String key = configurationProperty.getConfigurationKey().getName();
        if (PackageMetadataStore.getInstance().hasOption(packageDefinition.getRepository().getPluginConfiguration().getId(), key, PackageConfiguration.REQUIRED)) {
            if (configurationProperty.getValue().isEmpty() && configurationProperty.doesNotHaveErrorsAgainstConfigurationValue()) {
                configurationProperty.addErrorAgainstConfigurationValue("Field: '" + configurationProperty.getConfigurationKey().getName() + "' is required");
            }
        }
    }
}
 
Example #4
Source File: PluginServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void validatePluginSettingsFor_shouldNotAddAnyErrorInPluginSettingsObjectWhenThereIsNoValidationError() {
    final ElasticAgentPluginInfo elasticAgentPluginInfo = mockElasticAgentPluginInfo(getPluggableInstanceSettings());

    addPluginSettingsMetadataToStore(elasticAgentPluginId, ELASTIC_AGENT_EXTENSION, getPluginSettingsConfiguration());
    when(elasticAgentExtension.extensionName()).thenReturn(ELASTIC_AGENT_EXTENSION);
    when(elasticAgentExtension.canHandlePlugin(elasticAgentPluginId)).thenReturn(true);
    when(elasticAgentExtension.validatePluginSettings(eq(elasticAgentPluginId), any(PluginSettingsConfiguration.class)))
            .thenReturn(new ValidationResult());

    PluginSettings pluginSettings = PluginSettings.from(getPlugin(elasticAgentPluginId), elasticAgentPluginInfo);

    pluginService.validatePluginSettings(pluginSettings);

    assertThat(pluginSettings.hasErrors(), is(false));
}
 
Example #5
Source File: PluginServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void updatePluginSettings_shouldUpdateThePluginSettingsWhenThereIsNoValidationFailure() {
    final Plugin plugin = getPlugin(elasticAgentPluginId);
    setUpElasticPluginForTheTest(true);
    when(pluginDao.findPlugin(elasticAgentPluginId)).thenReturn(plugin);
    when(entityHashingService.hashForEntity(any(PluginSettings.class))).thenReturn("foo");
    when(pluginSettings.toPluginSettingsConfiguration()).thenReturn(mock(PluginSettingsConfiguration.class));

    when(elasticAgentExtension.validatePluginSettings(eq(elasticAgentPluginId), any(PluginSettingsConfiguration.class)))
            .thenReturn(new ValidationResult());

    when(pluginSettings.hasErrors()).thenReturn(false);
    when(result.isSuccessful()).thenReturn(true);

    pluginService.updatePluginSettings(pluginSettings, currentUser, result, "foo");

    verify(pluginDao, times(1)).saveOrUpdate(plugin);
    verify(elasticAgentExtension, times(1)).notifyPluginSettingsChange(eq(elasticAgentPluginId), anyMap());
    verify(result, times(1)).isSuccessful();
    verify(entityHashingService, times(1)).removeFromCache(pluginSettings, pluginSettings.getPluginId());
    verifyNoMoreInteractions(result);
}
 
Example #6
Source File: PluginServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIgnoreErrorsWhileNotifyingPluginSettingChange() {
    setUpElasticPluginForTheTest(true);
    when(pluginDao.findPlugin(elasticAgentPluginId)).thenReturn(new NullPlugin());
    when(pluginSettings.toPluginSettingsConfiguration()).thenReturn(mock(PluginSettingsConfiguration.class));

    when(result.isSuccessful()).thenReturn(true);
    when(pluginSettings.hasErrors()).thenReturn(false);
    when(elasticAgentExtension.validatePluginSettings(eq(elasticAgentPluginId), any(PluginSettingsConfiguration.class))).thenReturn(new ValidationResult());

    doThrow(new RuntimeException()).when(elasticAgentExtension).notifyPluginSettingsChange(eq(elasticAgentPluginId), anyMap());

    pluginService.createPluginSettings(pluginSettings, currentUser, result);

    verify(pluginDao, times(1)).saveOrUpdate(any());
    verify(elasticAgentExtension).notifyPluginSettingsChange(eq(elasticAgentPluginId), anyMap());
    assertTrue(result.isSuccessful());
}
 
Example #7
Source File: JsonBasedTaskExtensionHandler_V1.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Override
public ValidationResult toValidationResult(String responseBody) {
    ValidationResult validationResult = new ValidationResult();
    ArrayList<String> exceptions = new ArrayList<>();
    try {
        Map result = (Map) new GsonBuilder().create().fromJson(responseBody, Object.class);
        if (result == null) return validationResult;
        final Map<String, Object> errors = (Map<String, Object>) result.get("errors");
        if (errors != null) {
            for (Map.Entry<String, Object> entry : errors.entrySet()) {
                if (!(entry.getValue() instanceof String)) {
                    exceptions.add(String.format("Key: '%s' - The Json for Validation Request must contain a not-null error message of type String", entry.getKey()));
                } else {
                    validationResult.addError(new ValidationError(entry.getKey(), entry.getValue().toString()));
                }
            }
        }
        if (!exceptions.isEmpty()) {
            throw new RuntimeException(StringUtils.join(exceptions, ", "));
        }
        return validationResult;
    } catch (Exception e) {
        LOGGER.error("Error occurred while converting the Json to Validation Result. Error: {}. The Json received was '{}'.", e.getMessage(), responseBody);
        throw new RuntimeException(String.format("Error occurred while converting the Json to Validation Result. Error: %s.", e.getMessage()));
    }
}
 
Example #8
Source File: PluggableScmServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldValidateMandatoryAndSecureFieldsForSCM() {
    SCMConfiguration scmConfig = new SCMConfiguration(new SCMProperty("KEY2").with(Property.REQUIRED, true).with(Property.SECURE, true));
    scmConfigurations.add(scmConfig);

    Configuration configuration = new Configuration(ConfigurationPropertyMother.create("KEY1"), ConfigurationPropertyMother.create("KEY2", true, ""));
    SCM modifiedSCM = new SCM("scm-id", new PluginConfiguration(pluginId, "1"), configuration);
    ValidationResult validationResult = new ValidationResult();
    when(scmExtension.isSCMConfigurationValid(eq(modifiedSCM.getPluginConfiguration().getId()), any(SCMPropertyConfiguration.class))).thenReturn(validationResult);

    pluggableScmService.validate(modifiedSCM);

    final List<ValidationError> validationErrors = validationResult.getErrors();
    assertFalse(validationErrors.isEmpty());
    final ValidationError validationErrorForKey1 = getValidationErrorFor(validationErrors, "KEY1");
    assertNotNull(validationErrorForKey1);
    assertThat(validationErrorForKey1.getMessage(), is("This field is required"));
    final ValidationError validationErrorForKey2 = getValidationErrorFor(validationErrors, "KEY2");
    assertNotNull(validationErrorForKey2);
    assertThat(validationErrorForKey2.getMessage(), is("This field is required"));
}
 
Example #9
Source File: ExternalArtifactsServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldMapPluginValidationErrorsToConfigrationProperties() {
    Configuration configuration = new Configuration();
    configuration.add(ConfigurationPropertyMother.create("Image", false, "alpine"));
    configuration.add(ConfigurationPropertyMother.create("Tag", false, "fml"));

    pluggableArtifactConfig.setConfiguration(configuration);

    ValidationResult validationResult = new ValidationResult();
    validationResult.addError(new ValidationError("Image", "invalid"));
    validationResult.addError(new ValidationError("Tag", "invalid"));
    ArtifactStore artifactStore = mock(ArtifactStore.class);
    when(artifactStore.getPluginId()).thenReturn(pluginId);

    when(artifactExtension.validatePluggableArtifactConfig(any(String.class), any())).thenReturn(validationResult);

    externalArtifactsService.validateExternalArtifactConfig(pluggableArtifactConfig, artifactStore, true);

    assertThat(configuration.getProperty("Image").errors().get("Image").get(0), is("invalid"));
    assertThat(configuration.getProperty("Tag").errors().get("Tag").get(0), is("invalid"));
}
 
Example #10
Source File: PluggableScmServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void isValidShouldMapPluginValidationErrorsToPluggableSCMForMissingConfigurations() {
    PluginConfiguration pluginConfiguration = new PluginConfiguration("plugin_id", "version");

    ValidationResult validationResult = new ValidationResult();
    validationResult.addError(new ValidationError("url", "URL is a required field"));

    SCM scmConfig = mock(SCM.class);

    when(scmConfig.doesPluginExist()).thenReturn(true);
    when(scmConfig.getPluginConfiguration()).thenReturn(pluginConfiguration);
    when(scmConfig.getConfiguration()).thenReturn(new Configuration());
    when(scmExtension.isSCMConfigurationValid(any(String.class), any(SCMPropertyConfiguration.class))).thenReturn(validationResult);

    assertFalse(pluggableScmService.isValid(scmConfig));
    verify(scmConfig).addError("url", "URL is a required field");
}
 
Example #11
Source File: ElasticAgentProfileConfigurationValidator.java    From gocd with Apache License 2.0 6 votes vote down vote up
public void validate(ElasticProfile elasticAgentProfile, String pluginId) {
    try {
        ValidationResult result = elasticAgentExtension.validate(pluginId, elasticAgentProfile.getConfigurationAsMap(true));

        if (!result.isSuccessful()) {
            for (ValidationError error : result.getErrors()) {
                ConfigurationProperty property = elasticAgentProfile.getProperty(error.getKey());

                if (property == null) {
                    elasticAgentProfile.addNewConfiguration(error.getKey(), false);
                    property = elasticAgentProfile.getProperty(error.getKey());
                }
                property.addError(error.getKey(), error.getMessage());
            }
        }
    } catch (RecordNotFoundException e) {
        elasticAgentProfile.addError("pluginId", String.format("Unable to validate Elastic Agent Profile configuration, missing plugin: %s", pluginId));
    }
}
 
Example #12
Source File: ExternalArtifactsService.java    From gocd with Apache License 2.0 6 votes vote down vote up
public void validateExternalArtifactConfig(PluggableArtifactConfig preprocessedPluggableArtifactConfig, ArtifactStore artifactStore, boolean addPluginIdError) {
    if (preprocessedPluggableArtifactConfig.hasValidPluginAndStore(artifactStore)) {
        String pluginId = artifactStore.getPluginId();
        try {
            ValidationResult validationResult = artifactExtension.validatePluggableArtifactConfig(pluginId, preprocessedPluggableArtifactConfig.getConfiguration().getConfigurationAsMap(true));
            mapErrorsToConfiguration(validationResult, preprocessedPluggableArtifactConfig.getConfiguration(), preprocessedPluggableArtifactConfig);

        } catch (RecordNotFoundException e) {
            preprocessedPluggableArtifactConfig.addError("pluginId", String.format("Plugin with id `%s` is not found.", pluginId));
        }
    } else {
        if (addPluginIdError) {
            preprocessedPluggableArtifactConfig.addError("pluginId", "Could not determine the plugin to perform the plugin validations. Possible reasons: artifact store does not exist or plugin is not installed.");
        }
    }
}
 
Example #13
Source File: PluginService.java    From gocd with Apache License 2.0 6 votes vote down vote up
void validatePluginSettings(PluginSettings pluginSettings) {
    pluginSettings.validateTree();
    if (pluginSettings.hasErrors()) {
        return;
    }

    final String pluginId = pluginSettings.getPluginId();
    final PluginSettingsConfiguration configuration = pluginSettings.toPluginSettingsConfiguration();

    final GoPluginExtension extension = findExtensionWhichCanHandleSettingsFor(pluginId);
    if (extension == null) {
        throw new IllegalArgumentException(String.format("Plugin '%s' does not exist or does not implement settings validation.", pluginId));
    }

    final ValidationResult result = extension.validatePluginSettings(pluginId, configuration);
    if (!result.isSuccessful()) {
        for (ValidationError error : result.getErrors()) {
            pluginSettings.populateErrorMessageFor(error.getKey(), error.getMessage());
        }
    }
}
 
Example #14
Source File: TaskExtensionTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldValidateTask() {
    GoPluginApiResponse response = mock(GoPluginApiResponse.class);
    TaskExtension jsonBasedTaskExtension = new TaskExtension(pluginManager, extensionsRegistry);
    TaskConfig taskConfig = mock(TaskConfig.class);

    when(response.responseCode()).thenReturn(DefaultGoApiResponse.SUCCESS_RESPONSE_CODE);
    when(pluginManager.isPluginOfType(PLUGGABLE_TASK_EXTENSION, pluginId)).thenReturn(true);
    when(response.responseBody()).thenReturn("{\"errors\":{\"key\":\"error\"}}");
    when(pluginManager.submitTo(eq(pluginId), eq(PLUGGABLE_TASK_EXTENSION), any(GoPluginApiRequest.class))).thenReturn(response);

    ValidationResult validationResult = jsonBasedTaskExtension.validate(pluginId, taskConfig);

    verify(pluginManager).submitTo(eq(pluginId), eq(PLUGGABLE_TASK_EXTENSION), any(GoPluginApiRequest.class));
    assertFalse(validationResult.isSuccessful());
    assertEquals(validationResult.getErrors().get(0).getKey(), "key");
    assertEquals(validationResult.getErrors().get(0).getMessage(), "error");
}
 
Example #15
Source File: PluginConfig.java    From go-generic-artifactory-poller with Apache License 2.0 6 votes vote down vote up
public ValidationResult isPackageConfigurationValid(PackageConfiguration packageConfig, RepositoryConfiguration repoConfig) {
    GenericArtifactoryPackageConfig genericArtifactoryPackageConfig = new GenericArtifactoryPackageConfig(packageConfig);
    ValidationResult validationResult = genericArtifactoryPackageConfig.validatePackagePath();

    if(!validationResult.isSuccessful()){
        return validationResult;
    }

    validationResult = genericArtifactoryPackageConfig.validatePackageId();

    if(!validationResult.isSuccessful()){
        return validationResult;
    }

    detectInvalidKeys(packageConfig, validationResult, GenericArtifactoryPackageConfig.getValidKeys());

    return validationResult;
}
 
Example #16
Source File: PluggableScmServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldValidateSCM() {
    SCMConfiguration scmConfig = new SCMConfiguration(new SCMProperty("KEY2").with(Property.REQUIRED, false));
    scmConfigurations.add(scmConfig);

    Configuration configuration = new Configuration(ConfigurationPropertyMother.create("KEY1"));
    SCM modifiedSCM = new SCM("scm-id", new PluginConfiguration(pluginId, "1"), configuration);
    ValidationResult validationResult = new ValidationResult();
    validationResult.addError(new ValidationError("KEY1", "error message"));
    when(scmExtension.isSCMConfigurationValid(eq(modifiedSCM.getPluginConfiguration().getId()), any(SCMPropertyConfiguration.class))).thenReturn(validationResult);

    pluggableScmService.validate(modifiedSCM);

    assertFalse(modifiedSCM.getConfiguration().getProperty("KEY1").errors().isEmpty());
    assertThat(modifiedSCM.getConfiguration().getProperty("KEY1").errors().firstError(), is("error message"));
    verify(scmExtension).isSCMConfigurationValid(eq(modifiedSCM.getPluginConfiguration().getId()), any(SCMPropertyConfiguration.class));
}
 
Example #17
Source File: PackageDefinitionServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPerformPluginValidationsBeforeValidationsByGoAndGoDoesNotAddErrorIfAlreadyPresent() throws Exception {
    Configuration configuration = new Configuration();
    configuration.add(ConfigurationPropertyMother.create("required-field", false, ""));
    PackageDefinition packageDefinition = PackageDefinitionMother.create("1", "name", configuration, packageRepository);

    ValidationResult expectedValidationResult = new ValidationResult();
    expectedValidationResult.addError(new ValidationError("required-field", "error-one"));
    expectedValidationResult.addError(new ValidationError("required-field", "error-two"));

    when(packageRepositoryExtension.isPackageConfigurationValid(eq(packageRepository.getPluginConfiguration().getId()),
            any(com.thoughtworks.go.plugin.api.material.packagerepository.PackageConfiguration.class),
            any(RepositoryConfiguration.class))).thenReturn(expectedValidationResult);
    service.performPluginValidationsFor(packageDefinition);
    assertThat(packageDefinition.getConfiguration().get(0).getConfigurationValue().errors().getAllOn("value").size(), is(2));
    assertThat(packageDefinition.getConfiguration().get(0).getConfigurationValue().errors().getAllOn("value"), is(hasItems("error-one", "error-two")));
}
 
Example #18
Source File: PluggableTaskServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void isValidShouldMapPluginValidationErrorsToPluggableTaskConfigrations() {
    PluginConfiguration pluginConfiguration = new PluginConfiguration("plugin_id", "version");
    Configuration configuration = new Configuration();
    configuration.add(ConfigurationPropertyMother.create("source", false, "src_dir"));
    configuration.add(ConfigurationPropertyMother.create("destination", false, "dest_dir"));

    ValidationResult validationResult = new ValidationResult();
    validationResult.addError(new ValidationError("source", "source directory format is invalid"));
    validationResult.addError(new ValidationError("destination", "destination directory format is invalid"));

    PluggableTask pluggableTask = mock(PluggableTask.class);

    when(pluggableTask.isValid()).thenReturn(true);
    when(pluggableTask.toTaskConfig()).thenReturn(new TaskConfig());
    when(pluggableTask.getPluginConfiguration()).thenReturn(pluginConfiguration);
    when(pluggableTask.getConfiguration()).thenReturn(configuration);
    when(taskExtension.validate(any(String.class), any(TaskConfig.class))).thenReturn(validationResult);

    assertFalse(pluggableTaskService.isValid(pluggableTask));
    assertThat(configuration.getProperty("source").errors().get("source").get(0), is("source directory format is invalid"));
    assertThat(configuration.getProperty("destination").errors().get("destination").get(0), is("destination directory format is invalid"));
}
 
Example #19
Source File: PluginServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void validatePluginSettingsFor_shouldPopulateValidationErrorsInPluginSettingsObject() {
    final ElasticAgentPluginInfo elasticAgentPluginInfo = mockElasticAgentPluginInfo(getPluggableInstanceSettings());
    final ValidationResult validationResult = new ValidationResult();
    validationResult.addError(new ValidationError("key-1", "m1"));
    validationResult.addError(new ValidationError("key-3", "m3"));

    addPluginSettingsMetadataToStore(elasticAgentPluginId, ELASTIC_AGENT_EXTENSION, getPluginSettingsConfiguration());
    when(elasticAgentExtension.extensionName()).thenReturn(ELASTIC_AGENT_EXTENSION);
    when(elasticAgentExtension.canHandlePlugin(elasticAgentPluginId)).thenReturn(true);
    when(elasticAgentExtension.validatePluginSettings(eq(elasticAgentPluginId), any(PluginSettingsConfiguration.class)))
            .thenReturn(validationResult);

    PluginSettings pluginSettings = PluginSettings.from(getPlugin(elasticAgentPluginId), elasticAgentPluginInfo);

    pluginService.validatePluginSettings(pluginSettings);

    assertThat(pluginSettings.hasErrors(), is(true));
    assertThat(pluginSettings.getErrorFor("key-1"), is(Arrays.asList("m1")));
    assertThat(pluginSettings.getErrorFor("key-3"), is(Arrays.asList("m3")));
}
 
Example #20
Source File: PluggableTaskServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldValidateMandatoryFields() {
    Configuration configuration = new Configuration(ConfigurationPropertyMother.create("KEY1"));
    PluggableTask modifiedTask = new PluggableTask(new PluginConfiguration(pluginId, "1"), configuration);
    ValidationResult validationResult = new ValidationResult();
    when(taskExtension.validate(eq(modifiedTask.getPluginConfiguration().getId()), any(TaskConfig.class))).thenReturn(validationResult);

    pluggableTaskService.validate(modifiedTask);

    final List<ValidationError> validationErrors = validationResult.getErrors();
    assertFalse(validationErrors.isEmpty());
    final ValidationError validationError = validationErrors.stream().filter(new Predicate<ValidationError>() {
        @Override
        public boolean test(ValidationError item) {
            return ((ValidationError) item).getKey().equals("KEY1");
        }
    }).findFirst().orElse(null);
    assertNotNull(validationError);
    assertThat(validationError.getMessage(), is("This field is required"));
}
 
Example #21
Source File: PluginServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void updatePluginSettings_shouldValidatePluginSettingUsingExtensionAndReturnUnprocessableEntityWhenThereIsAValidationFailure() {
    setUpElasticPluginForTheTest(true);
    when(pluginDao.findPlugin(elasticAgentPluginId)).thenReturn(getPlugin(elasticAgentPluginId));

    final ValidationResult validationResult = new ValidationResult();
    validationResult.addError(new ValidationError("key-1", "error-message"));
    when(elasticAgentExtension.validatePluginSettings(eq(elasticAgentPluginId), any(PluginSettingsConfiguration.class))).thenReturn(validationResult);
    when(pluginSettings.hasErrors()).thenReturn(true);
    when(entityHashingService.hashForEntity(any(PluginSettings.class))).thenReturn("foo");
    when(result.isSuccessful()).thenReturn(false);

    pluginService.updatePluginSettings(pluginSettings, currentUser, result, "foo");

    verify(pluginDao, times(0)).saveOrUpdate(any());
    verify(elasticAgentExtension, times(0)).notifyPluginSettingsChange(eq(elasticAgentPluginId), anyMap());
    verify(result, times(1)).unprocessableEntity("Save failed. There are errors in the plugin settings. Please fix them and resubmit.");
}
 
Example #22
Source File: ArtifactExtensionTestBase.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldValidatePluggableArtifactConfig() {
    String responseBody = "[{\"message\":\"Filename must not be blank.\",\"key\":\"Filename\"}]";

    when(pluginManager.submitTo(eq(PLUGIN_ID), eq(ARTIFACT_EXTENSION), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, responseBody));

    ValidationResult validationResult = artifactExtension.validatePluggableArtifactConfig(PLUGIN_ID, Collections.singletonMap("Filename", ""));

    final GoPluginApiRequest request = requestArgumentCaptor.getValue();

    assertThat(request.extension(), is(ARTIFACT_EXTENSION));
    assertThat(request.requestName(), is(REQUEST_PUBLISH_ARTIFACT_VALIDATE));
    assertThat(request.requestBody(), is("{\"Filename\":\"\"}"));

    assertThat(validationResult.isSuccessful(), is(false));
    assertThat(validationResult.getErrors(), containsInAnyOrder(
            new ValidationError("Filename", "Filename must not be blank.")
    ));
}
 
Example #23
Source File: ArtifactExtensionTestBase.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldValidateArtifactStoreConfig() {
    String responseBody = "[{\"message\":\"ACCESS_KEY must not be blank.\",\"key\":\"ACCESS_KEY\"}]";

    when(pluginManager.submitTo(eq(PLUGIN_ID), eq(ARTIFACT_EXTENSION), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, responseBody));

    ValidationResult validationResult = artifactExtension.validateArtifactStoreConfig(PLUGIN_ID, Collections.singletonMap("ACCESS_KEY", ""));

    final GoPluginApiRequest request = requestArgumentCaptor.getValue();

    assertThat(request.extension(), is(ARTIFACT_EXTENSION));
    assertThat(request.requestName(), is(REQUEST_STORE_CONFIG_VALIDATE));
    assertThat(request.requestBody(), is("{\"ACCESS_KEY\":\"\"}"));

    assertThat(validationResult.isSuccessful(), is(false));
    assertThat(validationResult.getErrors(), containsInAnyOrder(
            new ValidationError("ACCESS_KEY", "ACCESS_KEY must not be blank.")
    ));
}
 
Example #24
Source File: JsonBasedTaskExtensionHandler_V1Test.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldConvertJsonResponseToValidationResultWhenValidationFails() {
    String jsonResponse = "{\"errors\":{\"key1\":\"err1\",\"key2\":\"err2\"}}";

    TaskConfig configuration = new TaskConfig();
    TaskConfigProperty property = new TaskConfigProperty("URL", "http://foo");
    property.with(Property.SECURE, false);
    property.with(Property.REQUIRED, true);
    configuration.add(property);

    ValidationResult result = new JsonBasedTaskExtensionHandler_V1().toValidationResult(jsonResponse);

    Assert.assertThat(result.isSuccessful(), is(false));


    ValidationError error1 = result.getErrors().get(0);
    ValidationError error2 = result.getErrors().get(1);

    Assert.assertThat(error1.getKey(), is("key1"));
    Assert.assertThat(error1.getMessage(), is("err1"));
    Assert.assertThat(error2.getKey(), is("key2"));
    Assert.assertThat(error2.getMessage(), is("err2"));
}
 
Example #25
Source File: TaskExtensionTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTalkToPluginToValidatePluginSettings() throws Exception {
    extension.registerHandler("1.0", pluginSettingsJSONMessageHandler);
    extension.messageHandlerMap.put("1.0", jsonMessageHandler);

    String requestBody = "expected-request";
    when(pluginSettingsJSONMessageHandler.requestMessageForPluginSettingsValidation(pluginSettingsConfiguration)).thenReturn(requestBody);

    String responseBody = "expected-response";
    ValidationResult deserializedResponse = new ValidationResult();
    when(pluginSettingsJSONMessageHandler.responseMessageForPluginSettingsValidation(responseBody)).thenReturn(deserializedResponse);

    when(pluginManager.isPluginOfType(PLUGGABLE_TASK_EXTENSION, pluginId)).thenReturn(true);
    when(pluginManager.submitTo(eq(pluginId), eq(PLUGGABLE_TASK_EXTENSION), requestArgumentCaptor.capture())).thenReturn(DefaultGoPluginApiResponse.success(responseBody));

    ValidationResult response = extension.validatePluginSettings(pluginId, pluginSettingsConfiguration);

    assertRequest(requestArgumentCaptor.getValue(), PLUGGABLE_TASK_EXTENSION, "1.0", PluginSettingsConstants.REQUEST_VALIDATE_PLUGIN_SETTINGS, requestBody);
    verify(pluginSettingsJSONMessageHandler).responseMessageForPluginSettingsValidation(responseBody);
    assertSame(response, deserializedResponse);
}
 
Example #26
Source File: ArtifactStoreConfigCommandTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldPassValidationIfIdIsNotNull() {
    HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
    ArtifactStore artifactStore = new ArtifactStore("docker", "cd.go.artifact.docker");
    cruiseConfig.getArtifactStores().add(artifactStore);
    when(extension.validateArtifactStoreConfig(eq("cd.go.artifact.docker"), anyMap())).thenReturn(new ValidationResult());

    StubCommand command = new StubCommand(goConfigService, artifactStore, extension, currentUser, result);
    boolean isValid = command.isValid(cruiseConfig);
    assertTrue(isValid);
}
 
Example #27
Source File: PackageRepositoryService.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void addErrorsToConfiguration(ValidationResult validationResult, PackageRepository packageRepository) {
    for (ValidationError validationError : validationResult.getErrors()) {
        ConfigurationProperty property = packageRepository.getConfiguration().getProperty(validationError.getKey());

        if (property != null) {
            property.addError(validationError.getKey(), validationError.getMessage());
        } else {
            String validationErrorKey = StringUtils.isBlank(validationError.getKey()) ? PackageRepository.CONFIGURATION : validationError.getKey();
            packageRepository.addError(validationErrorKey, validationError.getMessage());
        }
    }
}
 
Example #28
Source File: ElasticAgentExtensionV4Test.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldValidateProfile() {
    String responseBody = "[{\"message\":\"Url must not be blank.\",\"key\":\"Url\"},{\"message\":\"SearchBase must not be blank.\",\"key\":\"SearchBase\"}]";
    when(pluginManager.submitTo(eq(PLUGIN_ID), eq(ELASTIC_AGENT_EXTENSION), requestArgumentCaptor.capture())).thenReturn(DefaultGoPluginApiResponse.success(responseBody));

    final ValidationResult result = extensionV4.validateElasticProfile(PLUGIN_ID, Collections.emptyMap());

    assertThat(result.isSuccessful(), is(false));
    assertThat(result.getErrors(), containsInAnyOrder(
            new ValidationError("Url", "Url must not be blank."),
            new ValidationError("SearchBase", "SearchBase must not be blank.")
    ));

    assertExtensionRequest("4.0", REQUEST_VALIDATE_PROFILE, "{}");
}
 
Example #29
Source File: ElasticAgentExtensionConverterV5Test.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleValidationResponse() {
    String responseBody = "[{\"key\":\"key-one\",\"message\":\"error on key one\"}, {\"key\":\"key-two\",\"message\":\"error on key two\"}]";
    ValidationResult result = new ElasticAgentExtensionConverterV5().getElasticProfileValidationResultResponseFromBody(responseBody);
    assertThat(result.isSuccessful(), is(false));
    assertThat(result.getErrors().size(), is(2));
    assertThat(result.getErrors().get(0).getKey(), is("key-one"));
    assertThat(result.getErrors().get(0).getMessage(), is("error on key one"));
    assertThat(result.getErrors().get(1).getKey(), is("key-two"));
    assertThat(result.getErrors().get(1).getMessage(), is("error on key two"));
}
 
Example #30
Source File: SecretsExtensionV1Test.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
void shouldTalkToPlugin_toValidateSecretsConfig() {
    String responseBody = "[{\"message\":\"Vault Url cannot be blank.\",\"key\":\"Url\"},{\"message\":\"Path cannot be blank.\",\"key\":\"Path\"}]";
    when(pluginManager.submitTo(eq(PLUGIN_ID), eq(SECRETS_EXTENSION), requestArgumentCaptor.capture())).thenReturn(DefaultGoPluginApiResponse.success(responseBody));

    final ValidationResult result = secretsExtensionV1.validateSecretsConfig(PLUGIN_ID, singletonMap("username", "some_name"));

    assertThat(result.isSuccessful()).isFalse();
    assertThat(result.getErrors()).contains(new ValidationError("Url", "Vault Url cannot be blank."), new ValidationError("Path", "Path cannot be blank."));

    assertExtensionRequest(REQUEST_VALIDATE_SECRETS_CONFIG, "{\"username\":\"some_name\"}");
}