servicesContainer.addSingleton(QProfileProjectOperations.class);
servicesContainer.addSingleton(QProfileProjectLookup.class);
servicesContainer.addSingleton(QProfileBackup.class);
+ servicesContainer.addSingleton(QProfileExporter.class);
// users
servicesContainer.addSingleton(HibernateUserFinder.class);
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2013 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+package org.sonar.server.qualityprofile;
+
+import com.google.common.collect.ArrayListMultimap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Multimap;
+import org.apache.commons.lang.StringUtils;
+import org.apache.ibatis.session.SqlSession;
+import org.sonar.api.ServerComponent;
+import org.sonar.api.profiles.ProfileImporter;
+import org.sonar.api.profiles.RulesProfile;
+import org.sonar.api.rules.ActiveRule;
+import org.sonar.api.rules.ActiveRuleParam;
+import org.sonar.api.rules.RulePriority;
+import org.sonar.api.utils.ValidationMessages;
+import org.sonar.core.qualityprofile.db.ActiveRuleDao;
+import org.sonar.core.qualityprofile.db.ActiveRuleDto;
+import org.sonar.core.qualityprofile.db.ActiveRuleParamDto;
+import org.sonar.server.exceptions.BadRequestException;
+import org.sonar.server.rule.RuleRegistry;
+
+import javax.annotation.CheckForNull;
+
+import java.io.StringReader;
+import java.util.List;
+
+import static com.google.common.collect.Lists.newArrayList;
+
+public class QProfileExporter implements ServerComponent {
+
+ private final ActiveRuleDao activeRuleDao;
+ private final List<ProfileImporter> importers;
+ private final RuleRegistry ruleRegistry;
+
+ /**
+ * Used by pico when no plugin provide profile exporter / importer
+ */
+ public QProfileExporter(ActiveRuleDao activeRuleDao, RuleRegistry ruleRegistry) {
+ this(activeRuleDao, Lists.<ProfileImporter>newArrayList(), ruleRegistry);
+ }
+
+ public QProfileExporter(ActiveRuleDao activeRuleDao, List<ProfileImporter> importers, RuleRegistry ruleRegistry) {
+ this.activeRuleDao = activeRuleDao;
+ this.importers = importers;
+ this.ruleRegistry = ruleRegistry;
+ }
+
+ public QProfileResult importXml(QProfile profile, String pluginKey, String xml, SqlSession session) {
+ QProfileResult result = new QProfileResult();
+ ValidationMessages messages = ValidationMessages.create();
+ ProfileImporter importer = getProfileImporter(pluginKey);
+ RulesProfile rulesProfile = importer.importProfile(new StringReader(xml), messages);
+ importProfile(profile.id(), rulesProfile, session);
+ processValidationMessages(messages, result);
+ return result;
+ }
+
+ private void importProfile(int profileId, RulesProfile rulesProfile, SqlSession sqlSession) {
+ List<ActiveRuleDto> activeRuleDtos = newArrayList();
+ Multimap<Integer, ActiveRuleParamDto> paramsByActiveRule = ArrayListMultimap.create();
+ for (ActiveRule activeRule : rulesProfile.getActiveRules()) {
+ ActiveRuleDto activeRuleDto = toActiveRuleDto(activeRule, profileId);
+ activeRuleDao.insert(activeRuleDto, sqlSession);
+ activeRuleDtos.add(activeRuleDto);
+ for (ActiveRuleParam activeRuleParam : activeRule.getActiveRuleParams()) {
+ ActiveRuleParamDto activeRuleParamDto = toActiveRuleParamDto(activeRuleParam, activeRuleDto);
+ activeRuleDao.insert(activeRuleParamDto, sqlSession);
+ paramsByActiveRule.put(activeRuleDto.getId(), activeRuleParamDto);
+ }
+ }
+ ruleRegistry.bulkIndexActiveRules(activeRuleDtos, paramsByActiveRule);
+ }
+
+ @CheckForNull
+ private ProfileImporter getProfileImporter(String exporterKey) {
+ for (ProfileImporter importer : importers) {
+ if (StringUtils.equals(exporterKey, importer.getKey())) {
+ return importer;
+ }
+ }
+ return null;
+ }
+
+ private void processValidationMessages(ValidationMessages messages, QProfileResult result) {
+ if (!messages.getErrors().isEmpty()) {
+ List<BadRequestException.Message> errors = newArrayList();
+ for (String error : messages.getErrors()) {
+ errors.add(BadRequestException.Message.of(error));
+ }
+ throw BadRequestException.of("Fail to import profile", errors);
+ }
+ result.setWarnings(messages.getWarnings());
+ result.setInfos(messages.getInfos());
+ }
+
+ private ActiveRuleDto toActiveRuleDto(ActiveRule activeRule, int profileId) {
+ return new ActiveRuleDto()
+ .setProfileId(profileId)
+ .setRuleId(activeRule.getRule().getId())
+ .setSeverity(toSeverityLevel(activeRule.getSeverity()));
+ }
+
+ private Integer toSeverityLevel(RulePriority rulePriority) {
+ return rulePriority.ordinal();
+ }
+
+ private ActiveRuleParamDto toActiveRuleParamDto(ActiveRuleParam activeRuleParam, ActiveRuleDto activeRuleDto) {
+ return new ActiveRuleParamDto()
+ .setActiveRuleId(activeRuleDto.getId())
+ .setRulesParameterId(activeRuleParam.getRuleParam().getId())
+ .setKey(activeRuleParam.getKey())
+ .setValue(activeRuleParam.getValue());
+ }
+
+}
package org.sonar.server.qualityprofile;
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Multimap;
-import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.sonar.api.ServerComponent;
-import org.sonar.api.profiles.ProfileImporter;
-import org.sonar.api.profiles.RulesProfile;
-import org.sonar.api.rules.ActiveRule;
-import org.sonar.api.rules.ActiveRuleParam;
-import org.sonar.api.rules.RulePriority;
-import org.sonar.api.utils.ValidationMessages;
import org.sonar.core.permission.GlobalPermissions;
import org.sonar.core.persistence.MyBatis;
import org.sonar.core.preview.PreviewCache;
import org.sonar.core.properties.PropertiesDao;
import org.sonar.core.properties.PropertyDto;
-import org.sonar.core.qualityprofile.db.*;
+import org.sonar.core.qualityprofile.db.ActiveRuleDao;
+import org.sonar.core.qualityprofile.db.QualityProfileDao;
+import org.sonar.core.qualityprofile.db.QualityProfileDto;
import org.sonar.server.configuration.ProfilesManager;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.rule.RuleRegistry;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
-import java.io.StringReader;
-import java.util.List;
import java.util.Map;
-import static com.google.common.collect.Lists.newArrayList;
-
public class QProfileOperations implements ServerComponent {
public static final String PROFILE_PROPERTY_PREFIX = "sonar.profile.";
private final QualityProfileDao dao;
private final ActiveRuleDao activeRuleDao;
private final PropertiesDao propertiesDao;
- private final List<ProfileImporter> importers;
+ private final QProfileExporter exporter;
private final PreviewCache dryRunCache;
private final RuleRegistry ruleRegistry;
private final QProfileLookup profileLookup;
private final ProfilesManager profilesManager;
- /**
- * Used by pico when no plugin provide profile exporter / importer
- */
public QProfileOperations(MyBatis myBatis, QualityProfileDao dao, ActiveRuleDao activeRuleDao, PropertiesDao propertiesDao,
- PreviewCache dryRunCache, RuleRegistry ruleRegistry, QProfileLookup profileLookup, ProfilesManager profilesManager) {
- this(myBatis, dao, activeRuleDao, propertiesDao, Lists.<ProfileImporter>newArrayList(), dryRunCache, ruleRegistry, profileLookup, profilesManager);
- }
-
- public QProfileOperations(MyBatis myBatis, QualityProfileDao dao, ActiveRuleDao activeRuleDao, PropertiesDao propertiesDao,
- List<ProfileImporter> importers, PreviewCache dryRunCache, RuleRegistry ruleRegistry, QProfileLookup profileLookup, ProfilesManager profilesManager) {
+ QProfileExporter exporter, PreviewCache dryRunCache, RuleRegistry ruleRegistry, QProfileLookup profileLookup, ProfilesManager profilesManager) {
this.myBatis = myBatis;
this.dao = dao;
this.activeRuleDao = activeRuleDao;
this.propertiesDao = propertiesDao;
- this.importers = importers;
+ this.exporter = exporter;
this.dryRunCache = dryRunCache;
this.ruleRegistry = ruleRegistry;
this.profileLookup = profileLookup;
QProfile profile = newProfile(name, language, userSession, session);
QProfileResult result = new QProfileResult();
- List<RulesProfile> importProfiles = readProfilesFromXml(result, xmlProfilesByPlugin);
- for (RulesProfile rulesProfile : importProfiles) {
- importProfile(profile.id(), rulesProfile, session);
- }
result.setProfile(profile);
+
+ for (Map.Entry<String, String> entry : xmlProfilesByPlugin.entrySet()) {
+ result.add(exporter.importXml(profile, entry.getKey(), entry.getValue(), session));
+ }
session.commit();
dryRunCache.reportGlobalModification();
return result;
checkPermission(userSession);
SqlSession session = myBatis.openSession();
try {
- QualityProfileDto profile = findNotNull(profileId, session);
- if (!profileLookup.isDeletable(QProfile.from(profile), session)) {
- throw new BadRequestException("This profile can not be deleted");
- } else {
- activeRuleDao.deleteParametersFromProfile(profile.getId(), session);
- activeRuleDao.deleteFromProfile(profile.getId(), session);
- dao.delete(profile.getId(), session);
- propertiesDao.deleteProjectProperties(PROFILE_PROPERTY_PREFIX + profile.getLanguage(), profile.getName(), session);
- ruleRegistry.deleteActiveRulesFromProfile(profile.getId());
- session.commit();
-
- dryRunCache.reportGlobalModification();
- }
+ deleteProfile(profileId, userSession, session);
+ session.commit();
} finally {
MyBatis.closeQuietly(session);
}
}
+ public void deleteProfile(int profileId, UserSession userSession, SqlSession session) {
+ checkPermission(userSession);
+ QualityProfileDto profile = findNotNull(profileId, session);
+ if (!profileLookup.isDeletable(QProfile.from(profile), session)) {
+ throw new BadRequestException("This profile can not be deleted");
+ } else {
+ activeRuleDao.deleteParametersFromProfile(profile.getId(), session);
+ activeRuleDao.deleteFromProfile(profile.getId(), session);
+ dao.delete(profile.getId(), session);
+ propertiesDao.deleteProjectProperties(PROFILE_PROPERTY_PREFIX + profile.getLanguage(), profile.getName(), session);
+ ruleRegistry.deleteActiveRulesFromProfile(profile.getId());
+ dryRunCache.reportGlobalModification();
+ }
+ }
+
public void setDefaultProfile(int profileId, UserSession userSession) {
checkPermission(userSession);
SqlSession session = myBatis.openSession();
return null;
}
- private List<RulesProfile> readProfilesFromXml(QProfileResult result, Map<String, String> xmlProfilesByPlugin) {
- List<RulesProfile> profiles = newArrayList();
- ValidationMessages messages = ValidationMessages.create();
- for (Map.Entry<String, String> entry : xmlProfilesByPlugin.entrySet()) {
- String pluginKey = entry.getKey();
- String file = entry.getValue();
- ProfileImporter importer = getProfileImporter(pluginKey);
- RulesProfile profile = importer.importProfile(new StringReader(file), messages);
- processValidationMessages(messages, result);
- profiles.add(profile);
- }
- return profiles;
- }
-
- public void importProfile(int profileId, RulesProfile rulesProfile, SqlSession sqlSession) {
- List<ActiveRuleDto> activeRuleDtos = newArrayList();
- Multimap<Integer, ActiveRuleParamDto> paramsByActiveRule = ArrayListMultimap.create();
- for (ActiveRule activeRule : rulesProfile.getActiveRules()) {
- ActiveRuleDto activeRuleDto = toActiveRuleDto(activeRule, profileId);
- activeRuleDao.insert(activeRuleDto, sqlSession);
- activeRuleDtos.add(activeRuleDto);
- for (ActiveRuleParam activeRuleParam : activeRule.getActiveRuleParams()) {
- ActiveRuleParamDto activeRuleParamDto = toActiveRuleParamDto(activeRuleParam, activeRuleDto);
- activeRuleDao.insert(activeRuleParamDto, sqlSession);
- paramsByActiveRule.put(activeRuleDto.getId(), activeRuleParamDto);
- }
- }
- ruleRegistry.bulkIndexActiveRules(activeRuleDtos, paramsByActiveRule);
- }
-
- @CheckForNull
- private ProfileImporter getProfileImporter(String exporterKey) {
- for (ProfileImporter importer : importers) {
- if (StringUtils.equals(exporterKey, importer.getKey())) {
- return importer;
- }
- }
- return null;
- }
-
- private void processValidationMessages(ValidationMessages messages, QProfileResult result) {
- if (!messages.getErrors().isEmpty()) {
- List<BadRequestException.Message> errors = newArrayList();
- for (String error : messages.getErrors()) {
- errors.add(BadRequestException.Message.of(error));
- }
- throw BadRequestException.of("Fail to create profile", errors);
- }
- result.setWarnings(messages.getWarnings());
- result.setInfos(messages.getInfos());
- }
-
- private ActiveRuleDto toActiveRuleDto(ActiveRule activeRule, int profileId) {
- return new ActiveRuleDto()
- .setProfileId(profileId)
- .setRuleId(activeRule.getRule().getId())
- .setSeverity(toSeverityLevel(activeRule.getSeverity()));
- }
-
- private Integer toSeverityLevel(RulePriority rulePriority) {
- return rulePriority.ordinal();
- }
-
- private ActiveRuleParamDto toActiveRuleParamDto(ActiveRuleParam activeRuleParam, ActiveRuleDto activeRuleDto) {
- return new ActiveRuleParamDto()
- .setActiveRuleId(activeRuleDto.getId())
- .setRulesParameterId(activeRuleParam.getRuleParam().getId())
- .setKey(activeRuleParam.getKey())
- .setValue(activeRuleParam.getValue());
- }
-
private void checkPermission(UserSession userSession) {
userSession.checkLoggedIn();
userSession.checkGlobalPermission(GlobalPermissions.QUALITY_PROFILE_ADMIN);
return this;
}
+ public QProfileResult add(QProfileResult result) {
+ warnings.addAll(result.warnings());
+ infos.addAll(result.infos());
+ return this;
+ }
+
}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2013 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+package org.sonar.server.qualityprofile;
+
+import com.google.common.collect.Multimap;
+import org.apache.ibatis.session.SqlSession;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.mockito.stubbing.Answer;
+import org.sonar.api.profiles.ProfileImporter;
+import org.sonar.api.profiles.RulesProfile;
+import org.sonar.api.rules.ActiveRule;
+import org.sonar.api.rules.Rule;
+import org.sonar.api.rules.RulePriority;
+import org.sonar.api.utils.ValidationMessages;
+import org.sonar.core.qualityprofile.db.ActiveRuleDao;
+import org.sonar.core.qualityprofile.db.ActiveRuleDto;
+import org.sonar.core.qualityprofile.db.ActiveRuleParamDto;
+import org.sonar.server.exceptions.BadRequestException;
+import org.sonar.server.rule.RuleRegistry;
+
+import java.io.Reader;
+import java.util.List;
+
+import static com.google.common.collect.Lists.newArrayList;
+import static org.fest.assertions.Assertions.assertThat;
+import static org.fest.assertions.Fail.fail;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyListOf;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.*;
+
+@RunWith(MockitoJUnitRunner.class)
+public class QProfileExporterTest {
+
+ @Mock
+ SqlSession session;
+
+ @Mock
+ ActiveRuleDao activeRuleDao;
+
+ @Mock
+ RuleRegistry ruleRegistry;
+
+ List<ProfileImporter> importers = newArrayList();
+
+ Integer currentId = 1;
+
+ QProfileExporter operations;
+
+ @Before
+ public void setUp() throws Exception {
+ // Associate an id when inserting an object to simulate the db id generator
+ doAnswer(new Answer() {
+ public Object answer(InvocationOnMock invocation) {
+ Object[] args = invocation.getArguments();
+ ActiveRuleDto dto = (ActiveRuleDto) args[0];
+ dto.setId(currentId++);
+ return null;
+ }
+ }).when(activeRuleDao).insert(any(ActiveRuleDto.class), any(SqlSession.class));
+
+ operations = new QProfileExporter(activeRuleDao, importers, ruleRegistry);
+ }
+
+ @Test
+ public void import_from_xml_plugin() throws Exception {
+ RulesProfile profile = RulesProfile.create("Default", "java");
+ Rule rule = Rule.create("pmd", "rule1");
+ rule.createParameter("max");
+ rule.setId(10);
+ ActiveRule activeRule = profile.activateRule(rule, RulePriority.BLOCKER);
+ activeRule.setParameter("max", "10");
+
+ ProfileImporter importer = mock(ProfileImporter.class);
+ when(importer.getKey()).thenReturn("pmd");
+ when(importer.importProfile(any(Reader.class), any(ValidationMessages.class))).thenReturn(profile);
+ importers.add(importer);
+
+ operations.importXml(new QProfile().setId(1), "pmd", "<xml/>", session);
+
+ ArgumentCaptor<ActiveRuleDto> activeRuleArgument = ArgumentCaptor.forClass(ActiveRuleDto.class);
+ verify(activeRuleDao).insert(activeRuleArgument.capture(), eq(session));
+ assertThat(activeRuleArgument.getValue().getRulId()).isEqualTo(10);
+ assertThat(activeRuleArgument.getValue().getSeverity()).isEqualTo(4);
+
+ ArgumentCaptor<ActiveRuleParamDto> activeRuleParamArgument = ArgumentCaptor.forClass(ActiveRuleParamDto.class);
+ verify(activeRuleDao).insert(activeRuleParamArgument.capture(), eq(session));
+ assertThat(activeRuleParamArgument.getValue().getKey()).isEqualTo("max");
+ assertThat(activeRuleParamArgument.getValue().getValue()).isEqualTo("10");
+
+ verify(ruleRegistry).bulkIndexActiveRules(anyListOf(ActiveRuleDto.class), any(Multimap.class));
+ }
+
+ @Test
+ public void import_from_xml_plugin_add_infos_and_warnings() throws Exception {
+ final RulesProfile profile = RulesProfile.create("Default", "java");
+ Rule rule = Rule.create("pmd", "rule1");
+ rule.createParameter("max");
+ rule.setId(10);
+ ActiveRule activeRule = profile.activateRule(rule, RulePriority.BLOCKER);
+ activeRule.setParameter("max", "10");
+
+ ProfileImporter importer = mock(ProfileImporter.class);
+ when(importer.getKey()).thenReturn("pmd");
+ doAnswer(new Answer() {
+ public Object answer(InvocationOnMock invocation) {
+ Object[] args = invocation.getArguments();
+ ValidationMessages validationMessages = (ValidationMessages) args[1];
+ validationMessages.addInfoText("an info message");
+ validationMessages.addWarningText("a warning message");
+ return profile;
+ }
+ }).when(importer).importProfile(any(Reader.class), any(ValidationMessages.class));
+ importers.add(importer);
+
+ QProfileResult result = operations.importXml(new QProfile().setId(1), "pmd", "<xml/>", session);;
+ assertThat(result.infos()).hasSize(1);
+ assertThat(result.warnings()).hasSize(1);
+ }
+
+ @Test
+ public void fail_to_import_profile_from_xml_plugin_if_error() throws Exception {
+ try {
+ final RulesProfile profile = RulesProfile.create("Default", "java");
+ Rule rule = Rule.create("pmd", "rule1");
+ rule.createParameter("max");
+ rule.setId(10);
+ ActiveRule activeRule = profile.activateRule(rule, RulePriority.BLOCKER);
+ activeRule.setParameter("max", "10");
+
+ ProfileImporter importer = mock(ProfileImporter.class);
+ when(importer.getKey()).thenReturn("pmd");
+ importers.add(importer);
+
+ doAnswer(new Answer() {
+ public Object answer(InvocationOnMock invocation) {
+ Object[] args = invocation.getArguments();
+ ValidationMessages validationMessages = (ValidationMessages) args[1];
+ validationMessages.addErrorText("error!");
+ return profile;
+ }
+ }).when(importer).importProfile(any(Reader.class), any(ValidationMessages.class));
+
+ operations.importXml(new QProfile().setId(1), "pmd", "<xml/>", session);
+ fail();
+ } catch (Exception e) {
+ assertThat(e).isInstanceOf(BadRequestException.class);
+ }
+ }
+
+}
package org.sonar.server.qualityprofile;
import com.google.common.collect.Maps;
-import com.google.common.collect.Multimap;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
-import org.sonar.api.profiles.ProfileImporter;
-import org.sonar.api.profiles.RulesProfile;
-import org.sonar.api.rules.ActiveRule;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.RulePriority;
-import org.sonar.api.utils.ValidationMessages;
import org.sonar.core.permission.GlobalPermissions;
import org.sonar.core.persistence.MyBatis;
import org.sonar.core.preview.PreviewCache;
import org.sonar.core.properties.PropertiesDao;
import org.sonar.core.properties.PropertyDto;
-import org.sonar.core.qualityprofile.db.*;
+import org.sonar.core.qualityprofile.db.ActiveRuleDao;
+import org.sonar.core.qualityprofile.db.ActiveRuleDto;
+import org.sonar.core.qualityprofile.db.QualityProfileDao;
+import org.sonar.core.qualityprofile.db.QualityProfileDto;
import org.sonar.server.configuration.ProfilesManager;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.user.MockUserSession;
import org.sonar.server.user.UserSession;
-import java.io.Reader;
-import java.util.List;
-import java.util.Map;
-
-import static com.google.common.collect.Lists.newArrayList;
-import static com.google.common.collect.Maps.newHashMap;
import static org.fest.assertions.Assertions.assertThat;
import static org.fest.assertions.Fail.fail;
import static org.mockito.Matchers.any;
@Mock
ProfilesManager profilesManager;
- List<ProfileImporter> importers = newArrayList();
+ @Mock
+ QProfileExporter exporter;
Integer currentId = 1;
}
}).when(qualityProfileDao).insert(any(QualityProfileDto.class), any(SqlSession.class));
- operations = new QProfileOperations(myBatis, qualityProfileDao, activeRuleDao, propertiesDao, importers, dryRunCache, ruleRegistry, profileLookup, profilesManager);
+ operations = new QProfileOperations(myBatis, qualityProfileDao, activeRuleDao, propertiesDao, exporter, dryRunCache, ruleRegistry, profileLookup, profilesManager);
}
@Test
}
}
- @Test
- public void create_profile_from_xml_plugin() throws Exception {
- RulesProfile profile = RulesProfile.create("Default", "java");
- Rule rule = Rule.create("pmd", "rule1");
- rule.createParameter("max");
- rule.setId(10);
- ActiveRule activeRule = profile.activateRule(rule, RulePriority.BLOCKER);
- activeRule.setParameter("max", "10");
-
- Map<String, String> xmlProfilesByPlugin = newHashMap();
- xmlProfilesByPlugin.put("pmd", "<xml/>");
- ProfileImporter importer = mock(ProfileImporter.class);
- when(importer.getKey()).thenReturn("pmd");
- when(importer.importProfile(any(Reader.class), any(ValidationMessages.class))).thenReturn(profile);
- importers.add(importer);
-
- operations.newProfile("Default", "java", xmlProfilesByPlugin, authorizedUserSession);
- verify(session).commit();
-
- ArgumentCaptor<QualityProfileDto> profileArgument = ArgumentCaptor.forClass(QualityProfileDto.class);
- verify(qualityProfileDao).insert(profileArgument.capture(), eq(session));
- assertThat(profileArgument.getValue().getName()).isEqualTo("Default");
- assertThat(profileArgument.getValue().getLanguage()).isEqualTo("java");
-
- ArgumentCaptor<ActiveRuleDto> activeRuleArgument = ArgumentCaptor.forClass(ActiveRuleDto.class);
- verify(activeRuleDao).insert(activeRuleArgument.capture(), eq(session));
- assertThat(activeRuleArgument.getValue().getRulId()).isEqualTo(10);
- assertThat(activeRuleArgument.getValue().getSeverity()).isEqualTo(4);
-
- ArgumentCaptor<ActiveRuleParamDto> activeRuleParamArgument = ArgumentCaptor.forClass(ActiveRuleParamDto.class);
- verify(activeRuleDao).insert(activeRuleParamArgument.capture(), eq(session));
- assertThat(activeRuleParamArgument.getValue().getKey()).isEqualTo("max");
- assertThat(activeRuleParamArgument.getValue().getValue()).isEqualTo("10");
-
- verify(ruleRegistry).bulkIndexActiveRules(anyListOf(ActiveRuleDto.class), any(Multimap.class));
- }
-
- @Test
- public void create_profile_from_xml_plugin_add_infos_and_warnings() throws Exception {
- final RulesProfile profile = RulesProfile.create("Default", "java");
- Rule rule = Rule.create("pmd", "rule1");
- rule.createParameter("max");
- rule.setId(10);
- ActiveRule activeRule = profile.activateRule(rule, RulePriority.BLOCKER);
- activeRule.setParameter("max", "10");
-
- Map<String, String> xmlProfilesByPlugin = newHashMap();
- xmlProfilesByPlugin.put("pmd", "<xml/>");
- ProfileImporter importer = mock(ProfileImporter.class);
- when(importer.getKey()).thenReturn("pmd");
- doAnswer(new Answer() {
- public Object answer(InvocationOnMock invocation) {
- Object[] args = invocation.getArguments();
- ValidationMessages validationMessages = (ValidationMessages) args[1];
- validationMessages.addInfoText("an info message");
- validationMessages.addWarningText("a warning message");
- return profile;
- }
- }).when(importer).importProfile(any(Reader.class), any(ValidationMessages.class));
- importers.add(importer);
-
- QProfileResult result = operations.newProfile("Default", "java", xmlProfilesByPlugin, authorizedUserSession);
- assertThat(result.infos()).hasSize(1);
- assertThat(result.warnings()).hasSize(1);
- }
-
- @Test
- public void fail_to_create_profile_from_xml_plugin_if_error() throws Exception {
- try {
- Map<String, String> xmlProfilesByPlugin = newHashMap();
- xmlProfilesByPlugin.put("pmd", "<xml/>");
- ProfileImporter importer = mock(ProfileImporter.class);
- when(importer.getKey()).thenReturn("pmd");
- importers.add(importer);
-
- doAnswer(new Answer() {
- public Object answer(InvocationOnMock invocation) {
- Object[] args = invocation.getArguments();
- ValidationMessages validationMessages = (ValidationMessages) args[1];
- validationMessages.addErrorText("error!");
- return null;
- }
- }).when(importer).importProfile(any(Reader.class), any(ValidationMessages.class));
-
- operations.newProfile("Default", "java", xmlProfilesByPlugin, authorizedUserSession);
- fail();
- } catch (Exception e) {
- assertThat(e).isInstanceOf(BadRequestException.class);
- }
- verify(session, never()).commit();
- }
-
@Test
public void rename_profile() throws Exception {
when(qualityProfileDao.selectById(1, session)).thenReturn(new QualityProfileDto().setId(1).setName("Default").setLanguage("java"));