diff options
author | Julien Lancelot <julien.lancelot@sonarsource.com> | 2014-03-25 14:55:13 +0100 |
---|---|---|
committer | Julien Lancelot <julien.lancelot@sonarsource.com> | 2014-03-25 14:55:13 +0100 |
commit | 767869e7fdcd15e3cf290a247b60b34b1bde6958 (patch) | |
tree | a9db34f6d6d19e2d1a049d7d86ddff067c85d82c /sonar-core | |
parent | 74abc65d43b9f5af2fd67a8c316c36afec4bed8d (diff) | |
download | sonarqube-767869e7fdcd15e3cf290a247b60b34b1bde6958.tar.gz sonarqube-767869e7fdcd15e3cf290a247b60b34b1bde6958.zip |
SONAR-5056 Backup debt model
Diffstat (limited to 'sonar-core')
10 files changed, 0 insertions, 1337 deletions
diff --git a/sonar-core/src/main/java/org/sonar/core/technicaldebt/TechnicalDebtModelRepository.java b/sonar-core/src/main/java/org/sonar/core/technicaldebt/TechnicalDebtModelRepository.java deleted file mode 100644 index 89031c8304e..00000000000 --- a/sonar-core/src/main/java/org/sonar/core/technicaldebt/TechnicalDebtModelRepository.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 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.core.technicaldebt; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.Maps; -import org.picocontainer.Startable; -import org.sonar.api.Plugin; -import org.sonar.api.ServerExtension; -import org.sonar.api.platform.PluginMetadata; -import org.sonar.api.platform.PluginRepository; - -import java.io.InputStreamReader; -import java.io.Reader; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; - -import static com.google.common.collect.Lists.newArrayList; - -/** - * <p>This class is used to find which technical debt model XML files exist in the Sonar instance.</p> - * <p> - * Those XML files are provided by language plugins that embed their own contribution to the definition of the Technical debt model. - * They must be located in the classpath of those language plugins, more specifically in the "com.sonar.sqale" package, and - * they must be named "<pluginKey>-model.xml". - * </p> - */ -// TODO move it to sonar-server and rename it DebtModelPluginRepository when it will be no more used by the SQALE plugin -public class TechnicalDebtModelRepository implements ServerExtension, Startable { - - public static final String DEFAULT_MODEL = "technical-debt"; - - private static final String XML_FILE_SUFFIX = "-model.xml"; - private static final String XML_FILE_PREFIX = "com/sonar/sqale/"; - - private String xmlFilePrefix; - - private PluginRepository pluginRepository; - private Map<String, ClassLoader> contributingPluginKeyToClassLoader; - - public TechnicalDebtModelRepository(PluginRepository pluginRepository) { - this.pluginRepository = pluginRepository; - this.xmlFilePrefix = XML_FILE_PREFIX; - } - - @VisibleForTesting - TechnicalDebtModelRepository(PluginRepository pluginRepository, String xmlFilePrefix) { - this.pluginRepository = pluginRepository; - this.xmlFilePrefix = xmlFilePrefix; - } - - @VisibleForTesting - TechnicalDebtModelRepository(Map<String, ClassLoader> contributingPluginKeyToClassLoader, String xmlFilePrefix) { - this.contributingPluginKeyToClassLoader = contributingPluginKeyToClassLoader; - this.xmlFilePrefix = xmlFilePrefix; - } - - /** - * {@inheritDoc} - */ - @Override - public void start() { - findAvailableXMLFiles(); - } - - protected void findAvailableXMLFiles() { - if (contributingPluginKeyToClassLoader == null) { - contributingPluginKeyToClassLoader = Maps.newTreeMap(); - // Add default model - contributingPluginKeyToClassLoader.put(DEFAULT_MODEL, getClass().getClassLoader()); - for (PluginMetadata metadata : pluginRepository.getMetadata()) { - String pluginKey = metadata.getKey(); - Plugin plugin = pluginRepository.getPlugin(pluginKey); - if (plugin != null) { - ClassLoader classLoader = plugin.getClass().getClassLoader(); - if (classLoader.getResource(getXMLFilePath(pluginKey)) != null) { - contributingPluginKeyToClassLoader.put(pluginKey, classLoader); - } - } - } - } - contributingPluginKeyToClassLoader = Collections.unmodifiableMap(contributingPluginKeyToClassLoader); - } - - @VisibleForTesting - String getXMLFilePath(String model) { - return xmlFilePrefix + model + XML_FILE_SUFFIX; - } - - /** - * Returns the list of plugins that can contribute to the technical debt model. - * - * @return the list of plugin keys - */ - public Collection<String> getContributingPluginList() { - return newArrayList(contributingPluginKeyToClassLoader.keySet()); - } - - /** - * Creates a new {@link java.io.Reader} for the XML file that contains the model contributed by the given plugin. - * - * @param pluginKey the key of the plugin that contributes the XML file - * @return the reader, that must be closed once its use is finished. - */ - public Reader createReaderForXMLFile(String pluginKey) { - ClassLoader classLoader = contributingPluginKeyToClassLoader.get(pluginKey); - String xmlFilePath = getXMLFilePath(pluginKey); - return new InputStreamReader(classLoader.getResourceAsStream(xmlFilePath)); - } - - @VisibleForTesting - Map<String, ClassLoader> getContributingPluginKeyToClassLoader(){ - return contributingPluginKeyToClassLoader; - } - - /** - * {@inheritDoc} - */ - @Override - public void stop() { - // Nothing to do - } - -} diff --git a/sonar-core/src/main/java/org/sonar/core/technicaldebt/TechnicalDebtModelSynchronizer.java b/sonar-core/src/main/java/org/sonar/core/technicaldebt/TechnicalDebtModelSynchronizer.java deleted file mode 100644 index f4a76c5eb13..00000000000 --- a/sonar-core/src/main/java/org/sonar/core/technicaldebt/TechnicalDebtModelSynchronizer.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 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.core.technicaldebt; - -import org.apache.commons.io.IOUtils; -import org.apache.ibatis.session.SqlSession; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.sonar.api.ServerExtension; -import org.sonar.api.technicaldebt.batch.internal.DefaultCharacteristic; -import org.sonar.api.utils.ValidationMessages; -import org.sonar.core.persistence.MyBatis; -import org.sonar.core.technicaldebt.db.CharacteristicDao; -import org.sonar.core.technicaldebt.db.CharacteristicDto; - -import java.io.Reader; -import java.util.List; - -import static com.google.common.collect.Lists.newArrayList; - -/** - * @deprecated since 4.3 - */ -@Deprecated -public class TechnicalDebtModelSynchronizer implements ServerExtension { - - private static final Logger LOG = LoggerFactory.getLogger(TechnicalDebtModelSynchronizer.class); - - private final MyBatis mybatis; - private final CharacteristicDao dao; - private final TechnicalDebtModelRepository languageModelFinder; - private final TechnicalDebtXMLImporter importer; - - public TechnicalDebtModelSynchronizer(MyBatis mybatis, CharacteristicDao dao, TechnicalDebtModelRepository modelRepository, TechnicalDebtXMLImporter importer) { - this.mybatis = mybatis; - this.dao = dao; - this.languageModelFinder = modelRepository; - this.importer = importer; - } - - public List<CharacteristicDto> synchronize(ValidationMessages messages, TechnicalDebtRuleCache rulesCache) { - SqlSession session = mybatis.openSession(); - - List<CharacteristicDto> model = newArrayList(); - try { - model = synchronize(messages, rulesCache, session); - session.commit(); - } finally { - MyBatis.closeQuietly(session); - } - return model; - } - - public List<CharacteristicDto> synchronize(ValidationMessages messages, TechnicalDebtRuleCache rulesCache, SqlSession session) { - DefaultTechnicalDebtModel defaultModel = loadModelFromXml(TechnicalDebtModelRepository.DEFAULT_MODEL, messages, rulesCache); - List<CharacteristicDto> model = loadOrCreateModelFromDb(defaultModel, session); - messages.log(LOG); - - return model; - } - - private List<CharacteristicDto> loadOrCreateModelFromDb(DefaultTechnicalDebtModel defaultModel, SqlSession session) { - List<CharacteristicDto> characteristicDtos = loadModel(); - if (characteristicDtos.isEmpty()) { - return createTechnicalDebtModel(defaultModel, session); - } - return characteristicDtos; - } - - private List<CharacteristicDto> loadModel() { - return dao.selectEnabledCharacteristics(); - } - - private List<CharacteristicDto> createTechnicalDebtModel(DefaultTechnicalDebtModel defaultModel, SqlSession session) { - List<CharacteristicDto> characteristics = newArrayList(); - for (DefaultCharacteristic rootCharacteristic : defaultModel.rootCharacteristics()) { - CharacteristicDto rootCharacteristicDto = CharacteristicDto.toDto(rootCharacteristic, null); - dao.insert(rootCharacteristicDto, session); - characteristics.add(rootCharacteristicDto); - for (DefaultCharacteristic characteristic : rootCharacteristic.children()) { - CharacteristicDto characteristicDto = CharacteristicDto.toDto(characteristic, rootCharacteristicDto.getId()); - dao.insert(characteristicDto, session); - characteristics.add(characteristicDto); - } - } - return characteristics; - } - - public DefaultTechnicalDebtModel loadModelFromXml(String pluginKey, ValidationMessages messages, TechnicalDebtRuleCache rulesCache) { - Reader xmlFileReader = null; - try { - xmlFileReader = languageModelFinder.createReaderForXMLFile(pluginKey); - return importer.importXML(xmlFileReader, messages, rulesCache); - } finally { - IOUtils.closeQuietly(xmlFileReader); - } - } - -} diff --git a/sonar-core/src/main/java/org/sonar/core/technicaldebt/TechnicalDebtRuleCache.java b/sonar-core/src/main/java/org/sonar/core/technicaldebt/TechnicalDebtRuleCache.java deleted file mode 100644 index 6e06fcba40b..00000000000 --- a/sonar-core/src/main/java/org/sonar/core/technicaldebt/TechnicalDebtRuleCache.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 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.core.technicaldebt; - -import com.google.common.collect.Maps; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rules.Rule; -import org.sonar.api.rules.RuleFinder; -import org.sonar.api.rules.RuleQuery; - -import javax.annotation.CheckForNull; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -/** - * @deprecated since 4.3 - */ -@Deprecated -public class TechnicalDebtRuleCache { - - private final RuleFinder ruleFinder; - - private Map<String, Map<String, Rule>> cachedRules; - private Map<Integer, Rule> cachedRulesId; - - public TechnicalDebtRuleCache(RuleFinder ruleFinder) { - this.ruleFinder = ruleFinder; - } - - @CheckForNull - public Rule getByRuleKey(RuleKey ruleKey) { - initRules(); - return lookUpRuleInCache(ruleKey.repository(), ruleKey.rule()); - } - - @CheckForNull - public Rule getByRuleId(Integer ruleId) { - initRules(); - return cachedRulesId.get(ruleId); - } - - public boolean exists(Integer ruleId) { - initRules(); - return getByRuleId(ruleId) != null; - } - - public boolean exists(RuleKey ruleKey) { - return getByRuleKey(ruleKey) != null; - } - - private void initRules(){ - if(cachedRules == null) { - loadRules(); - } - } - - private void loadRules() { - cachedRules = Maps.newHashMap(); - cachedRulesId = Maps.newHashMap(); - Collection<Rule> rules = ruleFinder.findAll(RuleQuery.create()); - for (Rule rule : rules) { - if(!cachedRules.containsKey(rule.getRepositoryKey())) { - cachedRules.put(rule.getRepositoryKey(), new HashMap<String, Rule>()); - } - Map<String, Rule> cachedRepository = cachedRules.get(rule.getRepositoryKey()); - if(!cachedRepository.containsKey(rule.getKey())) { - cachedRepository.put(rule.getKey(), rule); - cachedRulesId.put(rule.getId(), rule); - } - } - } - - @CheckForNull - private Rule lookUpRuleInCache(String repository, String ruleKey) { - Map<String, Rule> cachedRepository = cachedRules.get(repository); - if(cachedRepository != null) { - return cachedRepository.get(ruleKey); - } - return null; - } - -} diff --git a/sonar-core/src/main/java/org/sonar/core/technicaldebt/TechnicalDebtXMLImporter.java b/sonar-core/src/main/java/org/sonar/core/technicaldebt/TechnicalDebtXMLImporter.java deleted file mode 100644 index b0a66036121..00000000000 --- a/sonar-core/src/main/java/org/sonar/core/technicaldebt/TechnicalDebtXMLImporter.java +++ /dev/null @@ -1,326 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 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.core.technicaldebt; - -import com.google.common.base.Predicate; -import com.google.common.base.Strings; -import com.google.common.collect.Iterables; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.math.NumberUtils; -import org.codehaus.stax2.XMLInputFactory2; -import org.codehaus.staxmate.SMInputFactory; -import org.codehaus.staxmate.in.SMHierarchicCursor; -import org.codehaus.staxmate.in.SMInputCursor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.sonar.api.ServerExtension; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rules.Rule; -import org.sonar.api.technicaldebt.batch.internal.DefaultCharacteristic; -import org.sonar.api.technicaldebt.batch.internal.DefaultRequirement; -import org.sonar.api.utils.ValidationMessages; -import org.sonar.api.utils.internal.WorkDuration; - -import javax.annotation.CheckForNull; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; - -import java.io.Reader; -import java.io.StringReader; -import java.util.List; - -import static com.google.common.collect.Lists.newArrayList; - -/** - * @deprecated since 4.3 - */ -@Deprecated -public class TechnicalDebtXMLImporter implements ServerExtension { - - private static final Logger LOG = LoggerFactory.getLogger(TechnicalDebtXMLImporter.class); - - public static final String CHARACTERISTIC = "chc"; - public static final String CHARACTERISTIC_KEY = "key"; - public static final String CHARACTERISTIC_NAME = "name"; - public static final String PROPERTY = "prop"; - - public static final String PROPERTY_KEY = "key"; - public static final String PROPERTY_VALUE = "val"; - public static final String PROPERTY_TEXT_VALUE = "txt"; - - public static final String REPOSITORY_KEY = "rule-repo"; - public static final String RULE_KEY = "rule-key"; - - public static final String PROPERTY_FUNCTION = "remediationFunction"; - public static final String PROPERTY_FACTOR = "remediationFactor"; - public static final String PROPERTY_OFFSET = "offset"; - - public DefaultTechnicalDebtModel importXML(String xml, ValidationMessages messages, TechnicalDebtRuleCache technicalDebtRuleCache) { - return importXML(new StringReader(xml), messages, technicalDebtRuleCache); - } - - public DefaultTechnicalDebtModel importXML(Reader xml, ValidationMessages messages, TechnicalDebtRuleCache repositoryCache) { - DefaultTechnicalDebtModel model = new DefaultTechnicalDebtModel(); - try { - SMInputFactory inputFactory = initStax(); - SMHierarchicCursor cursor = inputFactory.rootElementCursor(xml); - - // advance to <sqale> - cursor.advance(); - SMInputCursor chcCursor = cursor.childElementCursor(CHARACTERISTIC); - - while (chcCursor.getNext() != null) { - processCharacteristic(model, null, chcCursor, messages, repositoryCache); - } - - cursor.getStreamReader().closeCompletely(); - - } catch (XMLStreamException e) { - LOG.error("XML is not valid", e); - messages.addErrorText("XML is not valid: " + e.getMessage()); - } - return model; - } - - private SMInputFactory initStax() { - XMLInputFactory xmlFactory = XMLInputFactory2.newInstance(); - xmlFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); - xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE); - xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE); - xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.FALSE); - return new SMInputFactory(xmlFactory); - } - - private DefaultCharacteristic processCharacteristic(DefaultTechnicalDebtModel model, DefaultCharacteristic parent, SMInputCursor chcCursor, ValidationMessages messages, - TechnicalDebtRuleCache technicalDebtRuleCache) throws XMLStreamException { - DefaultCharacteristic characteristic = new DefaultCharacteristic(); - SMInputCursor cursor = chcCursor.childElementCursor(); - while (cursor.getNext() != null) { - String node = cursor.getLocalName(); - if (StringUtils.equals(node, CHARACTERISTIC_KEY)) { - characteristic.setKey(cursor.collectDescendantText().trim()); - // Attached to parent only if a key is existing, otherwise characteristic with empty key can be added. - characteristic.setParent(parent); - - } else if (StringUtils.equals(node, CHARACTERISTIC_NAME)) { - characteristic.setName(cursor.collectDescendantText().trim(), false); - - // <chc> can contain characteristics or requirements - } else if (StringUtils.equals(node, CHARACTERISTIC)) { - processCharacteristic(model, characteristic, cursor, messages, technicalDebtRuleCache); - - } else if (StringUtils.equals(node, REPOSITORY_KEY)) { - DefaultRequirement requirement = processRequirement(cursor, messages, technicalDebtRuleCache); - if (requirement != null) { - addRequirement(requirement, parent, messages); - } - } - } - - if (StringUtils.isNotBlank(characteristic.key()) && characteristic.isRoot()) { - characteristic.setOrder(model.rootCharacteristics().size() + 1); - model.addRootCharacteristic(characteristic); - return characteristic; - } - return null; - } - - private void addRequirement(DefaultRequirement requirement, DefaultCharacteristic parent, ValidationMessages messages) { - DefaultCharacteristic root = parent.parent(); - if (root == null) { - messages.addWarningText("Requirement '" + requirement.ruleKey() + "' is ignored because it's defined directly under a root characteristic."); - } else { - requirement.setCharacteristic(parent); - requirement.setRootCharacteristic(root); - } - } - - private DefaultRequirement processRequirement(SMInputCursor cursor, ValidationMessages messages, TechnicalDebtRuleCache technicalDebtRuleCache) - throws XMLStreamException { - - DefaultRequirement requirement = new DefaultRequirement(); - String ruleRepositoryKey = cursor.collectDescendantText().trim(); - String ruleKey = null; - Properties properties = new Properties(); - while (cursor.getNext() != null) { - String node = cursor.getLocalName(); - if (StringUtils.equals(node, PROPERTY)) { - properties.add(processProperty(cursor, messages)); - } else if (StringUtils.equals(node, RULE_KEY)) { - ruleKey = cursor.collectDescendantText().trim(); - } - } - fillRule(requirement, ruleRepositoryKey, ruleKey, messages, technicalDebtRuleCache); - if (requirement.ruleKey() == null) { - return null; - } - return processFunctionsOnRequirement(requirement, properties, messages); - } - - private void fillRule(DefaultRequirement requirement, String ruleRepositoryKey, String ruleKey, ValidationMessages messages, - TechnicalDebtRuleCache technicalDebtRuleCache) { - if (StringUtils.isNotBlank(ruleRepositoryKey) && StringUtils.isNotBlank(ruleKey)) { - Rule rule = technicalDebtRuleCache.getByRuleKey(RuleKey.of(ruleRepositoryKey, ruleKey)); - if (rule != null) { - requirement.setRuleKey(RuleKey.of(ruleRepositoryKey, ruleKey)); - } else { - messages.addWarningText("Rule not found: [repository=" + ruleRepositoryKey + ", key=" + ruleKey + "]"); - } - } - } - - private Property processProperty(SMInputCursor cursor, ValidationMessages messages) throws XMLStreamException { - SMInputCursor c = cursor.childElementCursor(); - String key = null; - int value = 0; - String textValue = null; - while (c.getNext() != null) { - String node = c.getLocalName(); - if (StringUtils.equals(node, PROPERTY_KEY)) { - key = c.collectDescendantText().trim(); - - } else if (StringUtils.equals(node, PROPERTY_VALUE)) { - String s = c.collectDescendantText().trim(); - try { - // The value is still a double for the moment - Double valueDouble = NumberUtils.createDouble(s); - value = valueDouble.intValue(); - } catch (NumberFormatException ex) { - messages.addErrorText(String.format("Cannot import value '%s' for field %s - Expected a numeric value instead", s, key)); - } - } else if (StringUtils.equals(node, PROPERTY_TEXT_VALUE)) { - textValue = c.collectDescendantText().trim(); - } - } - return new Property(key, value, textValue); - } - - @CheckForNull - private DefaultRequirement processFunctionsOnRequirement(DefaultRequirement requirement, Properties properties, ValidationMessages messages) { - Property function = properties.function(); - Property factor = properties.factor(); - Property offset = properties.offset(); - - if (function != null) { - // Requirements should always have values, so we init it with default values - requirement.setFactorValue(0); - requirement.setFactorUnit(WorkDuration.UNIT.DAYS); - requirement.setOffsetValue(0); - requirement.setOffsetUnit(WorkDuration.UNIT.DAYS); - - String functionKey = function.getTextValue(); - if ("linear_threshold".equals(functionKey)) { - function.setTextValue(DefaultRequirement.FUNCTION_LINEAR); - offset.setValue(0); - offset.setTextValue("d"); - messages.addWarningText(String.format("Linear with threshold function is no longer used, function of the requirement '%s' is replaced by linear.", requirement.ruleKey())); - } else if ("constant_resource".equals(functionKey)) { - messages.addWarningText(String.format("Constant/file function is no longer used, requirements '%s' are ignored.", requirement.ruleKey())); - return null; - } - - requirement.setFunction(function.getTextValue()); - if (factor != null) { - requirement.setFactorValue(factor.getValue()); - if (!Strings.isNullOrEmpty(factor.getTextValue())) { - requirement.setFactorUnit(DefaultRequirement.toUnit(factor.getTextValue())); - } - } - if (offset != null) { - requirement.setOffsetValue(offset.getValue()); - if (!Strings.isNullOrEmpty(offset.getTextValue())) { - requirement.setOffsetUnit(DefaultRequirement.toUnit(offset.getTextValue())); - } - } - return requirement; - } - return null; - } - - private static class Properties { - List<Property> properties; - - public Properties() { - this.properties = newArrayList(); - } - - public Properties add(Property property) { - this.properties.add(property); - return this; - } - - public Property function() { - return find(PROPERTY_FUNCTION); - } - - public Property factor() { - return find(PROPERTY_FACTOR); - } - - public Property offset() { - return find(PROPERTY_OFFSET); - } - - private Property find(final String key) { - return Iterables.find(properties, new Predicate<Property>() { - @Override - public boolean apply(Property input) { - return input.getKey().equals(key); - } - }, null); - } - - } - - private static class Property { - String key; - int value; - String textValue; - - private Property(String key, int value, String textValue) { - this.key = key; - this.value = value; - this.textValue = textValue; - } - - private Property setValue(int value) { - this.value = value; - return this; - } - - private Property setTextValue(String textValue) { - this.textValue = textValue; - return this; - } - - private String getKey() { - return key; - } - - private int getValue() { - return value; - } - - private String getTextValue() { - return textValue; - } - } -} diff --git a/sonar-core/src/test/java/org/sonar/core/technicaldebt/TechnicalDebtModelRepositoryTest.java b/sonar-core/src/test/java/org/sonar/core/technicaldebt/TechnicalDebtModelRepositoryTest.java deleted file mode 100644 index f74e95f2e7a..00000000000 --- a/sonar-core/src/test/java/org/sonar/core/technicaldebt/TechnicalDebtModelRepositoryTest.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 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.core.technicaldebt; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.io.Resources; -import org.apache.commons.io.IOUtils; -import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.sonar.api.SonarPlugin; -import org.sonar.api.platform.PluginMetadata; -import org.sonar.api.platform.PluginRepository; - -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.Reader; -import java.net.MalformedURLException; -import java.util.Collection; -import java.util.List; -import java.util.Map; - -import static org.fest.assertions.Assertions.assertThat; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class TechnicalDebtModelRepositoryTest { - - private static final String TEST_XML_PREFIX_PATH = "org/sonar/core/technicaldebt/TechnicalDebtModelRepositoryTest/"; - - private TechnicalDebtModelRepository modelFinder; - - @Test - public void test_component_initialization() throws Exception { - // we do have the "csharp-model.xml" file in src/test/resources - PluginMetadata csharpPluginMetadata = mock(PluginMetadata.class); - when(csharpPluginMetadata.getKey()).thenReturn("csharp"); - - // but we don' have the "php-model.xml" one - PluginMetadata phpPluginMetadata = mock(PluginMetadata.class); - when(phpPluginMetadata.getKey()).thenReturn("php"); - - PluginRepository repository = mock(PluginRepository.class); - when(repository.getMetadata()).thenReturn(Lists.newArrayList(csharpPluginMetadata, phpPluginMetadata)); - FakePlugin fakePlugin = new FakePlugin(); - when(repository.getPlugin(anyString())).thenReturn(fakePlugin); - modelFinder = new TechnicalDebtModelRepository(repository, TEST_XML_PREFIX_PATH); - - // when - modelFinder.start(); - - // assert - Collection<String> contributingPluginList = modelFinder.getContributingPluginList(); - assertThat(contributingPluginList.size()).isEqualTo(2); - assertThat(contributingPluginList).containsOnly("technical-debt", "csharp"); - } - - @Test - public void contributing_plugin_list() throws Exception { - initModel(); - Collection<String> contributingPluginList = modelFinder.getContributingPluginList(); - assertThat(contributingPluginList.size()).isEqualTo(2); - assertThat(contributingPluginList).contains("csharp", "java"); - } - - @Test - public void get_content_for_xml_file() throws Exception { - initModel(); - Reader xmlFileReader = null; - try { - xmlFileReader = modelFinder.createReaderForXMLFile("csharp"); - assertNotNull(xmlFileReader); - List<String> lines = IOUtils.readLines(xmlFileReader); - assertThat(lines.size()).isEqualTo(25); - assertThat(lines.get(0)).isEqualTo("<sqale>"); - } catch (Exception e) { - fail("Should be able to read the XML file."); - } finally { - IOUtils.closeQuietly(xmlFileReader); - } - } - - @Test - public void return_xml_file_path_for_plugin() throws Exception { - initModel(); - assertThat(modelFinder.getXMLFilePath("foo")).isEqualTo(TEST_XML_PREFIX_PATH + "foo-model.xml"); - } - - @Test - public void contain_default_model() throws Exception { - modelFinder = new TechnicalDebtModelRepository(mock(PluginRepository.class)); - modelFinder.start(); - assertThat(modelFinder.getContributingPluginKeyToClassLoader().keySet()).containsOnly("technical-debt"); - } - - private void initModel() throws MalformedURLException { - Map<String, ClassLoader> contributingPluginKeyToClassLoader = Maps.newHashMap(); - contributingPluginKeyToClassLoader.put("csharp", newClassLoader()); - contributingPluginKeyToClassLoader.put("java", newClassLoader()); - modelFinder = new TechnicalDebtModelRepository(contributingPluginKeyToClassLoader, TEST_XML_PREFIX_PATH); - } - - private ClassLoader newClassLoader() throws MalformedURLException { - ClassLoader loader = mock(ClassLoader.class); - when(loader.getResourceAsStream(anyString())).thenAnswer(new Answer<InputStream>() { - public InputStream answer(InvocationOnMock invocation) throws Throwable { - return new FileInputStream(Resources.getResource((String) invocation.getArguments()[0]).getPath()); - } - }); - return loader; - } - - class FakePlugin extends SonarPlugin { - public List getExtensions() { - return null; - } - } - -} diff --git a/sonar-core/src/test/java/org/sonar/core/technicaldebt/TechnicalDebtModelSynchronizerTest.java b/sonar-core/src/test/java/org/sonar/core/technicaldebt/TechnicalDebtModelSynchronizerTest.java deleted file mode 100644 index e2c12374ea5..00000000000 --- a/sonar-core/src/test/java/org/sonar/core/technicaldebt/TechnicalDebtModelSynchronizerTest.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 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.core.technicaldebt; - -import com.google.common.collect.Lists; -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.technicaldebt.batch.internal.DefaultCharacteristic; -import org.sonar.api.utils.ValidationMessages; -import org.sonar.core.persistence.MyBatis; -import org.sonar.core.technicaldebt.db.CharacteristicDao; -import org.sonar.core.technicaldebt.db.CharacteristicDto; - -import java.io.Reader; -import java.util.Collections; -import java.util.List; - -import static org.fest.assertions.Assertions.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.*; - -@RunWith(MockitoJUnitRunner.class) -public class TechnicalDebtModelSynchronizerTest { - - @Mock - MyBatis myBatis; - - @Mock - SqlSession session; - - @Mock - TechnicalDebtModelRepository technicalDebtModelRepository; - - @Mock - TechnicalDebtRuleCache ruleCache; - - @Mock - CharacteristicDao dao; - - @Mock - TechnicalDebtXMLImporter xmlImporter; - - Integer currentId = 1; - - private DefaultTechnicalDebtModel defaultModel; - - private TechnicalDebtModelSynchronizer manager; - - @Before - public void initAndMerge() throws Exception { - when(myBatis.openSession()).thenReturn(session); - - defaultModel = new DefaultTechnicalDebtModel(); - Reader defaultModelReader = mock(Reader.class); - when(technicalDebtModelRepository.createReaderForXMLFile("technical-debt")).thenReturn(defaultModelReader); - when(xmlImporter.importXML(eq(defaultModelReader), any(ValidationMessages.class), eq(ruleCache))).thenReturn(defaultModel); - - doAnswer(new Answer() { - public Object answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - CharacteristicDto dto = (CharacteristicDto) args[0]; - dto.setId(currentId++); - return null; - } - }).when(dao).insert(any(CharacteristicDto.class), any(SqlSession.class)); - - - manager = new TechnicalDebtModelSynchronizer(myBatis, dao, technicalDebtModelRepository, xmlImporter); - } - - @Test - public void create_default_model_on_first_execution_when_no_plugin() throws Exception { - DefaultCharacteristic rootCharacteristic = new DefaultCharacteristic().setKey("PORTABILITY"); - new DefaultCharacteristic().setKey("COMPILER_RELATED_PORTABILITY").setParent(rootCharacteristic); - defaultModel.addRootCharacteristic(rootCharacteristic); - - when(technicalDebtModelRepository.getContributingPluginList()).thenReturn(Collections.<String>emptyList()); - when(dao.selectEnabledCharacteristics()).thenReturn(Lists.<CharacteristicDto>newArrayList()); - - manager.synchronize(ValidationMessages.create(), ruleCache); - - verify(dao).selectEnabledCharacteristics(); - ArgumentCaptor<CharacteristicDto> characteristicCaptor = ArgumentCaptor.forClass(CharacteristicDto.class); - verify(dao, times(2)).insert(characteristicCaptor.capture(), eq(session)); - - List<CharacteristicDto> result = characteristicCaptor.getAllValues(); - assertThat(result.get(0).getKey()).isEqualTo("PORTABILITY"); - assertThat(result.get(1).getKey()).isEqualTo("COMPILER_RELATED_PORTABILITY"); - verifyNoMoreInteractions(dao); - } - -} diff --git a/sonar-core/src/test/java/org/sonar/core/technicaldebt/TechnicalDebtRuleCacheTest.java b/sonar-core/src/test/java/org/sonar/core/technicaldebt/TechnicalDebtRuleCacheTest.java deleted file mode 100644 index 8e0afd525c3..00000000000 --- a/sonar-core/src/test/java/org/sonar/core/technicaldebt/TechnicalDebtRuleCacheTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 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.core.technicaldebt; - -import com.google.common.collect.Lists; -import org.fest.assertions.Assertions; -import org.junit.Test; -import org.mockito.Matchers; -import org.mockito.Mockito; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rules.Rule; -import org.sonar.api.rules.RuleFinder; -import org.sonar.api.rules.RuleQuery; - -import java.util.Collections; - -public class TechnicalDebtRuleCacheTest { - - @Test - public void lazy_load_rules_on_first_call() throws Exception { - - RuleFinder ruleFinder = Mockito.mock(RuleFinder.class); - Mockito.when(ruleFinder.findAll(Matchers.any(RuleQuery.class))).thenReturn(Collections.EMPTY_LIST); - - TechnicalDebtRuleCache technicalDebtRuleCache = new TechnicalDebtRuleCache(ruleFinder); - technicalDebtRuleCache.getByRuleKey(RuleKey.of("repo1", "rule1")); - technicalDebtRuleCache.getByRuleKey(RuleKey.of("repo1", "rule1")); - - Mockito.verify(ruleFinder, Mockito.times(1)).findAll(Matchers.any(RuleQuery.class)); - } - - @Test - public void return_matching_rule() throws Exception { - - Rule rule1 = Rule.create("repo1", "rule1"); - Rule rule2 = Rule.create("repo2", "rule2"); - - RuleFinder ruleFinder = Mockito.mock(RuleFinder.class); - Mockito.when(ruleFinder.findAll(Matchers.any(RuleQuery.class))).thenReturn(Lists.newArrayList(rule1, rule2)); - - TechnicalDebtRuleCache technicalDebtRuleCache = new TechnicalDebtRuleCache(ruleFinder); - Rule actualRule1 = technicalDebtRuleCache.getByRuleKey(RuleKey.of("repo1", "rule1")); - Rule actualRule2 = technicalDebtRuleCache.getByRuleKey(RuleKey.of("repo2", "rule2")); - - Assertions.assertThat(actualRule1).isEqualTo(rule1); - Assertions.assertThat(actualRule2).isEqualTo(rule2); - } - - @Test - public void return_if_rule_exists() throws Exception { - - Rule rule1 = Rule.create("repo1", "rule1"); - - RuleFinder ruleFinder = Mockito.mock(RuleFinder.class); - Mockito.when(ruleFinder.findAll(Matchers.any(RuleQuery.class))).thenReturn(Lists.newArrayList(rule1)); - - TechnicalDebtRuleCache technicalDebtRuleCache = new TechnicalDebtRuleCache(ruleFinder); - - Assertions.assertThat(technicalDebtRuleCache.exists(RuleKey.of("repo1", "rule1"))).isTrue(); - Assertions.assertThat(technicalDebtRuleCache.exists(RuleKey.of("repo2", "rule2"))).isFalse(); - } - - @Test - public void return_if_rule_id_exists() throws Exception { - - Rule rule1 = Rule.create("repo1", "rule1"); - rule1.setId(1); - - RuleFinder ruleFinder = Mockito.mock(RuleFinder.class); - Mockito.when(ruleFinder.findAll(Matchers.any(RuleQuery.class))).thenReturn(Lists.newArrayList(rule1)); - - TechnicalDebtRuleCache technicalDebtRuleCache = new TechnicalDebtRuleCache(ruleFinder); - - Assertions.assertThat(technicalDebtRuleCache.exists(1)).isTrue(); - Assertions.assertThat(technicalDebtRuleCache.exists(2)).isFalse(); - } -} diff --git a/sonar-core/src/test/java/org/sonar/core/technicaldebt/TechnicalDebtXMLImporterTest.java b/sonar-core/src/test/java/org/sonar/core/technicaldebt/TechnicalDebtXMLImporterTest.java deleted file mode 100644 index 4ff4e1f17ee..00000000000 --- a/sonar-core/src/test/java/org/sonar/core/technicaldebt/TechnicalDebtXMLImporterTest.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 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.core.technicaldebt; - -import com.google.common.base.Charsets; -import com.google.common.collect.Lists; -import com.google.common.io.Resources; -import org.junit.Test; -import org.mockito.Matchers; -import org.mockito.Mockito; -import org.sonar.api.rules.Rule; -import org.sonar.api.rules.RuleFinder; -import org.sonar.api.rules.RuleQuery; -import org.sonar.api.technicaldebt.batch.internal.DefaultCharacteristic; -import org.sonar.api.technicaldebt.batch.internal.DefaultRequirement; -import org.sonar.api.utils.ValidationMessages; -import org.sonar.api.utils.internal.WorkDuration; - -import java.io.IOException; - -import static org.fest.assertions.Assertions.assertThat; - -public class TechnicalDebtXMLImporterTest { - - @Test - public void import_characteristics() { - TechnicalDebtRuleCache technicalDebtRuleCache = mockRuleCache(); - - String xml = getFileContent("import_characteristics.xml"); - - ValidationMessages messages = ValidationMessages.create(); - DefaultTechnicalDebtModel sqale = new TechnicalDebtXMLImporter().importXML(xml, messages, technicalDebtRuleCache); - - assertThat(sqale.rootCharacteristics()).hasSize(2); - assertThat(sqale.rootCharacteristics().get(0).key()).isEqualTo("PORTABILITY"); - assertThat(sqale.rootCharacteristics().get(1).key()).isEqualTo("MAINTAINABILITY"); - - DefaultCharacteristic portability = sqale.characteristicByKey("PORTABILITY"); - assertThat(portability.order()).isEqualTo(1); - assertThat(portability.children()).hasSize(2); - assertThat(portability.children().get(0).key()).isEqualTo("COMPILER_RELATED_PORTABILITY"); - assertThat(sqale.characteristicByKey("COMPILER_RELATED_PORTABILITY").parent().key()).isEqualTo("PORTABILITY"); - assertThat(portability.children().get(1).key()).isEqualTo("HARDWARE_RELATED_PORTABILITY"); - assertThat(sqale.characteristicByKey("HARDWARE_RELATED_PORTABILITY").parent().key()).isEqualTo("PORTABILITY"); - - DefaultCharacteristic maintainability = sqale.characteristicByKey("MAINTAINABILITY"); - assertThat(maintainability.order()).isEqualTo(2); - assertThat(maintainability.children()).hasSize(1); - assertThat(maintainability.children().get(0).key()).isEqualTo("READABILITY"); - assertThat(sqale.characteristicByKey("READABILITY").parent().key()).isEqualTo("MAINTAINABILITY"); - } - - @Test - public void use_default_unit_when_no_unit() { - TechnicalDebtRuleCache technicalDebtRuleCache = mockRuleCache(); - - String xml = getFileContent("use_default_unit_when_no_unit.xml"); - - ValidationMessages messages = ValidationMessages.create(); - DefaultTechnicalDebtModel sqale = new TechnicalDebtXMLImporter().importXML(xml, messages, technicalDebtRuleCache); - - DefaultCharacteristic memoryEfficiency = sqale.characteristicByKey("MEMORY_EFFICIENCY"); - DefaultRequirement requirement = memoryEfficiency.requirements().get(0); - assertThat(requirement.factorValue()).isEqualTo(3); - assertThat(requirement.factorUnit()).isEqualTo(WorkDuration.UNIT.DAYS); - assertThat(requirement.offsetValue()).isEqualTo(1); - assertThat(requirement.offsetUnit()).isEqualTo(WorkDuration.UNIT.DAYS); - } - - @Test - public void import_xml_with_linear_function() { - TechnicalDebtRuleCache technicalDebtRuleCache = mockRuleCache(); - - String xml = getFileContent("shouldImportXML_with_linear.xml"); - - ValidationMessages messages = ValidationMessages.create(); - DefaultTechnicalDebtModel sqale = new TechnicalDebtXMLImporter().importXML(xml, messages, technicalDebtRuleCache); - - checkXmlCorrectlyImported(sqale, messages); - } - - @Test - public void import_xml_with_linear_with_offset() { - TechnicalDebtRuleCache technicalDebtRuleCache = mockRuleCache(); - - String xml = getFileContent("shouldImportXML_with_linear_with_offset.xml"); - - ValidationMessages messages = ValidationMessages.create(); - DefaultTechnicalDebtModel sqale = new TechnicalDebtXMLImporter().importXML(xml, messages, technicalDebtRuleCache); - - checkXmlCorrectlyImported(sqale, 1, WorkDuration.UNIT.HOURS, messages); - } - - @Test - public void convert_deprecated_linear_with_threshold_function_by_linear_function() { - TechnicalDebtRuleCache technicalDebtRuleCache = mockRuleCache(); - - String xml = getFileContent("shouldImportXML_with_deprecated_linear_with_threshold.xml"); - - ValidationMessages messages = ValidationMessages.create(); - DefaultTechnicalDebtModel sqale = new TechnicalDebtXMLImporter().importXML(xml, messages, technicalDebtRuleCache); - - checkXmlCorrectlyImported(sqale, 0, WorkDuration.UNIT.DAYS, messages); - assertThat(messages.getWarnings()).hasSize(1); - } - - @Test - public void ignore_deprecated_constant_per_file_function() { - TechnicalDebtRuleCache technicalDebtRuleCache = mockRuleCache(); - - String xml = getFileContent("shouldImportXML_with_deprecated_constant_per_file.xml"); - - ValidationMessages messages = ValidationMessages.create(); - DefaultTechnicalDebtModel sqale = new TechnicalDebtXMLImporter().importXML(xml, messages, technicalDebtRuleCache); - - assertThat(messages.getWarnings()).hasSize(1); - - // characteristics - assertThat(sqale.rootCharacteristics()).hasSize(1); - DefaultCharacteristic efficiency = sqale.characteristicByKey("EFFICIENCY"); - assertThat(efficiency.requirements()).isEmpty(); - } - - @Test - public void ignore_requirement_on_root_characteristics() { - TechnicalDebtRuleCache technicalDebtRuleCache = mockRuleCache(); - - String xml = getFileContent("ignore_requirement_on_root_characteristics.xml"); - - ValidationMessages messages = ValidationMessages.create(); - DefaultTechnicalDebtModel sqale = new TechnicalDebtXMLImporter().importXML(xml, messages, technicalDebtRuleCache); - - assertThat(messages.getWarnings()).hasSize(1); - - assertThat(sqale.characteristics()).hasSize(1); - DefaultCharacteristic efficiency = sqale.characteristicByKey("EFFICIENCY"); - assertThat(efficiency.requirements()).isEmpty(); - assertThat(messages.getWarnings().get(0)).contains("checkstyle"); - } - - @Test - public void shouldBadlyFormattedImportXML() { - TechnicalDebtRuleCache technicalDebtRuleCache = mockRuleCache(); - String xml = getFileContent("shouldImportXML_badly-formatted.xml"); - - ValidationMessages messages = ValidationMessages.create(); - DefaultTechnicalDebtModel sqale = new TechnicalDebtXMLImporter().importXML(xml, messages, technicalDebtRuleCache); - - checkXmlCorrectlyImported(sqale, messages); - } - - @Test - public void ignore_requirement_with_not_found_rule() { - TechnicalDebtRuleCache technicalDebtRuleCache = mockRuleCache(); - String xml = getFileContent("shouldLogWarningIfRuleNotFound.xml"); - ValidationMessages messages = ValidationMessages.create(); - - DefaultTechnicalDebtModel sqale = new TechnicalDebtXMLImporter().importXML(xml, messages, technicalDebtRuleCache); - - assertThat(messages.getWarnings()).hasSize(1); - assertThat(messages.getWarnings().get(0)).isEqualTo("Rule not found: [repository=findbugs, key=Foo]"); - - // characteristics - assertThat(sqale.rootCharacteristics()).hasSize(1); - DefaultCharacteristic efficiency = sqale.characteristicByKey("EFFICIENCY"); - assertThat(efficiency.requirements()).isEmpty(); - assertThat(messages.getWarnings().get(0)).contains("findbugs"); - } - - @Test - public void shouldNotifyOnUnexpectedValueTypeInXml() throws Exception { - - TechnicalDebtRuleCache technicalDebtRuleCache = mockRuleCache(); - - String xml = getFileContent("shouldRejectXML_with_invalid_value.xml"); - ValidationMessages messages = ValidationMessages.create(); - - new TechnicalDebtXMLImporter().importXML(xml, messages, technicalDebtRuleCache); - - assertThat(messages.getErrors()).hasSize(1); - assertThat(messages.getErrors().get(0)).isEqualTo("Cannot import value 'abc' for field factor - Expected a numeric value instead"); - } - - private TechnicalDebtRuleCache mockRuleCache() { - RuleFinder finder = Mockito.mock(RuleFinder.class); - Mockito.when(finder.findAll(Matchers.any(RuleQuery.class))).thenReturn(Lists.newArrayList(Rule.create("checkstyle", "Regexp", "Regular expression"))); - return new TechnicalDebtRuleCache(finder); - } - - private void checkXmlCorrectlyImported(DefaultTechnicalDebtModel sqale, ValidationMessages messages) { - checkXmlCorrectlyImported(sqale, 0, WorkDuration.UNIT.DAYS, messages); - } - - private void checkXmlCorrectlyImported(DefaultTechnicalDebtModel sqale, Integer offsetValue, WorkDuration.UNIT offsetUnit, ValidationMessages messages) { - assertThat(messages.getErrors()).isEmpty(); - - // characteristics - assertThat(sqale.rootCharacteristics()).hasSize(2); - DefaultCharacteristic efficiency = sqale.characteristicByKey("EFFICIENCY"); - assertThat(efficiency.name()).isEqualTo("Efficiency"); - - // sub-characteristics - assertThat(efficiency.children()).hasSize(1); - DefaultCharacteristic memoryEfficiency = sqale.characteristicByKey("MEMORY_EFFICIENCY"); - assertThat(memoryEfficiency.name()).isEqualTo("Memory use"); - - // requirement - assertThat(memoryEfficiency.requirements()).hasSize(1); - DefaultRequirement requirement = memoryEfficiency.requirements().get(0); - assertThat(requirement.ruleKey().repository()).isEqualTo("checkstyle"); - assertThat(requirement.ruleKey().rule()).isEqualTo("Regexp"); - assertThat(requirement.function()).isEqualTo("linear"); - assertThat(requirement.factorValue()).isEqualTo(3); - assertThat(requirement.factorUnit()).isEqualTo(WorkDuration.UNIT.HOURS); - assertThat(requirement.offsetValue()).isEqualTo(offsetValue); - assertThat(requirement.offsetUnit()).isEqualTo(offsetUnit); - assertThat(requirement.characteristic().key()).isEqualTo("MEMORY_EFFICIENCY"); - assertThat(requirement.rootCharacteristic().key()).isEqualTo("EFFICIENCY"); - } - - private String getFileContent(String file) { - try { - return Resources.toString(Resources.getResource(TechnicalDebtXMLImporterTest.class, "TechnicalDebtXMLImporterTest/" + file), Charsets.UTF_8); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - -} diff --git a/sonar-core/src/test/resources/org/sonar/core/technicaldebt/TechnicalDebtModelRepositoryTest/csharp-model.xml b/sonar-core/src/test/resources/org/sonar/core/technicaldebt/TechnicalDebtModelRepositoryTest/csharp-model.xml deleted file mode 100644 index e4569a2a7bf..00000000000 --- a/sonar-core/src/test/resources/org/sonar/core/technicaldebt/TechnicalDebtModelRepositoryTest/csharp-model.xml +++ /dev/null @@ -1,25 +0,0 @@ -<sqale> - <chc> - <key>USABILITY</key> - <name>Usability</name> - <desc>Estimate usability</desc> - </chc> - <chc> - <key>EFFICIENCY</key> - <name>Efficiency</name> - <chc> - <rule-repo>gendarme</rule-repo> - <rule-key>EnsureLocalDisposalRule</rule-key> - <prop> - <key>remediationFactor</key> - <val>0.125</val> - <txt>d</txt> - </prop> - <prop> - <key>remediationFunction</key> - <txt>linear</txt> - </prop> - </chc> - </chc> - -</sqale>
\ No newline at end of file diff --git a/sonar-core/src/test/resources/org/sonar/core/technicaldebt/TechnicalDebtModelRepositoryTest/java-model.xml b/sonar-core/src/test/resources/org/sonar/core/technicaldebt/TechnicalDebtModelRepositoryTest/java-model.xml deleted file mode 100644 index 0b37f562107..00000000000 --- a/sonar-core/src/test/resources/org/sonar/core/technicaldebt/TechnicalDebtModelRepositoryTest/java-model.xml +++ /dev/null @@ -1,25 +0,0 @@ -<sqale> - <chc> - <key>USABILITY</key> - <name>Usability</name> - <desc>Estimate usability</desc> - </chc> - <chc> - <key>EFFICIENCY</key> - <name>Efficiency</name> - <chc> - <rule-repo>squid-cobol</rule-repo> - <rule-key>CheckLoop</rule-key> - <prop> - <key>remediationFactor</key> - <val>0.125</val> - <txt>d</txt> - </prop> - <prop> - <key>remediationFunction</key> - <txt>linear</txt> - </prop> - </chc> - </chc> - -</sqale>
\ No newline at end of file |