repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/rule/RuleDefinitionsLoader.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.rule; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.api.impl.server.RulesDefinitionContext; import org.sonar.server.plugins.ServerPluginRepository; import org.springframework.beans.factory.annotation.Autowired; /** * Loads all instances of {@link RulesDefinition}. Used during server startup * and restore of debt model backup. */ public class RuleDefinitionsLoader { private final RulesDefinition[] pluginDefs; private final ServerPluginRepository serverPluginRepository; @Autowired(required = false) public RuleDefinitionsLoader(ServerPluginRepository serverPluginRepository, RulesDefinition[] pluginDefs) { this.serverPluginRepository = serverPluginRepository; this.pluginDefs = pluginDefs; } /** * Used when no definitions at all. */ @Autowired(required = false) public RuleDefinitionsLoader(ServerPluginRepository serverPluginRepository) { this(serverPluginRepository, new RulesDefinition[0]); } public RulesDefinition.Context load() { RulesDefinition.Context context = new RulesDefinitionContext(); for (RulesDefinition pluginDefinition : pluginDefs) { context.setCurrentPluginKey(serverPluginRepository.getPluginKey(pluginDefinition)); pluginDefinition.define(context); } context.setCurrentPluginKey(null); return context; } }
2,204
35.75
109
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/rule/RuleDescriptionSectionsGenerator.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.rule; import java.util.Set; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.db.rule.RuleDescriptionSectionDto; public interface RuleDescriptionSectionsGenerator { boolean isGeneratorForRule(RulesDefinition.Rule rule); Set<RuleDescriptionSectionDto> generateSections(RulesDefinition.Rule rule); }
1,192
35.151515
77
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/rule/RuleDescriptionSectionsGeneratorResolver.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.rule; import java.util.Set; import org.sonar.api.server.rule.RulesDefinition; import static java.util.stream.Collectors.toSet; import static org.sonar.api.utils.Preconditions.checkState; public class RuleDescriptionSectionsGeneratorResolver { private final Set<RuleDescriptionSectionsGenerator> ruleDescriptionSectionsGenerators; RuleDescriptionSectionsGeneratorResolver(Set<RuleDescriptionSectionsGenerator> ruleDescriptionSectionsGenerators) { this.ruleDescriptionSectionsGenerators = ruleDescriptionSectionsGenerators; } RuleDescriptionSectionsGenerator getRuleDescriptionSectionsGenerator(RulesDefinition.Rule ruleDef) { Set<RuleDescriptionSectionsGenerator> generatorsFound = ruleDescriptionSectionsGenerators.stream() .filter(generator -> generator.isGeneratorForRule(ruleDef)) .collect(toSet()); checkState(generatorsFound.size() < 2, "More than one rule description section generator found for rule with key %s", ruleDef.key()); checkState(!generatorsFound.isEmpty(), "No rule description section generator found for rule with key %s", ruleDef.key()); return generatorsFound.iterator().next(); } }
2,022
43.955556
137
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/rule/RuleParam.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.rule; import org.sonar.api.server.rule.RuleParamType; import javax.annotation.CheckForNull; public interface RuleParam { String key(); @CheckForNull String description(); @CheckForNull String defaultValue(); RuleParamType type(); }
1,119
28.473684
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/rule/SingleDeprecatedRuleKey.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.rule; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.sonar.api.rule.RuleKey; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.db.rule.DeprecatedRuleKeyDto; @Immutable class SingleDeprecatedRuleKey { private String oldRuleKey; private String oldRepositoryKey; private String newRuleKey; private String newRepositoryKey; private String uuid; private String ruleUuid; /** * static methods {@link #from(RulesDefinition.Rule)} and {@link #from(DeprecatedRuleKeyDto)} must be used */ private SingleDeprecatedRuleKey() { // empty } public static Set<SingleDeprecatedRuleKey> from(RulesDefinition.Rule rule) { rule.deprecatedRuleKeys(); return rule.deprecatedRuleKeys().stream() .map(r -> new SingleDeprecatedRuleKey() .setNewRepositoryKey(rule.repository().key()) .setNewRuleKey(rule.key()) .setOldRepositoryKey(r.repository()) .setOldRuleKey(r.rule())) .collect(Collectors.toSet()); } public static SingleDeprecatedRuleKey from(DeprecatedRuleKeyDto rule) { return new SingleDeprecatedRuleKey() .setUuid(rule.getUuid()) .setRuleUuid(rule.getRuleUuid()) .setNewRepositoryKey(rule.getNewRepositoryKey()) .setNewRuleKey(rule.getNewRuleKey()) .setOldRepositoryKey(rule.getOldRepositoryKey()) .setOldRuleKey(rule.getOldRuleKey()); } public String getOldRuleKey() { return oldRuleKey; } public String getOldRepositoryKey() { return oldRepositoryKey; } public RuleKey getOldRuleKeyAsRuleKey() { return RuleKey.of(oldRepositoryKey, oldRuleKey); } public RuleKey getNewRuleKeyAsRuleKey() { return RuleKey.of(newRepositoryKey, newRuleKey); } @CheckForNull public String getNewRuleKey() { return newRuleKey; } @CheckForNull public String getNewRepositoryKey() { return newRepositoryKey; } @CheckForNull public String getUuid() { return uuid; } @CheckForNull public String getRuleUuid() { return ruleUuid; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SingleDeprecatedRuleKey that = (SingleDeprecatedRuleKey) o; return Objects.equals(oldRuleKey, that.oldRuleKey) && Objects.equals(oldRepositoryKey, that.oldRepositoryKey) && Objects.equals(newRuleKey, that.newRuleKey) && Objects.equals(newRepositoryKey, that.newRepositoryKey); } @Override public int hashCode() { return Objects.hash(oldRuleKey, oldRepositoryKey, newRuleKey, newRepositoryKey); } private SingleDeprecatedRuleKey setRuleUuid(String ruleUuid) { this.ruleUuid = ruleUuid; return this; } private SingleDeprecatedRuleKey setUuid(String uuid) { this.uuid = uuid; return this; } private SingleDeprecatedRuleKey setOldRuleKey(String oldRuleKey) { this.oldRuleKey = oldRuleKey; return this; } private SingleDeprecatedRuleKey setOldRepositoryKey(String oldRepositoryKey) { this.oldRepositoryKey = oldRepositoryKey; return this; } private SingleDeprecatedRuleKey setNewRuleKey(@Nullable String newRuleKey) { this.newRuleKey = newRuleKey; return this; } private SingleDeprecatedRuleKey setNewRepositoryKey(@Nullable String newRepositoryKey) { this.newRepositoryKey = newRepositoryKey; return this; } }
4,449
27.709677
108
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/rule/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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. */ @ParametersAreNonnullByDefault package org.sonar.server.rule; import javax.annotation.ParametersAreNonnullByDefault;
961
40.826087
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/startup/GeneratePluginIndex.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.startup; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.CharUtils; import org.sonar.api.Startable; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.api.utils.log.Profiler; import org.sonar.server.platform.ServerFileSystem; import org.sonar.server.plugins.ServerPlugin; import org.sonar.server.plugins.ServerPluginRepository; /** * The file deploy/plugins/index.txt is required for old versions of SonarLint. * They don't use the web service api/plugins/installed to get the list * of installed plugins. * https://jira.sonarsource.com/browse/SLCORE-146 */ @ServerSide public final class GeneratePluginIndex implements Startable { private static final Logger LOG = Loggers.get(GeneratePluginIndex.class); private final ServerFileSystem serverFs; private final ServerPluginRepository serverPluginRepository; public GeneratePluginIndex(ServerFileSystem serverFs, ServerPluginRepository serverPluginRepository) { this.serverFs = serverFs; this.serverPluginRepository = serverPluginRepository; } @Override public void start() { Profiler profiler = Profiler.create(LOG).startInfo("Generate scanner plugin index"); writeIndex(serverFs.getPluginIndex()); profiler.stopDebug(); } @Override public void stop() { // Nothing to do } private void writeIndex(File indexFile) { try { FileUtils.forceMkdir(indexFile.getParentFile()); try (Writer writer = new OutputStreamWriter(new FileOutputStream(indexFile), StandardCharsets.UTF_8)) { for (ServerPlugin plugin : serverPluginRepository.getPlugins()) { writer.append(toRow(plugin)); writer.append(CharUtils.LF); } writer.flush(); } } catch (IOException e) { throw new IllegalStateException("Unable to generate plugin index at " + indexFile, e); } } private static String toRow(ServerPlugin file) { return new StringBuilder().append(file.getPluginInfo().getKey()) .append(",") .append(file.getPluginInfo().isSonarLintSupported()) .append(",") .append(file.getJar().getFile().getName()) .append("|") .append(file.getJar().getMd5()) .toString(); } }
3,337
33.412371
109
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/startup/LogServerId.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.startup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.Startable; import org.sonar.api.platform.Server; public final class LogServerId implements Startable { private static final Logger LOG = LoggerFactory.getLogger(LogServerId.class); private final Server server; public LogServerId(Server server) { this.server = server; } @Override public void start() { LOG.info("Server ID: {}", server.getId()); } @Override public void stop() { // nothing to do } }
1,393
28.659574
79
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/startup/RegisterMetrics.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.startup; import com.google.common.annotations.VisibleForTesting; import java.util.HashMap; import java.util.List; import java.util.Map; import org.sonar.api.Startable; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.measures.Metric; import org.sonar.api.measures.Metrics; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.api.utils.log.Profiler; import org.sonar.core.util.UuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.metric.MetricDto; import org.sonar.server.metric.MetricToDto; import static com.google.common.collect.FluentIterable.concat; import static com.google.common.collect.Lists.newArrayList; import org.springframework.beans.factory.annotation.Autowired; public class RegisterMetrics implements Startable { private static final Logger LOG = Loggers.get(RegisterMetrics.class); private final DbClient dbClient; private final UuidFactory uuidFactory; private final Metrics[] metricsRepositories; @Autowired(required = false) public RegisterMetrics(DbClient dbClient, UuidFactory uuidFactory, Metrics[] metricsRepositories) { this.dbClient = dbClient; this.uuidFactory = uuidFactory; this.metricsRepositories = metricsRepositories; } /** * Used when no plugin is defining Metrics */ @Autowired(required = false) public RegisterMetrics(DbClient dbClient, UuidFactory uuidFactory) { this(dbClient, uuidFactory, new Metrics[] {}); } @Override public void start() { register(concat(CoreMetrics.getMetrics(), getPluginMetrics())); } @Override public void stop() { // nothing to do } void register(Iterable<Metric> metrics) { Profiler profiler = Profiler.create(LOG).startInfo("Register metrics"); try (DbSession session = dbClient.openSession(true)) { save(session, metrics); sanitizeQualityGates(session); session.commit(); } profiler.stopDebug(); } private void sanitizeQualityGates(DbSession session) { dbClient.gateConditionDao().deleteConditionsWithInvalidMetrics(session); } private void save(DbSession session, Iterable<Metric> metrics) { Map<String, MetricDto> basesByKey = new HashMap<>(); var allMetrics = dbClient.metricDao().selectAll(session); for (MetricDto base : allMetrics) { basesByKey.put(base.getKey(), base); } for (Metric metric : metrics) { MetricDto dto = MetricToDto.INSTANCE.apply(metric); MetricDto base = basesByKey.get(metric.getKey()); if (base == null) { // new metric, never installed dto.setUuid(uuidFactory.create()); dbClient.metricDao().insert(session, dto); } else { dto.setUuid(base.getUuid()); dbClient.metricDao().update(session, dto); } basesByKey.remove(metric.getKey()); } for (MetricDto nonUpdatedBase : basesByKey.values()) { if (dbClient.metricDao().disableByKey(session, nonUpdatedBase.getKey())) { LOG.info("Disable metric {} [{}]", nonUpdatedBase.getShortName(), nonUpdatedBase.getKey()); } } } @VisibleForTesting List<Metric> getPluginMetrics() { List<Metric> metricsToRegister = newArrayList(); Map<String, Metrics> metricsByRepository = new HashMap<>(); for (Metrics metrics : metricsRepositories) { checkMetrics(metricsByRepository, metrics); metricsToRegister.addAll(metrics.getMetrics()); } return metricsToRegister; } private static void checkMetrics(Map<String, Metrics> metricsByRepository, Metrics metrics) { for (Metric metric : metrics.getMetrics()) { String metricKey = metric.getKey(); if (CoreMetrics.getMetrics().contains(metric)) { throw new IllegalStateException(String.format("Metric [%s] is already defined by SonarQube", metricKey)); } Metrics anotherRepository = metricsByRepository.get(metricKey); if (anotherRepository != null) { throw new IllegalStateException(String.format("Metric [%s] is already defined by the repository [%s]", metricKey, anotherRepository)); } metricsByRepository.put(metricKey, metrics); } } }
5,047
33.813793
142
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/startup/RegisterPermissionTemplates.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.startup; import java.util.Date; import java.util.Optional; import org.sonar.api.Startable; import org.sonar.api.security.DefaultGroups; import org.sonar.api.utils.System2; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.api.utils.log.Profiler; import org.sonar.api.web.UserRole; import org.sonar.core.util.UuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.user.GroupDto; import org.sonar.server.usergroups.DefaultGroupFinder; import static org.sonar.server.property.InternalProperties.DEFAULT_PROJECT_TEMPLATE; public class RegisterPermissionTemplates implements Startable { private static final Logger LOG = Loggers.get(RegisterPermissionTemplates.class); private final DbClient dbClient; private final UuidFactory uuidFactory; private final System2 system2; private final DefaultGroupFinder defaultGroupFinder; public RegisterPermissionTemplates(DbClient dbClient, UuidFactory uuidFactory, System2 system2, DefaultGroupFinder defaultGroupFinder) { this.dbClient = dbClient; this.uuidFactory = uuidFactory; this.system2 = system2; this.defaultGroupFinder = defaultGroupFinder; } @Override public void start() { Profiler profiler = Profiler.create(Loggers.get(getClass())).startInfo("Register permission templates"); try (DbSession dbSession = dbClient.openSession(false)) { Optional<String> defaultProjectTemplate = dbClient.internalPropertiesDao().selectByKey(dbSession, DEFAULT_PROJECT_TEMPLATE); if (!defaultProjectTemplate.isPresent()) { PermissionTemplateDto defaultTemplate = getOrInsertDefaultTemplate(dbSession); dbClient.internalPropertiesDao().save(dbSession, DEFAULT_PROJECT_TEMPLATE, defaultTemplate.getUuid()); dbSession.commit(); } } profiler.stopDebug(); } @Override public void stop() { // nothing to do } private PermissionTemplateDto getOrInsertDefaultTemplate(DbSession dbSession) { PermissionTemplateDto template = new PermissionTemplateDto() .setName("Default template") .setUuid(uuidFactory.create()) .setDescription("This permission template will be used as default when no other permission configuration is available") .setCreatedAt(new Date(system2.now())) .setUpdatedAt(new Date(system2.now())); dbClient.permissionTemplateDao().insert(dbSession, template); insertDefaultGroupPermissions(dbSession, template); dbSession.commit(); return template; } private void insertDefaultGroupPermissions(DbSession dbSession, PermissionTemplateDto template) { insertPermissionForAdministrators(dbSession, template); insertPermissionsForDefaultGroup(dbSession, template); } private void insertPermissionForAdministrators(DbSession dbSession, PermissionTemplateDto template) { Optional<GroupDto> admins = dbClient.groupDao().selectByName(dbSession, DefaultGroups.ADMINISTRATORS); if (admins.isPresent()) { insertGroupPermission(dbSession, template, UserRole.ADMIN, admins.get()); } else { LOG.error("Cannot setup default permission for group: " + DefaultGroups.ADMINISTRATORS); } } private void insertPermissionsForDefaultGroup(DbSession dbSession, PermissionTemplateDto template) { GroupDto defaultGroup = defaultGroupFinder.findDefaultGroup(dbSession); insertGroupPermission(dbSession, template, UserRole.USER, defaultGroup); insertGroupPermission(dbSession, template, UserRole.CODEVIEWER, defaultGroup); insertGroupPermission(dbSession, template, UserRole.ISSUE_ADMIN, defaultGroup); insertGroupPermission(dbSession, template, UserRole.SECURITYHOTSPOT_ADMIN, defaultGroup); } private void insertGroupPermission(DbSession dbSession, PermissionTemplateDto template, String permission, GroupDto group) { dbClient.permissionTemplateDao().insertGroupPermission(dbSession, template.getUuid(), group.getUuid(), permission, template.getName(), group.getName()); } }
4,947
40.932203
156
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/startup/RegisterPlugins.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.startup; import java.util.Map; import java.util.stream.Collectors; import org.sonar.api.Startable; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.System2; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.api.utils.log.Profiler; import org.sonar.core.platform.PluginInfo; import org.sonar.core.util.UuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.plugin.PluginDto; import org.sonar.core.plugin.PluginType; import org.sonar.server.plugins.ServerPlugin; import org.sonar.server.plugins.ServerPluginRepository; import static java.util.function.Function.identity; /** * Take care to update the 'plugins' table at startup. */ @ServerSide public class RegisterPlugins implements Startable { private static final Logger LOG = Loggers.get(RegisterPlugins.class); private final ServerPluginRepository serverPluginRepository; private final DbClient dbClient; private final UuidFactory uuidFactory; private final System2 system; public RegisterPlugins(ServerPluginRepository serverPluginRepository, DbClient dbClient, UuidFactory uuidFactory, System2 system) { this.serverPluginRepository = serverPluginRepository; this.dbClient = dbClient; this.uuidFactory = uuidFactory; this.system = system; } @Override public void start() { Profiler profiler = Profiler.create(LOG).startInfo("Register plugins"); updateDB(); profiler.stopDebug(); } @Override public void stop() { // Nothing to do } private void updateDB() { long now = system.now(); try (DbSession dbSession = dbClient.openSession(false)) { Map<String, PluginDto> allPreviousPluginsByKey = dbClient.pluginDao().selectAll(dbSession).stream() .collect(Collectors.toMap(PluginDto::getKee, identity())); for (ServerPlugin installed : serverPluginRepository.getPlugins()) { PluginInfo info = installed.getPluginInfo(); PluginDto previousDto = allPreviousPluginsByKey.get(info.getKey()); if (previousDto == null) { LOG.debug("Register new plugin {}", info.getKey()); insertNewPluginDto(dbSession, installed, info); continue; } if (pluginTypeOrJarHashChanged(installed, previousDto)) { LOG.debug("Update plugin {}", info.getKey()); updatePluginDto(dbSession, installed, info, previousDto); } if (previousDto.isRemoved()) { LOG.debug("Previously removed plugin {} was re-installed", info.getKey()); previousDto.setRemoved(false); updatePluginDto(dbSession, installed, info, previousDto); } } // keep uninstalled plugins with a 'removed' flag, because corresponding rules and active rules are also not deleted for (PluginDto dto : allPreviousPluginsByKey.values()) { if (dto.isRemoved()) { continue; } if (serverPluginRepository.findPlugin(dto.getKee()).isEmpty()) { dto .setRemoved(true) .setUpdatedAt(now); dbClient.pluginDao().update(dbSession, dto); } } dbSession.commit(); } } private void insertNewPluginDto(DbSession dbSession, ServerPlugin installed, PluginInfo info) { long now = system.now(); PluginDto pluginDto = new PluginDto() .setUuid(uuidFactory.create()) .setKee(info.getKey()) .setBasePluginKey(info.getBasePlugin()) .setFileHash(installed.getJar().getMd5()) .setType(toTypeDto(installed.getType())) .setCreatedAt(now) .setUpdatedAt(now); dbClient.pluginDao().insert(dbSession, pluginDto); } private void updatePluginDto(DbSession dbSession, ServerPlugin installed, PluginInfo info, PluginDto previousDto) { long now = system.now(); previousDto .setBasePluginKey(info.getBasePlugin()) .setFileHash(installed.getJar().getMd5()) .setType(toTypeDto(installed.getType())) .setUpdatedAt(now); dbClient.pluginDao().update(dbSession, previousDto); } private static boolean pluginTypeOrJarHashChanged(ServerPlugin installed, PluginDto previousDto) { return !previousDto.getFileHash().equals(installed.getJar().getMd5()) || !previousDto.getType().equals(toTypeDto(installed.getType())); } private static PluginDto.Type toTypeDto(PluginType type) { switch (type) { case EXTERNAL: return PluginDto.Type.EXTERNAL; case BUNDLED: return PluginDto.Type.BUNDLED; default: throw new IllegalStateException("Unknown type: " + type); } } }
5,487
34.406452
139
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/startup/RenameDeprecatedPropertyKeys.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.startup; import com.google.common.base.Strings; import org.sonar.api.Startable; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.config.PropertyDefinitions; import org.slf4j.LoggerFactory; import org.sonar.db.property.PropertiesDao; /** * @since 3.4 */ public class RenameDeprecatedPropertyKeys implements Startable { private PropertiesDao dao; private PropertyDefinitions definitions; public RenameDeprecatedPropertyKeys(PropertiesDao dao, PropertyDefinitions definitions) { this.dao = dao; this.definitions = definitions; } @Override public void start() { LoggerFactory.getLogger(RenameDeprecatedPropertyKeys.class).info("Rename deprecated property keys"); for (PropertyDefinition definition : definitions.getAll()) { if (!Strings.isNullOrEmpty(definition.deprecatedKey())) { dao.renamePropertyKey(definition.deprecatedKey(), definition.key()); } } } @Override public void stop() { // nothing to do } }
1,865
31.736842
104
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/startup/UpgradeSuggestionsCleaner.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.startup; import org.sonar.api.Startable; import org.sonar.api.SonarEdition; import org.sonar.api.SonarRuntime; import org.sonar.api.server.ServerSide; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.ce.CeTaskMessageType; /** * Clean up messages (like removing upgrade suggestions after an edition upgrade) */ @ServerSide public class UpgradeSuggestionsCleaner implements Startable { private static final Logger LOGGER = LoggerFactory.getLogger(UpgradeSuggestionsCleaner.class); private final DbClient dbClient; private final SonarRuntime sonarRuntime; public UpgradeSuggestionsCleaner(DbClient dbClient, SonarRuntime sonarRuntime) { this.dbClient = dbClient; this.sonarRuntime = sonarRuntime; } @Override public void start() { if (sonarRuntime.getEdition() == SonarEdition.COMMUNITY) { return; } deleteUpgradeMessageDismissals(); } private void deleteUpgradeMessageDismissals() { LOGGER.info("Dismissed messages cleanup"); try (DbSession dbSession = dbClient.openSession(false)) { dbClient.userDismissedMessagesDao().deleteByType(dbSession, CeTaskMessageType.SUGGEST_DEVELOPER_EDITION_UPGRADE); dbClient.ceTaskMessageDao().deleteByType(dbSession, CeTaskMessageType.SUGGEST_DEVELOPER_EDITION_UPGRADE); dbSession.commit(); } } @Override public void stop() { // nothing to do } }
2,332
31.859155
119
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/startup/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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. */ @ParametersAreNonnullByDefault package org.sonar.server.startup; import javax.annotation.ParametersAreNonnullByDefault;
964
39.208333
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/telemetry/CloudUsageDataProvider.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.telemetry; import com.google.common.annotations.VisibleForTesting; import com.google.gson.Gson; import java.io.FileInputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.SecureRandom; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.util.Collection; import java.util.Scanner; import javax.annotation.CheckForNull; import javax.inject.Inject; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import okhttp3.internal.tls.OkHostnameVerifier; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.System2; import org.sonar.server.platform.ContainerSupport; import org.sonar.server.util.Paths2; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Objects.requireNonNull; @ServerSide public class CloudUsageDataProvider { private static final Logger LOG = LoggerFactory.getLogger(CloudUsageDataProvider.class); private static final String SERVICEACCOUNT_CA_PATH = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"; static final String KUBERNETES_SERVICE_HOST = "KUBERNETES_SERVICE_HOST"; static final String KUBERNETES_SERVICE_PORT = "KUBERNETES_SERVICE_PORT"; static final String SONAR_HELM_CHART_VERSION = "SONAR_HELM_CHART_VERSION"; static final String DOCKER_RUNNING = "DOCKER_RUNNING"; private static final String[] KUBERNETES_PROVIDER_COMMAND = {"bash", "-c", "uname -r"}; private final ContainerSupport containerSupport; private final System2 system2; private final Paths2 paths2; private OkHttpClient httpClient; private TelemetryData.CloudUsage cloudUsageData; @Inject public CloudUsageDataProvider(ContainerSupport containerSupport, System2 system2, Paths2 paths2) { this.containerSupport = containerSupport; this.system2 = system2; this.paths2 = paths2; if (isOnKubernetes()) { initHttpClient(); } } @VisibleForTesting CloudUsageDataProvider(ContainerSupport containerSupport, System2 system2, Paths2 paths2, OkHttpClient httpClient) { this.containerSupport = containerSupport; this.system2 = system2; this.paths2 = paths2; this.httpClient = httpClient; } public TelemetryData.CloudUsage getCloudUsage() { if (cloudUsageData != null) { return cloudUsageData; } String kubernetesVersion = null; String kubernetesPlatform = null; if (isOnKubernetes()) { VersionInfo versionInfo = getVersionInfo(); if (versionInfo != null) { kubernetesVersion = versionInfo.major() + "." + versionInfo.minor(); kubernetesPlatform = versionInfo.platform(); } } cloudUsageData = new TelemetryData.CloudUsage( isOnKubernetes(), kubernetesVersion, kubernetesPlatform, getKubernetesProvider(), getOfficialHelmChartVersion(), containerSupport.getContainerContext(), isOfficialImageUsed()); return cloudUsageData; } private boolean isOnKubernetes() { return StringUtils.isNotBlank(system2.envVariable(KUBERNETES_SERVICE_HOST)); } @CheckForNull private String getOfficialHelmChartVersion() { return system2.envVariable(SONAR_HELM_CHART_VERSION); } private boolean isOfficialImageUsed() { return Boolean.parseBoolean(system2.envVariable(DOCKER_RUNNING)); } /** * Create a http client to call the Kubernetes API. * This is based on the client creation in the official Kubernetes Java client. */ private void initHttpClient() { try { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(getKeyStore()); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManagers, new SecureRandom()); httpClient = new OkHttpClient.Builder() .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]) .hostnameVerifier(OkHostnameVerifier.INSTANCE) .build(); } catch (Exception e) { LOG.debug("Failed to create http client for Kubernetes API", e); } } private KeyStore getKeyStore() throws GeneralSecurityException, IOException { KeyStore caKeyStore = newEmptyKeyStore(); try (FileInputStream fis = new FileInputStream(paths2.get(SERVICEACCOUNT_CA_PATH).toFile())) { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(fis); int index = 0; for (Certificate certificate : certificates) { String certificateAlias = "ca" + index; caKeyStore.setCertificateEntry(certificateAlias, certificate); index++; } } return caKeyStore; } private static KeyStore newEmptyKeyStore() throws GeneralSecurityException, IOException { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); return keyStore; } record VersionInfo(String major, String minor, String platform) { } private VersionInfo getVersionInfo() { try { Request request = buildRequest(); try (Response response = httpClient.newCall(request).execute()) { ResponseBody responseBody = requireNonNull(response.body(), "Response body is null"); return new Gson().fromJson(responseBody.string(), VersionInfo.class); } } catch (Exception e) { LOG.debug("Failed to get Kubernetes version info", e); return null; } } private Request buildRequest() throws URISyntaxException { String host = system2.envVariable(KUBERNETES_SERVICE_HOST); String port = system2.envVariable(KUBERNETES_SERVICE_PORT); if (host == null || port == null) { throw new IllegalStateException("Kubernetes environment variables are not set"); } URI uri = new URI("https", null, host, Integer.parseInt(port), "/version", null, null); return new Request.Builder() .get() .url(uri.toString()) .build(); } @CheckForNull private static String getKubernetesProvider() { try { Process process = new ProcessBuilder().command(KUBERNETES_PROVIDER_COMMAND).start(); try (Scanner scanner = new Scanner(process.getInputStream(), UTF_8)) { scanner.useDelimiter("\n"); return scanner.next(); } finally { process.destroy(); } } catch (Exception e) { LOG.debug("Failed to get Kubernetes provider", e); return null; } } @VisibleForTesting OkHttpClient getHttpClient() { return httpClient; } }
7,971
33.510823
123
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/telemetry/TelemetryClient.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.telemetry; import java.io.IOException; import okhttp3.Call; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okio.BufferedSink; import okio.GzipSink; import okio.Okio; import org.sonar.api.Startable; import org.sonar.api.config.Configuration; import org.sonar.api.server.ServerSide; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.sonar.process.ProcessProperties.Property.SONAR_TELEMETRY_COMPRESSION; import static org.sonar.process.ProcessProperties.Property.SONAR_TELEMETRY_URL; @ServerSide public class TelemetryClient implements Startable { private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); private static final Logger LOG = LoggerFactory.getLogger(TelemetryClient.class); private final OkHttpClient okHttpClient; private final Configuration config; private String serverUrl; private boolean compression; public TelemetryClient(OkHttpClient okHttpClient, Configuration config) { this.config = config; this.okHttpClient = okHttpClient; } void upload(String json) throws IOException { Request request = buildHttpRequest(json); execute(okHttpClient.newCall(request)); } void optOut(String json) { Request.Builder request = new Request.Builder(); request.url(serverUrl); RequestBody body = RequestBody.create(JSON, json); request.delete(body); try { execute(okHttpClient.newCall(request.build())); } catch (IOException e) { LOG.debug("Error when sending opt-out usage statistics: {}", e.getMessage()); } } private Request buildHttpRequest(String json) { Request.Builder request = new Request.Builder(); request.addHeader("Content-Encoding", "gzip"); request.addHeader("Content-Type", "application/json"); request.url(serverUrl); RequestBody body = RequestBody.create(JSON, json); if (compression) { request.post(gzip(body)); } else { request.post(body); } return request.build(); } private static RequestBody gzip(final RequestBody body) { return new RequestBody() { @Override public MediaType contentType() { return body.contentType(); } @Override public long contentLength() { // We don't know the compressed length in advance! return -1; } @Override public void writeTo(BufferedSink sink) throws IOException { BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); body.writeTo(gzipSink); gzipSink.close(); } }; } private static void execute(Call call) throws IOException { try (Response ignored = call.execute()) { // auto close connection to avoid leaked connection } } @Override public void start() { this.serverUrl = config.get(SONAR_TELEMETRY_URL.getKey()) .orElseThrow(() -> new IllegalStateException(String.format("Setting '%s' must be provided.", SONAR_TELEMETRY_URL))); this.compression = config.getBoolean(SONAR_TELEMETRY_COMPRESSION.getKey()).orElse(true); } @Override public void stop() { // Nothing to do } }
4,061
30.734375
122
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/telemetry/TelemetryDaemon.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.telemetry; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.io.IOException; import java.io.StringWriter; import java.util.Optional; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.sonar.api.config.Configuration; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.System2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.utils.text.JsonWriter; import org.sonar.server.property.InternalProperties; import org.sonar.server.util.AbstractStoppableScheduledExecutorServiceImpl; import org.sonar.server.util.GlobalLockManager; import static org.sonar.process.ProcessProperties.Property.SONAR_TELEMETRY_ENABLE; import static org.sonar.process.ProcessProperties.Property.SONAR_TELEMETRY_FREQUENCY_IN_SECONDS; import static org.sonar.process.ProcessProperties.Property.SONAR_TELEMETRY_URL; @ServerSide public class TelemetryDaemon extends AbstractStoppableScheduledExecutorServiceImpl<ScheduledExecutorService> { private static final String THREAD_NAME_PREFIX = "sq-telemetry-service-"; private static final int ONE_DAY = 24 * 60 * 60 * 1_000; private static final String I_PROP_LAST_PING = "telemetry.lastPing"; private static final String I_PROP_OPT_OUT = "telemetry.optOut"; private static final String LOCK_NAME = "TelemetryStat"; private static final Logger LOG = LoggerFactory.getLogger(TelemetryDaemon.class); private static final String LOCK_DELAY_SEC = "sonar.telemetry.lock.delay"; static final String I_PROP_MESSAGE_SEQUENCE = "telemetry.messageSeq"; private final TelemetryDataLoader dataLoader; private final TelemetryDataJsonWriter dataJsonWriter; private final TelemetryClient telemetryClient; private final GlobalLockManager lockManager; private final Configuration config; private final InternalProperties internalProperties; private final System2 system2; public TelemetryDaemon(TelemetryDataLoader dataLoader, TelemetryDataJsonWriter dataJsonWriter, TelemetryClient telemetryClient, Configuration config, InternalProperties internalProperties, GlobalLockManager lockManager, System2 system2) { super(Executors.newSingleThreadScheduledExecutor(newThreadFactory())); this.dataLoader = dataLoader; this.dataJsonWriter = dataJsonWriter; this.telemetryClient = telemetryClient; this.config = config; this.internalProperties = internalProperties; this.lockManager = lockManager; this.system2 = system2; } @Override public void start() { boolean isTelemetryActivated = config.getBoolean(SONAR_TELEMETRY_ENABLE.getKey()) .orElseThrow(() -> new IllegalStateException(String.format("Setting '%s' must be provided.", SONAR_TELEMETRY_URL.getKey()))); boolean hasOptOut = internalProperties.read(I_PROP_OPT_OUT).isPresent(); if (!isTelemetryActivated && !hasOptOut) { optOut(); internalProperties.write(I_PROP_OPT_OUT, String.valueOf(system2.now())); LOG.info("Sharing of SonarQube statistics is disabled."); } if (isTelemetryActivated && hasOptOut) { internalProperties.write(I_PROP_OPT_OUT, null); } if (!isTelemetryActivated) { return; } LOG.info("Sharing of SonarQube statistics is enabled."); int frequencyInSeconds = frequency(); scheduleWithFixedDelay(telemetryCommand(), frequencyInSeconds, frequencyInSeconds, TimeUnit.SECONDS); } private static ThreadFactory newThreadFactory() { return new ThreadFactoryBuilder() .setNameFormat(THREAD_NAME_PREFIX + "%d") .setPriority(Thread.MIN_PRIORITY) .build(); } private Runnable telemetryCommand() { return () -> { try { if (!lockManager.tryLock(LOCK_NAME, lockDuration())) { return; } long now = system2.now(); if (shouldUploadStatistics(now)) { uploadStatistics(); updateTelemetryProps(now); } } catch (Exception e) { LOG.debug("Error while checking SonarQube statistics: {}", e.getMessage(), e); } // do not check at start up to exclude test instance which are not up for a long time }; } private void updateTelemetryProps(long now) { internalProperties.write(I_PROP_LAST_PING, String.valueOf(now)); Optional<String> currentSequence = internalProperties.read(I_PROP_MESSAGE_SEQUENCE); if (currentSequence.isEmpty()) { internalProperties.write(I_PROP_MESSAGE_SEQUENCE, String.valueOf(1)); return; } long current = Long.parseLong(currentSequence.get()); internalProperties.write(I_PROP_MESSAGE_SEQUENCE, String.valueOf(current + 1)); } private void optOut() { StringWriter json = new StringWriter(); try (JsonWriter writer = JsonWriter.of(json)) { writer.beginObject(); writer.prop("id", dataLoader.loadServerId()); writer.endObject(); } telemetryClient.optOut(json.toString()); } private void uploadStatistics() throws IOException { TelemetryData statistics = dataLoader.load(); StringWriter jsonString = new StringWriter(); try (JsonWriter json = JsonWriter.of(jsonString)) { dataJsonWriter.writeTelemetryData(json, statistics); } telemetryClient.upload(jsonString.toString()); dataLoader.reset(); } private boolean shouldUploadStatistics(long now) { Optional<Long> lastPing = internalProperties.read(I_PROP_LAST_PING).map(Long::valueOf); return lastPing.isEmpty() || now - lastPing.get() >= ONE_DAY; } private int frequency() { return config.getInt(SONAR_TELEMETRY_FREQUENCY_IN_SECONDS.getKey()) .orElseThrow(() -> new IllegalStateException(String.format("Setting '%s' must be provided.", SONAR_TELEMETRY_FREQUENCY_IN_SECONDS))); } private int lockDuration() { return config.getInt(LOCK_DELAY_SEC).orElse(60); } }
6,801
39.011765
151
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/telemetry/TelemetryDataLoaderImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.telemetry; import com.google.common.annotations.VisibleForTesting; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.Nullable; import javax.inject.Inject; import org.sonar.api.config.Configuration; import org.sonar.api.platform.Server; import org.sonar.api.server.ServerSide; import org.sonar.core.platform.PlatformEditionProvider; import org.sonar.core.platform.PluginInfo; import org.sonar.core.platform.PluginRepository; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.alm.setting.ALM; import org.sonar.db.alm.setting.ProjectAlmKeyAndProject; import org.sonar.db.component.AnalysisPropertyValuePerProject; import org.sonar.db.component.BranchMeasuresDto; import org.sonar.db.component.PrBranchAnalyzedLanguageCountByProjectDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.measure.ProjectLocDistributionDto; import org.sonar.db.measure.ProjectMainBranchLiveMeasureDto; import org.sonar.db.metric.MetricDto; import org.sonar.db.newcodeperiod.NewCodePeriodDto; import org.sonar.db.qualitygate.ProjectQgateAssociationDto; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.server.management.ManagedInstanceService; import org.sonar.server.platform.ContainerSupport; import org.sonar.server.property.InternalProperties; import org.sonar.server.qualitygate.QualityGateCaycChecker; import org.sonar.server.qualitygate.QualityGateFinder; import org.sonar.server.telemetry.TelemetryData.Database; import org.sonar.server.telemetry.TelemetryData.NewCodeDefinition; import static java.util.Arrays.asList; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toMap; import static org.sonar.api.internal.apachecommons.lang.StringUtils.startsWithIgnoreCase; import static org.sonar.api.measures.CoreMetrics.BUGS_KEY; import static org.sonar.api.measures.CoreMetrics.DEVELOPMENT_COST_KEY; import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY; import static org.sonar.api.measures.CoreMetrics.NCLOC_LANGUAGE_DISTRIBUTION_KEY; import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_KEY; import static org.sonar.api.measures.CoreMetrics.TECHNICAL_DEBT_KEY; import static org.sonar.api.measures.CoreMetrics.VULNERABILITIES_KEY; import static org.sonar.core.config.CorePropertyDefinitions.SONAR_ANALYSIS_DETECTEDCI; import static org.sonar.core.config.CorePropertyDefinitions.SONAR_ANALYSIS_DETECTEDSCM; import static org.sonar.core.platform.EditionProvider.Edition.COMMUNITY; import static org.sonar.core.platform.EditionProvider.Edition.DATACENTER; import static org.sonar.core.platform.EditionProvider.Edition.ENTERPRISE; import static org.sonar.db.newcodeperiod.NewCodePeriodType.REFERENCE_BRANCH; import static org.sonar.server.metric.UnanalyzedLanguageMetrics.UNANALYZED_CPP_KEY; import static org.sonar.server.metric.UnanalyzedLanguageMetrics.UNANALYZED_C_KEY; import static org.sonar.server.telemetry.TelemetryDaemon.I_PROP_MESSAGE_SEQUENCE; @ServerSide public class TelemetryDataLoaderImpl implements TelemetryDataLoader { @VisibleForTesting static final String SCIM_PROPERTY_ENABLED = "sonar.scim.enabled"; private static final String UNDETECTED = "undetected"; private static final Map<String, String> LANGUAGES_BY_SECURITY_JSON_PROPERTY_MAP = Map.of( "sonar.security.config.javasecurity", "java", "sonar.security.config.phpsecurity", "php", "sonar.security.config.pythonsecurity", "python", "sonar.security.config.roslyn.sonaranalyzer.security.cs", "csharp"); private final Server server; private final DbClient dbClient; private final PluginRepository pluginRepository; private final PlatformEditionProvider editionProvider; private final Configuration configuration; private final InternalProperties internalProperties; private final ContainerSupport containerSupport; private final QualityGateCaycChecker qualityGateCaycChecker; private final QualityGateFinder qualityGateFinder; private final ManagedInstanceService managedInstanceService; private final CloudUsageDataProvider cloudUsageDataProvider; private final Set<NewCodeDefinition> newCodeDefinitions = new HashSet<>(); private final Map<String, NewCodeDefinition> ncdByProject = new HashMap<>(); private final Map<String, NewCodeDefinition> ncdByBranch = new HashMap<>(); private NewCodeDefinition instanceNcd = NewCodeDefinition.getInstanceDefault(); @Inject public TelemetryDataLoaderImpl(Server server, DbClient dbClient, PluginRepository pluginRepository, PlatformEditionProvider editionProvider, InternalProperties internalProperties, Configuration configuration, ContainerSupport containerSupport, QualityGateCaycChecker qualityGateCaycChecker, QualityGateFinder qualityGateFinder, ManagedInstanceService managedInstanceService, CloudUsageDataProvider cloudUsageDataProvider) { this.server = server; this.dbClient = dbClient; this.pluginRepository = pluginRepository; this.editionProvider = editionProvider; this.internalProperties = internalProperties; this.configuration = configuration; this.containerSupport = containerSupport; this.qualityGateCaycChecker = qualityGateCaycChecker; this.qualityGateFinder = qualityGateFinder; this.managedInstanceService = managedInstanceService; this.cloudUsageDataProvider = cloudUsageDataProvider; } private static Database loadDatabaseMetadata(DbSession dbSession) { try { DatabaseMetaData metadata = dbSession.getConnection().getMetaData(); return new Database(metadata.getDatabaseProductName(), metadata.getDatabaseProductVersion()); } catch (SQLException e) { throw new IllegalStateException("Fail to get DB metadata", e); } } @Override public TelemetryData load() { TelemetryData.Builder data = TelemetryData.builder(); data.setMessageSequenceNumber(retrieveCurrentMessageSequenceNumber() + 1); data.setServerId(server.getId()); data.setVersion(server.getVersion()); data.setEdition(editionProvider.get().orElse(null)); Function<PluginInfo, String> getVersion = plugin -> plugin.getVersion() == null ? "undefined" : plugin.getVersion().getName(); Map<String, String> plugins = pluginRepository.getPluginInfos().stream().collect(toMap(PluginInfo::getKey, getVersion)); data.setPlugins(plugins); try (DbSession dbSession = dbClient.openSession(false)) { var branchMeasuresDtos = dbClient.branchDao().selectBranchMeasuresWithCaycMetric(dbSession); loadNewCodeDefinitions(dbSession, branchMeasuresDtos); data.setDatabase(loadDatabaseMetadata(dbSession)); data.setNcdId(instanceNcd.hashCode()); data.setNewCodeDefinitions(newCodeDefinitions); String defaultQualityGateUuid = qualityGateFinder.getDefault(dbSession).getUuid(); data.setDefaultQualityGate(defaultQualityGateUuid); resolveUnanalyzedLanguageCode(data, dbSession); resolveProjectStatistics(data, dbSession, defaultQualityGateUuid); resolveProjects(data, dbSession); resolveBranches(data, branchMeasuresDtos); resolveQualityGates(data, dbSession); resolveUsers(data, dbSession); } setSecurityCustomConfigIfPresent(data); Optional<String> installationDateProperty = internalProperties.read(InternalProperties.INSTALLATION_DATE); installationDateProperty.ifPresent(s -> data.setInstallationDate(Long.valueOf(s))); Optional<String> installationVersionProperty = internalProperties.read(InternalProperties.INSTALLATION_VERSION); return data .setInstallationVersion(installationVersionProperty.orElse(null)) .setInContainer(containerSupport.isRunningInContainer()) .setManagedInstanceInformation(buildManagedInstanceInformation()) .setCloudUsage(buildCloudUsage()) .build(); } private void resolveBranches(TelemetryData.Builder data, List<BranchMeasuresDto> branchMeasuresDtos) { var branches = branchMeasuresDtos.stream() .map(dto -> { var projectNcd = ncdByProject.getOrDefault(dto.getProjectUuid(), instanceNcd); var ncdId = ncdByBranch.getOrDefault(dto.getBranchUuid(), projectNcd).hashCode(); return new TelemetryData.Branch( dto.getProjectUuid(), dto.getBranchUuid(), ncdId, dto.getGreenQualityGateCount(), dto.getAnalysisCount(), dto.getExcludeFromPurge()); }) .toList(); data.setBranches(branches); } @Override public void reset() { this.newCodeDefinitions.clear(); this.ncdByBranch.clear(); this.ncdByProject.clear(); this.instanceNcd = NewCodeDefinition.getInstanceDefault(); } private void loadNewCodeDefinitions(DbSession dbSession, List<BranchMeasuresDto> branchMeasuresDtos) { var branchUuidByKey = branchMeasuresDtos.stream() .collect(Collectors.toMap(dto -> createBranchUniqueKey(dto.getProjectUuid(), dto.getBranchKey()), BranchMeasuresDto::getBranchUuid)); List<NewCodePeriodDto> newCodePeriodDtos = dbClient.newCodePeriodDao().selectAll(dbSession); NewCodeDefinition ncd; boolean hasInstance = false; for (var dto : newCodePeriodDtos) { String projectUuid = dto.getProjectUuid(); String branchUuid = dto.getBranchUuid(); if (branchUuid == null && projectUuid == null) { ncd = new NewCodeDefinition(dto.getType().name(), dto.getValue(), "instance"); this.instanceNcd = ncd; hasInstance = true; } else if (projectUuid != null) { var value = dto.getType() == REFERENCE_BRANCH ? branchUuidByKey.get(createBranchUniqueKey(projectUuid, dto.getValue())) : dto.getValue(); if (branchUuid == null || isCommunityEdition()) { ncd = new NewCodeDefinition(dto.getType().name(), value, "project"); this.ncdByProject.put(projectUuid, ncd); } else { ncd = new NewCodeDefinition(dto.getType().name(), value, "branch"); this.ncdByBranch.put(branchUuid, ncd); } } else { throw new IllegalStateException(String.format("Error in loading telemetry data. New code definition for branch %s doesn't have a projectUuid", branchUuid)); } this.newCodeDefinitions.add(ncd); } if (!hasInstance) { this.newCodeDefinitions.add(NewCodeDefinition.getInstanceDefault()); } } private boolean isCommunityEdition() { var edition = editionProvider.get(); return edition.isPresent() && edition.get() == COMMUNITY; } private static String createBranchUniqueKey(String projectUuid, @Nullable String branchKey) { return projectUuid + "-" + branchKey; } private void resolveUnanalyzedLanguageCode(TelemetryData.Builder data, DbSession dbSession) { long numberOfUnanalyzedCMeasures = dbClient.liveMeasureDao().countProjectsHavingMeasure(dbSession, UNANALYZED_C_KEY); long numberOfUnanalyzedCppMeasures = dbClient.liveMeasureDao().countProjectsHavingMeasure(dbSession, UNANALYZED_CPP_KEY); editionProvider.get() .filter(edition -> edition.equals(COMMUNITY)) .ifPresent(edition -> { data.setHasUnanalyzedC(numberOfUnanalyzedCMeasures > 0); data.setHasUnanalyzedCpp(numberOfUnanalyzedCppMeasures > 0); }); } private Long retrieveCurrentMessageSequenceNumber() { return internalProperties.read(I_PROP_MESSAGE_SEQUENCE).map(Long::parseLong).orElse(0L); } private void resolveProjectStatistics(TelemetryData.Builder data, DbSession dbSession, String defaultQualityGateUuid) { List<String> projectUuids = dbClient.projectDao().selectAllProjectUuids(dbSession); Map<String, String> scmByProject = getAnalysisPropertyByProject(dbSession, SONAR_ANALYSIS_DETECTEDSCM); Map<String, String> ciByProject = getAnalysisPropertyByProject(dbSession, SONAR_ANALYSIS_DETECTEDCI); Map<String, ProjectAlmKeyAndProject> almAndUrlByProject = getAlmAndUrlByProject(dbSession); Map<String, PrBranchAnalyzedLanguageCountByProjectDto> prAndBranchCountByProject = dbClient.branchDao().countPrBranchAnalyzedLanguageByProjectUuid(dbSession) .stream().collect(toMap(PrBranchAnalyzedLanguageCountByProjectDto::getProjectUuid, Function.identity())); Map<String, String> qgatesByProject = getProjectQgatesMap(dbSession); Map<String, Map<String, Number>> metricsByProject = getProjectMetricsByMetricKeys(dbSession, TECHNICAL_DEBT_KEY, DEVELOPMENT_COST_KEY, SECURITY_HOTSPOTS_KEY, VULNERABILITIES_KEY, BUGS_KEY); List<TelemetryData.ProjectStatistics> projectStatistics = new ArrayList<>(); for (String projectUuid : projectUuids) { Map<String, Number> metrics = metricsByProject.getOrDefault(projectUuid, Collections.emptyMap()); Optional<PrBranchAnalyzedLanguageCountByProjectDto> counts = ofNullable(prAndBranchCountByProject.get(projectUuid)); TelemetryData.ProjectStatistics stats = new TelemetryData.ProjectStatistics.Builder() .setProjectUuid(projectUuid) .setBranchCount(counts.map(PrBranchAnalyzedLanguageCountByProjectDto::getBranch).orElse(0L)) .setPRCount(counts.map(PrBranchAnalyzedLanguageCountByProjectDto::getPullRequest).orElse(0L)) .setQG(qgatesByProject.getOrDefault(projectUuid, defaultQualityGateUuid)) .setScm(Optional.ofNullable(scmByProject.get(projectUuid)).orElse(UNDETECTED)) .setCi(Optional.ofNullable(ciByProject.get(projectUuid)).orElse(UNDETECTED)) .setDevops(resolveDevopsPlatform(almAndUrlByProject, projectUuid)) .setBugs(metrics.getOrDefault("bugs", null)) .setDevelopmentCost(metrics.getOrDefault("development_cost", null)) .setVulnerabilities(metrics.getOrDefault("vulnerabilities", null)) .setSecurityHotspots(metrics.getOrDefault("security_hotspots", null)) .setTechnicalDebt(metrics.getOrDefault("sqale_index", null)) .setNcdId(ncdByProject.getOrDefault(projectUuid, instanceNcd).hashCode()) .build(); projectStatistics.add(stats); } data.setProjectStatistics(projectStatistics); } private static String resolveDevopsPlatform(Map<String, ProjectAlmKeyAndProject> almAndUrlByProject, String projectUuid) { if (almAndUrlByProject.containsKey(projectUuid)) { ProjectAlmKeyAndProject projectAlmKeyAndProject = almAndUrlByProject.get(projectUuid); return getAlmName(projectAlmKeyAndProject.getAlmId(), projectAlmKeyAndProject.getUrl()); } return UNDETECTED; } private void resolveProjects(TelemetryData.Builder data, DbSession dbSession) { Map<String, String> metricUuidMap = getNclocMetricUuidMap(dbSession); String nclocUuid = metricUuidMap.get(NCLOC_KEY); String nclocDistributionUuid = metricUuidMap.get(NCLOC_LANGUAGE_DISTRIBUTION_KEY); List<ProjectLocDistributionDto> branchesWithLargestNcloc = dbClient.liveMeasureDao().selectLargestBranchesLocDistribution(dbSession, nclocUuid, nclocDistributionUuid); List<String> branchUuids = branchesWithLargestNcloc.stream().map(ProjectLocDistributionDto::branchUuid).toList(); Map<String, Long> latestSnapshotMap = dbClient.snapshotDao().selectLastAnalysesByRootComponentUuids(dbSession, branchUuids) .stream() .collect(toMap(SnapshotDto::getRootComponentUuid, SnapshotDto::getBuildDate)); data.setProjects(buildProjectsList(branchesWithLargestNcloc, latestSnapshotMap)); } private static List<TelemetryData.Project> buildProjectsList(List<ProjectLocDistributionDto> branchesWithLargestNcloc, Map<String, Long> latestSnapshotMap) { return branchesWithLargestNcloc.stream() .flatMap(measure -> Arrays.stream(measure.locDistribution().split(";")) .map(languageAndLoc -> languageAndLoc.split("=")) .map(languageAndLoc -> new TelemetryData.Project( measure.projectUuid(), latestSnapshotMap.get(measure.branchUuid()), languageAndLoc[0], Long.parseLong(languageAndLoc[1]) )) ).toList(); } private Map<String, String> getNclocMetricUuidMap(DbSession dbSession) { return dbClient.metricDao().selectByKeys(dbSession, asList(NCLOC_KEY, NCLOC_LANGUAGE_DISTRIBUTION_KEY)) .stream() .collect(toMap(MetricDto::getKey, MetricDto::getUuid)); } private void resolveQualityGates(TelemetryData.Builder data, DbSession dbSession) { List<TelemetryData.QualityGate> qualityGates = new ArrayList<>(); Collection<QualityGateDto> qualityGateDtos = dbClient.qualityGateDao().selectAll(dbSession); for (QualityGateDto qualityGateDto : qualityGateDtos) { qualityGates.add( new TelemetryData.QualityGate(qualityGateDto.getUuid(), qualityGateCaycChecker.checkCaycCompliant(dbSession, qualityGateDto.getUuid()).toString()) ); } data.setQualityGates(qualityGates); } private void resolveUsers(TelemetryData.Builder data, DbSession dbSession) { data.setUsers(dbClient.userDao().selectUsersForTelemetry(dbSession)); } private void setSecurityCustomConfigIfPresent(TelemetryData.Builder data) { editionProvider.get() .filter(edition -> asList(ENTERPRISE, DATACENTER).contains(edition)) .ifPresent(edition -> data.setCustomSecurityConfigs(getCustomerSecurityConfigurations())); } private Map<String, String> getAnalysisPropertyByProject(DbSession dbSession, String analysisPropertyKey) { return dbClient.analysisPropertiesDao() .selectAnalysisPropertyValueInLastAnalysisPerProject(dbSession, analysisPropertyKey) .stream() .collect(toMap(AnalysisPropertyValuePerProject::getProjectUuid, AnalysisPropertyValuePerProject::getPropertyValue)); } private Map<String, ProjectAlmKeyAndProject> getAlmAndUrlByProject(DbSession dbSession) { List<ProjectAlmKeyAndProject> projectAlmKeyAndProjects = dbClient.projectAlmSettingDao().selectAlmTypeAndUrlByProject(dbSession); return projectAlmKeyAndProjects.stream().collect(toMap(ProjectAlmKeyAndProject::getProjectUuid, Function.identity())); } private static String getAlmName(String alm, String url) { if (checkIfCloudAlm(alm, ALM.GITHUB.getId(), url, "https://api.github.com")) { return "github_cloud"; } if (checkIfCloudAlm(alm, ALM.GITLAB.getId(), url, "https://gitlab.com/api/v4")) { return "gitlab_cloud"; } if (checkIfCloudAlm(alm, ALM.AZURE_DEVOPS.getId(), url, "https://dev.azure.com")) { return "azure_devops_cloud"; } if (ALM.BITBUCKET_CLOUD.getId().equals(alm)) { return alm; } return alm + "_server"; } private Map<String, String> getProjectQgatesMap(DbSession dbSession) { return dbClient.projectQgateAssociationDao().selectAll(dbSession) .stream() .collect(toMap(ProjectQgateAssociationDto::getUuid, p -> Optional.ofNullable(p.getGateUuid()).orElse(""))); } private Map<String, Map<String, Number>> getProjectMetricsByMetricKeys(DbSession dbSession, String... metricKeys) { Map<String, String> metricNamesByUuid = dbClient.metricDao().selectByKeys(dbSession, asList(metricKeys)) .stream() .collect(toMap(MetricDto::getUuid, MetricDto::getKey)); // metrics can be empty for un-analyzed projects if (metricNamesByUuid.isEmpty()) { return Collections.emptyMap(); } return dbClient.liveMeasureDao().selectForProjectMainBranchesByMetricUuids(dbSession, metricNamesByUuid.keySet()) .stream() .collect(groupingBy(ProjectMainBranchLiveMeasureDto::getProjectUuid, toMap(lmDto -> metricNamesByUuid.get(lmDto.getMetricUuid()), lmDto -> Optional.ofNullable(lmDto.getValue()).orElseGet(() -> Double.valueOf(lmDto.getTextValue())), (oldValue, newValue) -> newValue, HashMap::new))); } private static boolean checkIfCloudAlm(String almRaw, String alm, String url, String cloudUrl) { return alm.equals(almRaw) && startsWithIgnoreCase(url, cloudUrl); } @Override public String loadServerId() { return server.getId(); } private Set<String> getCustomerSecurityConfigurations() { return LANGUAGES_BY_SECURITY_JSON_PROPERTY_MAP.keySet().stream() .filter(this::isPropertyPresentInConfiguration) .map(LANGUAGES_BY_SECURITY_JSON_PROPERTY_MAP::get) .collect(Collectors.toSet()); } private boolean isPropertyPresentInConfiguration(String property) { return configuration.get(property).isPresent(); } private TelemetryData.ManagedInstanceInformation buildManagedInstanceInformation() { String provider = managedInstanceService.isInstanceExternallyManaged() ? managedInstanceService.getProviderName() : null; return new TelemetryData.ManagedInstanceInformation(managedInstanceService.isInstanceExternallyManaged(), provider); } private TelemetryData.CloudUsage buildCloudUsage() { return cloudUsageDataProvider.getCloudUsage(); } }
21,997
47.776053
171
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/telemetry/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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. */ @ParametersAreNonnullByDefault package org.sonar.server.telemetry; import javax.annotation.ParametersAreNonnullByDefault;
967
37.72
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/updatecenter/UpdateCenterModule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.updatecenter; import org.sonar.core.platform.Module; import org.sonar.server.plugins.UpdateCenterClient; import org.sonar.server.plugins.UpdateCenterMatrixFactory; public class UpdateCenterModule extends Module { @Override protected void configureModule() { add( UpdateCenterClient.class, UpdateCenterMatrixFactory.class); } }
1,219
34.882353
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/updatecenter/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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. */ @ParametersAreNonnullByDefault package org.sonar.server.updatecenter; import javax.annotation.ParametersAreNonnullByDefault;
969
39.416667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/util/DateCollector.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.util; import javax.annotation.Nullable; import java.util.Date; public class DateCollector { private long maxDate = 0L; public void add(@Nullable Date d) { if (d != null) { add(d.getTime()); } } public void add(long date) { maxDate = Math.max(maxDate, date); } /** * The most recent collected date. Value is zero if no dates were collected. */ public long getMax() { return maxDate; } }
1,305
26.787234
78
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/util/TempFolderCleaner.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.util; import org.sonar.api.Startable; import org.sonar.api.impl.utils.DefaultTempFolder; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.TempFolder; @ServerSide public class TempFolderCleaner implements Startable { private TempFolder defaultTempFolder; public TempFolderCleaner(TempFolder defaultTempFolder) { this.defaultTempFolder = defaultTempFolder; } /** * This method should not be renamed. It follows the naming convention * defined by IoC container. */ @Override public void start() { // Nothing to do } /** * This method should not be renamed. It follows the naming convention * defined by IoC container. */ @Override public void stop() { ((DefaultTempFolder) defaultTempFolder).clean(); } }
1,646
29.5
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/util/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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. */ @ParametersAreNonnullByDefault package org.sonar.server.util; import javax.annotation.ParametersAreNonnullByDefault;
961
39.083333
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/webhook/WebhookQGChangeEventListener.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.webhook; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.sonar.api.measures.Metric; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.AnalysisPropertyDto; import org.sonar.db.component.BranchDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.qualitygate.EvaluatedQualityGate; import org.sonar.server.qualitygate.changeevent.QGChangeEvent; import org.sonar.server.qualitygate.changeevent.QGChangeEventListener; import org.sonar.server.webhook.Branch.Type; public class WebhookQGChangeEventListener implements QGChangeEventListener { private final WebHooks webhooks; private final WebhookPayloadFactory webhookPayloadFactory; private final DbClient dbClient; public WebhookQGChangeEventListener(WebHooks webhooks, WebhookPayloadFactory webhookPayloadFactory, DbClient dbClient) { this.webhooks = webhooks; this.webhookPayloadFactory = webhookPayloadFactory; this.dbClient = dbClient; } @Override public void onIssueChanges(QGChangeEvent qualityGateEvent, Set<ChangedIssue> changedIssues) { if (!webhooks.isEnabled(qualityGateEvent.getProject())) { return; } Optional<EvaluatedQualityGate> evaluatedQualityGate = qualityGateEvent.getQualityGateSupplier().get(); if (isQGStatusUnchanged(qualityGateEvent, evaluatedQualityGate)) { return; } try (DbSession dbSession = dbClient.openSession(false)) { callWebhook(dbSession, qualityGateEvent, evaluatedQualityGate.orElse(null)); } } private static boolean isQGStatusUnchanged(QGChangeEvent qualityGateEvent, Optional<EvaluatedQualityGate> evaluatedQualityGate) { Optional<Metric.Level> previousStatus = qualityGateEvent.getPreviousStatus(); if (!previousStatus.isPresent() && !evaluatedQualityGate.isPresent()) { return true; } return previousStatus .map(previousQGStatus -> evaluatedQualityGate .filter(newQualityGate -> newQualityGate.getStatus() == previousQGStatus) .isPresent()) .orElse(false); } private void callWebhook(DbSession dbSession, QGChangeEvent event, @Nullable EvaluatedQualityGate evaluatedQualityGate) { webhooks.sendProjectAnalysisUpdate( new WebHooks.Analysis(event.getProject().getUuid(), event.getAnalysis().getUuid(), null), () -> buildWebHookPayload(dbSession, event, evaluatedQualityGate)); } private WebhookPayload buildWebHookPayload(DbSession dbSession, QGChangeEvent event, @Nullable EvaluatedQualityGate evaluatedQualityGate) { ProjectDto project = event.getProject(); BranchDto branch = event.getBranch(); SnapshotDto analysis = event.getAnalysis(); Map<String, String> analysisProperties = dbClient.analysisPropertiesDao().selectByAnalysisUuid(dbSession, analysis.getUuid()) .stream() .collect(Collectors.toMap(AnalysisPropertyDto::getKey, AnalysisPropertyDto::getValue)); ProjectAnalysis projectAnalysis = new ProjectAnalysis( new Project(project.getUuid(), project.getKey(), project.getName()), null, new Analysis(analysis.getUuid(), analysis.getCreatedAt(), analysis.getRevision()), new Branch(branch.isMain(), branch.getKey(), Type.valueOf(branch.getBranchType().name())), evaluatedQualityGate, null, analysisProperties); return webhookPayloadFactory.create(projectAnalysis); } }
4,375
41.076923
141
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/webhook/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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. */ @ParametersAreNonnullByDefault package org.sonar.server.webhook; import javax.annotation.ParametersAreNonnullByDefault;
964
39.208333
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/app/WebServerProcessLoggingTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.app; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; import ch.qos.logback.core.AppenderBase; import ch.qos.logback.core.ConsoleAppender; import ch.qos.logback.core.FileAppender; import ch.qos.logback.core.OutputStreamAppender; import ch.qos.logback.core.encoder.Encoder; import ch.qos.logback.core.encoder.LayoutWrappingEncoder; import ch.qos.logback.core.joran.spi.JoranException; import com.google.common.collect.ImmutableList; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.stream.Stream; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.process.Props; import org.sonar.process.logging.LogbackHelper; import org.sonar.process.logging.LogbackJsonLayout; import org.sonar.process.logging.PatternLayoutEncoder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.slf4j.Logger.ROOT_LOGGER_NAME; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; public class WebServerProcessLoggingTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); private File logDir; private Props props = new Props(new Properties()); private WebServerProcessLogging underTest = new WebServerProcessLogging(); @Before public void setUp() throws IOException { logDir = temp.newFolder(); props.set(PATH_LOGS.getKey(), logDir.getAbsolutePath()); } @AfterClass public static void resetLogback() throws JoranException { new LogbackHelper().resetFromXml("/logback-test.xml"); } @Test public void do_not_log_to_console() { LoggerContext ctx = underTest.configure(props); Logger root = ctx.getLogger(Logger.ROOT_LOGGER_NAME); Appender appender = root.getAppender("CONSOLE"); assertThat(appender).isNull(); } @Test public void check_level_of_jul() throws IOException { Props props = new Props(new Properties()); File dir = temp.newFolder(); props.set(PATH_LOGS.getKey(), dir.getAbsolutePath()); props.set("sonar.log.level.web", "TRACE"); LoggerContext ctx = underTest.configure(props); MemoryAppender memoryAppender = new MemoryAppender(); memoryAppender.start(); ctx.getLogger(ROOT_LOGGER_NAME).addAppender(memoryAppender); java.util.logging.Logger logger = java.util.logging.Logger.getLogger("com.ms.sqlserver.jdbc.DTV"); logger.finest("Test"); memoryAppender.stop(); assertThat(memoryAppender.getLogs()).hasSize(1); } @Test public void startup_logger_prints_to_only_to_system_out() { LoggerContext ctx = underTest.configure(props); Logger startup = ctx.getLogger("startup"); assertThat(startup.isAdditive()).isFalse(); Appender appender = startup.getAppender("CONSOLE"); assertThat(appender).isInstanceOf(ConsoleAppender.class); ConsoleAppender<ILoggingEvent> consoleAppender = (ConsoleAppender<ILoggingEvent>) appender; assertThat(consoleAppender.getTarget()).isEqualTo("System.out"); assertThat(consoleAppender.getEncoder()).isInstanceOf(PatternLayoutEncoder.class); PatternLayoutEncoder patternEncoder = (PatternLayoutEncoder) consoleAppender.getEncoder(); assertThat(patternEncoder.getPattern()).isEqualTo("%d{yyyy.MM.dd HH:mm:ss} %-5level app[][%logger{20}] %msg%n"); } @Test public void log_to_web_file() { LoggerContext ctx = underTest.configure(props); Logger root = ctx.getLogger(Logger.ROOT_LOGGER_NAME); Appender<ILoggingEvent> appender = root.getAppender("file_web"); assertThat(appender).isInstanceOf(FileAppender.class); FileAppender fileAppender = (FileAppender) appender; assertThat(fileAppender.getFile()).isEqualTo(new File(logDir, "web.log").getAbsolutePath()); assertThat(fileAppender.getEncoder()).isInstanceOf(PatternLayoutEncoder.class); PatternLayoutEncoder encoder = (PatternLayoutEncoder) fileAppender.getEncoder(); assertThat(encoder.getPattern()).isEqualTo("%d{yyyy.MM.dd HH:mm:ss} %-5level web[%X{HTTP_REQUEST_ID}][%logger{20}] %msg%n"); } @Test public void log_for_cluster_changes_layout_in_file_and_console() { props.set("sonar.cluster.enabled", "true"); props.set("sonar.cluster.node.name", "my-node"); LoggerContext ctx = underTest.configure(props); Logger root = ctx.getLogger(Logger.ROOT_LOGGER_NAME); FileAppender fileAppender = (FileAppender) root.getAppender("file_web"); PatternLayoutEncoder encoder = (PatternLayoutEncoder) fileAppender.getEncoder(); assertThat(encoder.getPattern()).isEqualTo("%d{yyyy.MM.dd HH:mm:ss} %-5level my-node web[%X{HTTP_REQUEST_ID}][%logger{20}] %msg%n"); Logger startup = ctx.getLogger("startup"); ConsoleAppender<ILoggingEvent> consoleAppender = (ConsoleAppender<ILoggingEvent>) startup.getAppender("CONSOLE"); PatternLayoutEncoder patternEncoder = (PatternLayoutEncoder) consoleAppender.getEncoder(); assertThat(patternEncoder.getPattern()).isEqualTo("%d{yyyy.MM.dd HH:mm:ss} %-5level my-node app[][%logger{20}] %msg%n"); } @Test public void default_level_for_root_logger_is_INFO() { LoggerContext ctx = underTest.configure(props); verifyRootLogLevel(ctx, Level.INFO); } @Test public void root_logger_level_changes_with_global_property() { props.set("sonar.log.level", "TRACE"); LoggerContext ctx = underTest.configure(props); verifyRootLogLevel(ctx, Level.TRACE); } @Test public void root_logger_level_changes_with_web_property() { props.set("sonar.log.level.web", "TRACE"); LoggerContext ctx = underTest.configure(props); verifyRootLogLevel(ctx, Level.TRACE); } @Test public void root_logger_level_is_configured_from_web_property_over_global_property() { props.set("sonar.log.level", "TRACE"); props.set("sonar.log.level.web", "DEBUG"); LoggerContext ctx = underTest.configure(props); verifyRootLogLevel(ctx, Level.DEBUG); } @Test public void root_logger_level_changes_with_web_property_and_is_case_insensitive() { props.set("sonar.log.level.web", "debug"); LoggerContext ctx = underTest.configure(props); verifyRootLogLevel(ctx, Level.DEBUG); } @Test public void sql_logger_level_changes_with_global_property_and_is_case_insensitive() { props.set("sonar.log.level", "InFO"); LoggerContext ctx = underTest.configure(props); verifySqlLogLevel(ctx, Level.INFO); } @Test public void sql_logger_level_changes_with_web_property_and_is_case_insensitive() { props.set("sonar.log.level.web", "TrACe"); LoggerContext ctx = underTest.configure(props); verifySqlLogLevel(ctx, Level.TRACE); } @Test public void sql_logger_level_changes_with_web_sql_property_and_is_case_insensitive() { props.set("sonar.log.level.web.sql", "debug"); LoggerContext ctx = underTest.configure(props); verifySqlLogLevel(ctx, Level.DEBUG); } @Test public void sql_logger_level_is_configured_from_web_sql_property_over_web_property() { props.set("sonar.log.level.web.sql", "debug"); props.set("sonar.log.level.web", "TRACE"); LoggerContext ctx = underTest.configure(props); verifySqlLogLevel(ctx, Level.DEBUG); } @Test public void sql_logger_level_is_configured_from_web_sql_property_over_global_property() { props.set("sonar.log.level.web.sql", "debug"); props.set("sonar.log.level", "TRACE"); LoggerContext ctx = underTest.configure(props); verifySqlLogLevel(ctx, Level.DEBUG); } @Test public void sql_logger_level_is_configured_from_web_property_over_global_property() { props.set("sonar.log.level.web", "debug"); props.set("sonar.log.level", "TRACE"); LoggerContext ctx = underTest.configure(props); verifySqlLogLevel(ctx, Level.DEBUG); } @Test public void es_logger_level_changes_with_global_property_and_is_case_insensitive() { props.set("sonar.log.level", "InFO"); LoggerContext ctx = underTest.configure(props); verifyEsLogLevel(ctx, Level.INFO); } @Test public void es_logger_level_changes_with_web_property_and_is_case_insensitive() { props.set("sonar.log.level.web", "TrACe"); LoggerContext ctx = underTest.configure(props); verifyEsLogLevel(ctx, Level.TRACE); } @Test public void es_logger_level_changes_with_web_es_property_and_is_case_insensitive() { props.set("sonar.log.level.web.es", "debug"); LoggerContext ctx = underTest.configure(props); verifyEsLogLevel(ctx, Level.DEBUG); } @Test public void es_logger_level_is_configured_from_web_es_property_over_web_property() { props.set("sonar.log.level.web.es", "debug"); props.set("sonar.log.level.web", "TRACE"); LoggerContext ctx = underTest.configure(props); verifyEsLogLevel(ctx, Level.DEBUG); } @Test public void es_logger_level_is_configured_from_web_es_property_over_global_property() { props.set("sonar.log.level.web.es", "debug"); props.set("sonar.log.level", "TRACE"); LoggerContext ctx = underTest.configure(props); verifyEsLogLevel(ctx, Level.DEBUG); } @Test public void es_logger_level_is_configured_from_web_property_over_global_property() { props.set("sonar.log.level.web", "debug"); props.set("sonar.log.level", "TRACE"); LoggerContext ctx = underTest.configure(props); verifyEsLogLevel(ctx, Level.DEBUG); } @Test public void jmx_logger_level_changes_with_global_property_and_is_case_insensitive() { props.set("sonar.log.level", "InFO"); LoggerContext ctx = underTest.configure(props); verifyJmxLogLevel(ctx, Level.INFO); } @Test public void jmx_logger_level_changes_with_jmx_property_and_is_case_insensitive() { props.set("sonar.log.level.web", "TrACe"); LoggerContext ctx = underTest.configure(props); verifyJmxLogLevel(ctx, Level.TRACE); } @Test public void jmx_logger_level_changes_with_web_jmx_property_and_is_case_insensitive() { props.set("sonar.log.level.web.jmx", "debug"); LoggerContext ctx = underTest.configure(props); verifyJmxLogLevel(ctx, Level.DEBUG); } @Test public void jmx_logger_level_is_configured_from_web_jmx_property_over_web_property() { props.set("sonar.log.level.web.jmx", "debug"); props.set("sonar.log.level.web", "TRACE"); LoggerContext ctx = underTest.configure(props); verifyJmxLogLevel(ctx, Level.DEBUG); } @Test public void jmx_logger_level_is_configured_from_web_jmx_property_over_global_property() { props.set("sonar.log.level.web.jmx", "debug"); props.set("sonar.log.level", "TRACE"); LoggerContext ctx = underTest.configure(props); verifyJmxLogLevel(ctx, Level.DEBUG); } @Test public void jmx_logger_level_is_configured_from_web_property_over_global_property() { props.set("sonar.log.level.web", "debug"); props.set("sonar.log.level", "TRACE"); LoggerContext ctx = underTest.configure(props); verifyJmxLogLevel(ctx, Level.DEBUG); } @Test public void root_logger_level_defaults_to_INFO_if_web_property_has_invalid_value() { props.set("sonar.log.level.web", "DodoDouh!"); LoggerContext ctx = underTest.configure(props); verifyRootLogLevel(ctx, Level.INFO); } @Test public void sql_logger_level_defaults_to_INFO_if_web_sql_property_has_invalid_value() { props.set("sonar.log.level.web.sql", "DodoDouh!"); LoggerContext ctx = underTest.configure(props); verifySqlLogLevel(ctx, Level.INFO); } @Test public void es_logger_level_defaults_to_INFO_if_web_es_property_has_invalid_value() { props.set("sonar.log.level.web.es", "DodoDouh!"); LoggerContext ctx = underTest.configure(props); verifyEsLogLevel(ctx, Level.INFO); } @Test public void jmx_loggers_level_defaults_to_INFO_if_wedb_jmx_property_has_invalid_value() { props.set("sonar.log.level.web.jmx", "DodoDouh!"); LoggerContext ctx = underTest.configure(props); verifyJmxLogLevel(ctx, Level.INFO); } @Test public void fail_with_IAE_if_global_property_unsupported_level() { props.set("sonar.log.level", "ERROR"); assertThatThrownBy(() -> underTest.configure(props)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("log level ERROR in property sonar.log.level is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void fail_with_IAE_if_web_property_unsupported_level() { props.set("sonar.log.level.web", "ERROR"); assertThatThrownBy(() -> underTest.configure(props)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("log level ERROR in property sonar.log.level.web is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void fail_with_IAE_if_web_sql_property_unsupported_level() { props.set("sonar.log.level.web.sql", "ERROR"); assertThatThrownBy(() -> underTest.configure(props)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("log level ERROR in property sonar.log.level.web.sql is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void fail_with_IAE_if_web_es_property_unsupported_level() { props.set("sonar.log.level.web.es", "ERROR"); assertThatThrownBy(() -> underTest.configure(props)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("log level ERROR in property sonar.log.level.web.es is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void fail_with_IAE_if_web_jmx_property_unsupported_level() { props.set("sonar.log.level.web.jmx", "ERROR"); assertThatThrownBy(() -> underTest.configure(props)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("log level ERROR in property sonar.log.level.web.jmx is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void configure_defines_hardcoded_levels() { LoggerContext context = underTest.configure(props); verifyImmutableLogLevels(context); } @Test public void configure_defines_hardcoded_levels_unchanged_by_global_property() { props.set("sonar.log.level", "TRACE"); LoggerContext context = underTest.configure(props); verifyImmutableLogLevels(context); } @Test public void configure_defines_hardcoded_levels_unchanged_by_ce_property() { props.set("sonar.log.level.ce", "TRACE"); LoggerContext context = underTest.configure(props); verifyImmutableLogLevels(context); } @Test public void configure_turns_off_some_Tomcat_loggers_if_global_log_level_is_not_set() { LoggerContext context = underTest.configure(props); verifyTomcatLoggersLogLevelsOff(context); } @Test public void configure_turns_off_some_Tomcat_loggers_if_global_log_level_is_INFO() { props.set("sonar.log.level", "INFO"); LoggerContext context = underTest.configure(props); verifyTomcatLoggersLogLevelsOff(context); } @Test public void configure_turns_off_some_Tomcat_loggers_if_global_log_level_is_DEBUG() { props.set("sonar.log.level", "DEBUG"); LoggerContext context = underTest.configure(props); verifyTomcatLoggersLogLevelsOff(context); } @Test public void configure_turns_off_some_Tomcat_loggers_if_global_log_level_is_TRACE() { props.set("sonar.log.level", "TRACE"); LoggerContext context = underTest.configure(props); assertThat(context.getLogger("org.apache.catalina.core.ContainerBase").getLevel()).isNull(); assertThat(context.getLogger("org.apache.catalina.core.StandardContext").getLevel()).isNull(); assertThat(context.getLogger("org.apache.catalina.core.StandardService").getLevel()).isNull(); } @Test public void configure_turns_off_some_MsSQL_driver_logger() { LoggerContext context = underTest.configure(props); Stream.of("com.microsoft.sqlserver.jdbc.internals", "com.microsoft.sqlserver.jdbc.ResultSet", "com.microsoft.sqlserver.jdbc.Statement", "com.microsoft.sqlserver.jdbc.Connection") .forEach(loggerName -> assertThat(context.getLogger(loggerName).getLevel()).isEqualTo(Level.OFF)); } @Test public void use_json_output() { props.set("sonar.log.jsonOutput", "true"); LoggerContext context = underTest.configure(props); Logger rootLogger = context.getLogger(ROOT_LOGGER_NAME); OutputStreamAppender appender = (OutputStreamAppender) rootLogger.getAppender("file_web"); Encoder<ILoggingEvent> encoder = appender.getEncoder(); assertThat(encoder).isInstanceOf(LayoutWrappingEncoder.class); assertThat(((LayoutWrappingEncoder) encoder).getLayout()).isInstanceOf(LogbackJsonLayout.class); } private void verifyRootLogLevel(LoggerContext ctx, Level expected) { Logger rootLogger = ctx.getLogger(ROOT_LOGGER_NAME); assertThat(rootLogger.getLevel()).isEqualTo(expected); } private void verifySqlLogLevel(LoggerContext ctx, Level expected) { assertThat(ctx.getLogger("sql").getLevel()).isEqualTo(expected); } private void verifyEsLogLevel(LoggerContext ctx, Level expected) { assertThat(ctx.getLogger("es").getLevel()).isEqualTo(expected); } private void verifyJmxLogLevel(LoggerContext ctx, Level expected) { assertThat(ctx.getLogger("javax.management.remote.timeout").getLevel()).isEqualTo(expected); assertThat(ctx.getLogger("javax.management.remote.misc").getLevel()).isEqualTo(expected); assertThat(ctx.getLogger("javax.management.remote.rmi").getLevel()).isEqualTo(expected); assertThat(ctx.getLogger("javax.management.mbeanserver").getLevel()).isEqualTo(expected); assertThat(ctx.getLogger("sun.rmi.loader").getLevel()).isEqualTo(expected); assertThat(ctx.getLogger("sun.rmi.transport.tcp").getLevel()).isEqualTo(expected); assertThat(ctx.getLogger("sun.rmi.transport.misc").getLevel()).isEqualTo(expected); assertThat(ctx.getLogger("sun.rmi.server.call").getLevel()).isEqualTo(expected); assertThat(ctx.getLogger("sun.rmi.dgc").getLevel()).isEqualTo(expected); } private void verifyImmutableLogLevels(LoggerContext ctx) { assertThat(ctx.getLogger("org.apache.ibatis").getLevel()).isEqualTo(Level.WARN); assertThat(ctx.getLogger("java.sql").getLevel()).isEqualTo(Level.WARN); assertThat(ctx.getLogger("java.sql.ResultSet").getLevel()).isEqualTo(Level.WARN); assertThat(ctx.getLogger("org.elasticsearch").getLevel()).isEqualTo(Level.INFO); assertThat(ctx.getLogger("org.elasticsearch.node").getLevel()).isEqualTo(Level.INFO); assertThat(ctx.getLogger("org.elasticsearch.http").getLevel()).isEqualTo(Level.INFO); assertThat(ctx.getLogger("ch.qos.logback").getLevel()).isEqualTo(Level.WARN); assertThat(ctx.getLogger("org.apache.catalina").getLevel()).isEqualTo(Level.INFO); assertThat(ctx.getLogger("org.apache.coyote").getLevel()).isEqualTo(Level.INFO); assertThat(ctx.getLogger("org.apache.jasper").getLevel()).isEqualTo(Level.INFO); assertThat(ctx.getLogger("org.apache.tomcat").getLevel()).isEqualTo(Level.INFO); } private void verifyTomcatLoggersLogLevelsOff(LoggerContext context) { assertThat(context.getLogger("org.apache.catalina.core.ContainerBase").getLevel()).isEqualTo(Level.OFF); assertThat(context.getLogger("org.apache.catalina.core.StandardContext").getLevel()).isEqualTo(Level.OFF); assertThat(context.getLogger("org.apache.catalina.core.StandardService").getLevel()).isEqualTo(Level.OFF); } public static class MemoryAppender extends AppenderBase<ILoggingEvent> { private static final List<ILoggingEvent> LOGS = new ArrayList<>(); @Override protected void append(ILoggingEvent eventObject) { LOGS.add(eventObject); } public List<ILoggingEvent> getLogs() { return ImmutableList.copyOf(LOGS); } public void clear() { LOGS.clear(); } } }
20,943
34.498305
140
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/ce/CeModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.ce; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class CeModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new CeModule().configure(container); assertThat(container.getAddedObjects()).hasSize(3); } }
1,243
34.542857
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/ce/http/CeHttpClientImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.ce.http; import java.io.File; import java.io.IOException; import java.util.Optional; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okio.Buffer; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.log.LoggerLevel; import org.sonar.process.ProcessEntryPoint; import org.sonar.process.ProcessId; import org.sonar.process.sharedmemoryfile.DefaultProcessCommands; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class CeHttpClientImplTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); @Rule public MockWebServer server = new MockWebServer(); private File ipcSharedDir; private CeHttpClient underTest; @Before public void setUp() throws Exception { ipcSharedDir = temp.newFolder(); MapSettings settings = new MapSettings(); settings.setProperty(ProcessEntryPoint.PROPERTY_SHARED_PATH, ipcSharedDir.getAbsolutePath()); underTest = new CeHttpClientImpl(settings.asConfig()); } @Test public void retrieveSystemInfo_returns_absent_if_process_is_down() { Optional<ProtobufSystemInfo.SystemInfo> info = underTest.retrieveSystemInfo(); assertThat(info).isEmpty(); } @Test public void retrieveSystemInfo_get_information_if_process_is_up() { Buffer response = new Buffer(); response.read(ProtobufSystemInfo.Section.newBuilder().build().toByteArray()); server.enqueue(new MockResponse().setBody(response)); // initialize registration of process setUpWithHttpUrl(ProcessId.COMPUTE_ENGINE); Optional<ProtobufSystemInfo.SystemInfo> info = underTest.retrieveSystemInfo(); assertThat(info.get().getSectionsCount()).isZero(); } @Test public void retrieveSystemInfo_throws_ISE_if_http_error() { server.enqueue(new MockResponse().setResponseCode(500)); // initialize registration of process setUpWithHttpUrl(ProcessId.COMPUTE_ENGINE); assertThatThrownBy(() -> underTest.retrieveSystemInfo()) .isInstanceOf(IllegalStateException.class) .hasMessage("Failed to call HTTP server of process " + ProcessId.COMPUTE_ENGINE) .hasRootCauseInstanceOf(IOException.class) .hasRootCauseMessage(format("Server returned HTTP response code: 500 for URL: http://%s:%d/systemInfo", server.getHostName(), server.getPort())); } @Test public void changeLogLevel_throws_NPE_if_level_argument_is_null() { assertThatThrownBy(() -> underTest.changeLogLevel(null)) .isInstanceOf(NullPointerException.class) .hasMessage("level can't be null"); } @Test public void changeLogLevel_throws_ISE_if_http_error() { String message = "blah"; server.enqueue(new MockResponse().setResponseCode(500).setBody(message)); // initialize registration of process setUpWithHttpUrl(ProcessId.COMPUTE_ENGINE); assertThatThrownBy(() -> underTest.changeLogLevel(LoggerLevel.DEBUG)) .isInstanceOf(IllegalStateException.class) .hasMessage("Failed to call HTTP server of process " + ProcessId.COMPUTE_ENGINE) .hasRootCauseInstanceOf(IOException.class) .hasRootCauseMessage(format("Failed to change log level in Compute Engine. Code was '500' and response was 'blah' for url " + "'http://%s:%s/changeLogLevel'", server.getHostName(), server.getPort())); } @Test public void changeLogLevel_does_not_fail_when_http_code_is_200() { server.enqueue(new MockResponse().setResponseCode(200)); setUpWithHttpUrl(ProcessId.COMPUTE_ENGINE); underTest.changeLogLevel(LoggerLevel.TRACE); } @Test public void changelogLevel_does_not_fail_if_process_is_down() { underTest.changeLogLevel(LoggerLevel.INFO); } private void setUpWithHttpUrl(ProcessId processId) { try (DefaultProcessCommands processCommands = DefaultProcessCommands.secondary(ipcSharedDir, processId.getIpcIndex())) { processCommands.setUp(); processCommands.setHttpUrl(format("http://%s:%d", server.getHostName(), server.getPort())); } } }
5,147
36.304348
151
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/es/IndexerStartupTaskAsyncTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.es; import com.google.common.collect.ImmutableSet; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; import org.sonar.server.es.metadata.MetadataIndex; import org.sonar.server.es.metadata.MetadataIndexImpl; import org.sonar.server.es.newindex.FakeIndexDefinition; import static org.mockito.ArgumentMatchers.anySet; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.sonar.server.es.newindex.FakeIndexDefinition.TYPE_FAKE; public class IndexerStartupTaskAsyncTest { @Rule public EsTester es = EsTester.createCustom(new FakeIndexDefinition()); private final MapSettings settings = new MapSettings(); private final MetadataIndex metadataIndex = mock(MetadataIndexImpl.class); private final StartupIndexer indexer = mock(StartupIndexer.class); private final IndexerStartupTask underTest = new IndexerStartupTask(es.client(), settings.asConfig(), metadataIndex, indexer); @Before public void setUp() { when(indexer.getType()).thenReturn(StartupIndexer.Type.ASYNCHRONOUS); doReturn(ImmutableSet.of(TYPE_FAKE)).when(indexer).getIndexTypes(); } @Test public void test(){ doReturn(false).when(metadataIndex).getInitialized(TYPE_FAKE); underTest.execute(); verify(indexer, times(1)).triggerAsyncIndexOnStartup(anySet()); } @Test public void set_initialized_after_indexation() { doReturn(false).when(metadataIndex).getInitialized(TYPE_FAKE); underTest.execute(); verify(metadataIndex).setInitialized(TYPE_FAKE, true); } @Test public void do_not_index_if_already_initialized() { doReturn(true).when(metadataIndex).getInitialized(TYPE_FAKE); underTest.execute(); verify(indexer).getIndexTypes(); verifyNoMoreInteractions(indexer); } @Test public void do_not_index_if_indexes_are_disabled() { settings.setProperty("sonar.internal.es.disableIndexes", "true"); es.putDocuments(TYPE_FAKE, new FakeDoc()); underTest.execute(); // do not index verifyNoMoreInteractions(indexer); } }
3,165
32.326316
128
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/es/IndexerStartupTaskTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.es; import com.google.common.collect.ImmutableSet; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito; import org.sonar.api.config.internal.MapSettings; import org.sonar.server.es.metadata.MetadataIndex; import org.sonar.server.es.metadata.MetadataIndexImpl; import org.sonar.server.es.newindex.FakeIndexDefinition; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.sonar.server.es.newindex.FakeIndexDefinition.TYPE_FAKE; public class IndexerStartupTaskTest { @Rule public EsTester es = EsTester.createCustom(new FakeIndexDefinition()); private final MapSettings settings = new MapSettings(); private final MetadataIndex metadataIndex = mock(MetadataIndexImpl.class); private final StartupIndexer indexer = mock(StartupIndexer.class); private final IndexerStartupTask underTest = new IndexerStartupTask(es.client(), settings.asConfig(), metadataIndex, indexer); @Before public void setUp() { when(indexer.getType()).thenReturn(StartupIndexer.Type.SYNCHRONOUS); doReturn(ImmutableSet.of(TYPE_FAKE)).when(indexer).getIndexTypes(); } @Test public void index_if_not_initialized() { doReturn(false).when(metadataIndex).getInitialized(TYPE_FAKE); underTest.execute(); verify(indexer).getIndexTypes(); verify(indexer).indexOnStartup(Mockito.eq(ImmutableSet.of(TYPE_FAKE))); } @Test public void set_initialized_after_indexation() { doReturn(false).when(metadataIndex).getInitialized(TYPE_FAKE); underTest.execute(); verify(metadataIndex).setInitialized(eq(TYPE_FAKE), eq(true)); } @Test public void do_not_index_if_already_initialized() { doReturn(true).when(metadataIndex).getInitialized(TYPE_FAKE); underTest.execute(); verify(indexer).getIndexTypes(); verifyNoMoreInteractions(indexer); } @Test public void do_not_index_if_indexes_are_disabled() { settings.setProperty("sonar.internal.es.disableIndexes", "true"); es.putDocuments(TYPE_FAKE, new FakeDoc()); underTest.execute(); // do not index verifyNoMoreInteractions(indexer); } }
3,216
32.510417
128
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/health/TestStandaloneHealthChecker.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.health; public class TestStandaloneHealthChecker implements HealthChecker { private Health health = Health.builder().setStatus(Health.Status.GREEN).build(); public void setHealth(Health h) { this.health = h; } @Override public Health checkNode() { return health; } @Override public ClusterHealth checkCluster() { throw new IllegalStateException(); } }
1,255
30.4
82
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/issue/index/AsyncIssueIndexingImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.issue.index; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.slf4j.event.Level; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.System2; import org.sonar.ce.queue.CeQueue; import org.sonar.ce.queue.CeTaskSubmit; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.core.util.UuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.ce.CeActivityDto; import org.sonar.db.ce.CeActivityDto.Status; import org.sonar.db.ce.CeQueueDto; import org.sonar.db.ce.CeTaskCharacteristicDto; import org.sonar.db.component.BranchDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.project.ProjectDto; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.db.ce.CeTaskCharacteristicDto.BRANCH_TYPE_KEY; import static org.sonar.db.ce.CeTaskTypes.BRANCH_ISSUE_SYNC; import static org.sonar.db.ce.CeTaskTypes.REPORT; import static org.sonar.db.component.BranchType.BRANCH; import static org.sonar.db.component.BranchType.PULL_REQUEST; import static org.sonar.db.component.SnapshotDto.STATUS_PROCESSED; public class AsyncIssueIndexingImplTest { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule public LogTester logTester = new LogTester(); private final DbClient dbClient = dbTester.getDbClient(); private final CeQueue ceQueue = mock(CeQueue.class); private final UuidFactory uuidFactory = new SequenceUuidFactory(); private final AsyncIssueIndexingImpl underTest = new AsyncIssueIndexingImpl(ceQueue, dbClient); @Before public void before() { when(ceQueue.prepareSubmit()).thenReturn(new CeTaskSubmit.Builder(uuidFactory.create())); } @Test public void triggerOnIndexCreation() { BranchDto dto = new BranchDto() .setBranchType(BRANCH) .setKey("branchName") .setUuid("branch_uuid") .setProjectUuid("project_uuid") .setIsMain(false); dbClient.branchDao().insert(dbTester.getSession(), dto); dbTester.commit(); underTest.triggerOnIndexCreation(); Optional<BranchDto> branch = dbClient.branchDao().selectByUuid(dbTester.getSession(), "branch_uuid"); assertThat(branch).isPresent(); assertThat(branch.get().isNeedIssueSync()).isTrue(); verify(ceQueue, times(1)).prepareSubmit(); verify(ceQueue, times(1)).massSubmit(anyCollection()); assertThat(logTester.logs(Level.INFO)) .contains("1 branch found in need of issue sync."); } @Test public void triggerForProject() { ProjectDto projectDto = dbTester.components().insertPrivateProject().getProjectDto(); BranchDto dto = new BranchDto() .setBranchType(BRANCH) .setKey("branchName") .setUuid("branch_uuid") .setProjectUuid(projectDto.getUuid()) .setIsMain(true); dbTester.components().insertProjectBranch(projectDto, dto); underTest.triggerForProject(projectDto.getUuid()); Optional<BranchDto> branch = dbClient.branchDao().selectByUuid(dbTester.getSession(), "branch_uuid"); assertThat(branch).isPresent(); assertThat(branch.get().isNeedIssueSync()).isTrue(); verify(ceQueue, times(2)).prepareSubmit(); verify(ceQueue, times(1)).massSubmit(anyCollection()); assertThat(logTester.logs(Level.INFO)) .contains("2 branch(es) found in need of issue sync for project."); } @Test public void triggerOnIndexCreation_no_branch() { underTest.triggerOnIndexCreation(); assertThat(logTester.logs(Level.INFO)).contains("0 branch found in need of issue sync."); } @Test public void triggerForProject_no_branch() { underTest.triggerForProject("some-random-uuid"); assertThat(logTester.logs(Level.INFO)).contains("0 branch(es) found in need of issue sync for project."); } @Test public void remove_existing_indexation_task() { String reportTaskUuid = persistReportTasks(); CeQueueDto task = new CeQueueDto(); task.setUuid("uuid_2"); task.setTaskType(BRANCH_ISSUE_SYNC); dbClient.ceQueueDao().insert(dbTester.getSession(), task); CeActivityDto activityDto = new CeActivityDto(task); activityDto.setStatus(Status.SUCCESS); dbClient.ceActivityDao().insert(dbTester.getSession(), activityDto); dbTester.commit(); underTest.triggerOnIndexCreation(); assertThat(dbClient.ceQueueDao().selectAllInAscOrder(dbTester.getSession())).extracting("uuid").containsExactly(reportTaskUuid); assertThat(dbClient.ceActivityDao().selectByTaskType(dbTester.getSession(), BRANCH_ISSUE_SYNC)).isEmpty(); assertThat(dbClient.ceActivityDao().selectByTaskType(dbTester.getSession(), REPORT)).hasSize(1); assertThat(dbClient.ceTaskCharacteristicsDao().selectByTaskUuids(dbTester.getSession(), new HashSet<>(List.of("uuid_2")))).isEmpty(); assertThat(logTester.logs(Level.INFO)) .contains( "1 pending indexation task found to be deleted...", "1 completed indexation task found to be deleted...", "Indexation task deletion complete.", "Deleting tasks characteristics...", "Tasks characteristics deletion complete."); } @Test public void remove_existing_indexation_for_project_task() { String reportTaskUuid = persistReportTasks(); ProjectDto projectDto = dbTester.components().insertPrivateProject().getProjectDto(); String branchUuid = "branch_uuid"; dbTester.components().insertProjectBranch(projectDto, b -> b.setBranchType(BRANCH).setUuid(branchUuid)); CeQueueDto mainBranchTask = new CeQueueDto().setUuid("uuid_2").setTaskType(BRANCH_ISSUE_SYNC) .setEntityUuid(projectDto.getUuid()).setComponentUuid(projectDto.getUuid()); dbClient.ceQueueDao().insert(dbTester.getSession(), mainBranchTask); CeQueueDto branchTask = new CeQueueDto().setUuid("uuid_3").setTaskType(BRANCH_ISSUE_SYNC) .setEntityUuid(projectDto.getUuid()).setComponentUuid(branchUuid); dbClient.ceQueueDao().insert(dbTester.getSession(), branchTask); ProjectDto anotherProjectDto = dbTester.components().insertPrivateProject().getProjectDto(); CeQueueDto taskOnAnotherProject = new CeQueueDto().setUuid("uuid_4").setTaskType(BRANCH_ISSUE_SYNC) .setEntityUuid(anotherProjectDto.getUuid()).setComponentUuid("another-branchUuid"); CeActivityDto canceledTaskOnAnotherProject = new CeActivityDto(taskOnAnotherProject).setStatus(Status.CANCELED); dbClient.ceActivityDao().insert(dbTester.getSession(), canceledTaskOnAnotherProject); dbTester.commit(); underTest.triggerForProject(projectDto.getUuid()); assertThat(dbClient.ceQueueDao().selectAllInAscOrder(dbTester.getSession())).extracting("uuid") .containsExactly(reportTaskUuid); assertThat(dbClient.ceActivityDao().selectByTaskType(dbTester.getSession(), REPORT)).hasSize(1); assertThat(dbClient.ceTaskCharacteristicsDao().selectByTaskUuids(dbTester.getSession(), new HashSet<>(List.of("uuid_2")))).isEmpty(); // verify that the canceled tasks on anotherProject is still here, and was not removed by the project reindexation assertThat(dbClient.ceActivityDao().selectByTaskType(dbTester.getSession(), BRANCH_ISSUE_SYNC)) .hasSize(1) .extracting(CeActivityDto::getEntityUuid) .containsExactly(anotherProjectDto.getUuid()); assertThat(logTester.logs(Level.INFO)) .contains( "2 pending indexation task found to be deleted...", "2 completed indexation task found to be deleted...", "Indexation task deletion complete.", "Deleting tasks characteristics...", "Tasks characteristics deletion complete.", "Tasks characteristics deletion complete.", "2 branch(es) found in need of issue sync for project."); } @Test public void order_by_last_analysis_date() { BranchDto dto = new BranchDto() .setBranchType(BRANCH) .setKey("branch_1") .setUuid("branch_uuid1") .setProjectUuid("project_uuid1") .setIsMain(false); dbClient.branchDao().insert(dbTester.getSession(), dto); dbTester.commit(); insertSnapshot("analysis_1", "project_uuid1", 1); BranchDto dto2 = new BranchDto() .setBranchType(BRANCH) .setKey("branch_2") .setUuid("branch_uuid2") .setProjectUuid("project_uuid2") .setIsMain(false); dbClient.branchDao().insert(dbTester.getSession(), dto2); dbTester.commit(); insertSnapshot("analysis_2", "project_uuid2", 2); underTest.triggerOnIndexCreation(); verify(ceQueue, times(2)).prepareSubmit(); ArgumentCaptor<Collection<CeTaskSubmit>> captor = ArgumentCaptor.forClass(Collection.class); verify(ceQueue, times(1)).massSubmit(captor.capture()); List<Collection<CeTaskSubmit>> captures = captor.getAllValues(); assertThat(captures).hasSize(1); Collection<CeTaskSubmit> tasks = captures.get(0); assertThat(tasks).hasSize(2); assertThat(tasks) .extracting(p -> p.getComponent().get().getUuid()) .containsExactly("branch_uuid2", "branch_uuid1"); assertThat(logTester.logs(Level.INFO)) .contains("2 projects found in need of issue sync."); } @Test public void characteristics_are_defined() { BranchDto dto = new BranchDto() .setBranchType(BRANCH) .setKey("branch_1") .setUuid("branch_uuid1") .setProjectUuid("project_uuid1") .setIsMain(false); dbClient.branchDao().insert(dbTester.getSession(), dto); dbTester.commit(); insertSnapshot("analysis_1", "project_uuid1", 1); BranchDto dto2 = new BranchDto() .setBranchType(PULL_REQUEST) .setKey("pr_1") .setUuid("pr_uuid_1") .setProjectUuid("project_uuid2") .setIsMain(false); dbClient.branchDao().insert(dbTester.getSession(), dto2); dbTester.commit(); insertSnapshot("analysis_2", "project_uuid2", 2); underTest.triggerOnIndexCreation(); ArgumentCaptor<Collection<CeTaskSubmit>> captor = ArgumentCaptor.forClass(Collection.class); verify(ceQueue, times(1)).massSubmit(captor.capture()); List<Collection<CeTaskSubmit>> captures = captor.getAllValues(); assertThat(captures).hasSize(1); Collection<CeTaskSubmit> tasks = captures.get(0); assertThat(tasks).hasSize(2); assertThat(tasks) .extracting(p -> p.getCharacteristics().get(BRANCH_TYPE_KEY), p -> p.getCharacteristics().get(CeTaskCharacteristicDto.BRANCH_KEY), p -> p.getCharacteristics().get(CeTaskCharacteristicDto.PULL_REQUEST)) .containsExactlyInAnyOrder( tuple("BRANCH", "branch_1", null), tuple("PULL_REQUEST", null, "pr_1")); } @Test public void verify_comparator_transitivity() { Map<String, SnapshotDto> map = new HashMap<>(); map.put("A", new SnapshotDto().setCreatedAt(1L)); map.put("B", new SnapshotDto().setCreatedAt(2L)); map.put("C", new SnapshotDto().setCreatedAt(-1L)); List<String> uuids = new ArrayList<>(map.keySet()); uuids.add("D"); Comparators.verifyTransitivity(AsyncIssueIndexingImpl.compareBySnapshot(map), uuids); } @Test public void trigger_with_lot_of_not_analyzed_project_should_not_raise_exception() { for (int i = 0; i < 100; i++) { BranchDto dto = new BranchDto() .setBranchType(BRANCH) .setKey("branch_" + i) .setUuid("branch_uuid" + i) .setProjectUuid("project_uuid" + i) .setIsMain(false); dbClient.branchDao().insert(dbTester.getSession(), dto); dbTester.commit(); insertSnapshot("analysis_" + i, "project_uuid" + i, 1); } for (int i = 100; i < 200; i++) { BranchDto dto = new BranchDto() .setBranchType(BRANCH) .setKey("branch_" + i) .setUuid("branch_uuid" + i) .setProjectUuid("project_uuid" + i) .setIsMain(false); dbClient.branchDao().insert(dbTester.getSession(), dto); dbTester.commit(); } assertThatCode(underTest::triggerOnIndexCreation).doesNotThrowAnyException(); } private SnapshotDto insertSnapshot(String analysisUuid, String projectUuid, long createdAt) { SnapshotDto snapshot = new SnapshotDto() .setUuid(analysisUuid) .setRootComponentUuid(projectUuid) .setStatus(STATUS_PROCESSED) .setCreatedAt(createdAt) .setLast(true); dbTester.getDbClient().snapshotDao().insert(dbTester.getSession(), snapshot); dbTester.commit(); return snapshot; } private String persistReportTasks() { CeQueueDto reportTask = new CeQueueDto(); reportTask.setUuid("uuid_1"); reportTask.setTaskType(REPORT); dbClient.ceQueueDao().insert(dbTester.getSession(), reportTask); CeActivityDto reportActivity = new CeActivityDto(reportTask); reportActivity.setStatus(Status.SUCCESS); dbClient.ceActivityDao().insert(dbTester.getSession(), reportActivity); return reportTask.getUuid(); } }
14,259
38.392265
137
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/issue/index/Comparators.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.issue.index; import java.util.Collection; import java.util.Comparator; public final class Comparators { /** * Prevent construction. */ private Comparators() { } /** * Verify that a comparator is transitive. * * @param <T> the type being compared * @param comparator the comparator to test * @param elements the elements to test against * @throws AssertionError if the comparator is not transitive */ public static <T> void verifyTransitivity(Comparator<T> comparator, Collection<T> elements) { for (T first : elements) { for (T second : elements) { int result1 = comparator.compare(first, second); int result2 = comparator.compare(second, first); if (result1 != -result2) { // Uncomment the following line to step through the failed case // comparator.compare(first, second); throw new AssertionError("compare(" + first + ", " + second + ") == " + result1 + " but swapping the parameters returns " + result2); } } } for (T first : elements) { for (T second : elements) { int firstGreaterThanSecond = comparator.compare(first, second); if (firstGreaterThanSecond <= 0) continue; for (T third : elements) { int secondGreaterThanThird = comparator.compare(second, third); if (secondGreaterThanThird <= 0) continue; int firstGreaterThanThird = comparator.compare(first, third); if (firstGreaterThanThird <= 0) { throw new AssertionError("compare(" + first + ", " + second + ") > 0, " + "compare(" + second + ", " + third + ") > 0, but compare(" + first + ", " + third + ") == " + firstGreaterThanThird); } } } } } }
2,691
34.893333
107
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/notification/NotificationChannelTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.notification; import org.junit.Test; import org.sonar.api.notifications.Notification; import org.sonar.api.notifications.NotificationChannel; import static org.assertj.core.api.Assertions.assertThat; public class NotificationChannelTest { @Test public void defaultMethods() { NotificationChannel channel = new FakeNotificationChannel(); assertThat(channel.getKey()).isEqualTo("FakeNotificationChannel"); assertThat(channel).hasToString("FakeNotificationChannel"); } private static class FakeNotificationChannel extends NotificationChannel { @Override public boolean deliver(Notification notification, String username) { return true; } } }
1,553
33.533333
76
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/notification/NotificationDaemonTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.notification; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import org.mockito.verification.Timeout; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.notifications.Notification; import org.sonar.api.utils.System2; import static java.util.Collections.singleton; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class NotificationDaemonTest { private DefaultNotificationManager manager = mock(DefaultNotificationManager.class); private NotificationService notificationService = mock(NotificationService.class); private NotificationDaemon underTest; private InOrder inOrder; @Before public void setUp() { MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, NotificationDaemon.class)).setProperty("sonar.notifications.delay", 1L); underTest = new NotificationDaemon(settings.asConfig(), manager, notificationService); inOrder = Mockito.inOrder(notificationService); } @After public void tearDown() { underTest.stop(); } @Test public void no_effect_when_no_notification() { when(manager.getFromQueue()).thenReturn(null); underTest.start(); inOrder.verify(notificationService, new Timeout(2000, Mockito.times(0))).deliverEmails(anyCollection()); inOrder.verifyNoMoreInteractions(); underTest.stop(); } @Test public void calls_both_api_and_deprecated_API() { Notification notification = mock(Notification.class); when(manager.getFromQueue()).thenReturn(notification).thenReturn(null); underTest.start(); verify(notificationService, timeout(2000)).deliver(notification); inOrder.verify(notificationService).deliverEmails(singleton(notification)); inOrder.verify(notificationService).deliver(notification); inOrder.verifyNoMoreInteractions(); underTest.stop(); } @Test public void notifications_are_processed_one_by_one_even_with_new_API() { Notification notification1 = mock(Notification.class); Notification notification2 = mock(Notification.class); Notification notification3 = mock(Notification.class); Notification notification4 = mock(Notification.class); when(manager.getFromQueue()) .thenReturn(notification1) .thenReturn(notification2) .thenReturn(notification3) .thenReturn(notification4) .thenReturn(null); underTest.start(); verify(notificationService, timeout(2000)).deliver(notification1); inOrder.verify(notificationService).deliverEmails(singleton(notification1)); inOrder.verify(notificationService).deliver(notification1); inOrder.verify(notificationService).deliverEmails(singleton(notification2)); inOrder.verify(notificationService).deliver(notification2); inOrder.verify(notificationService).deliverEmails(singleton(notification3)); inOrder.verify(notificationService).deliver(notification3); inOrder.verify(notificationService).deliverEmails(singleton(notification4)); inOrder.verify(notificationService).deliver(notification4); inOrder.verifyNoMoreInteractions(); underTest.stop(); } }
4,251
36.964286
157
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/notification/NotificationMediumTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.notification; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.config.internal.Settings; import org.sonar.api.notifications.Notification; import org.sonar.api.notifications.NotificationChannel; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class NotificationMediumTest { private static String CREATOR_SIMON = "simon"; private static String CREATOR_EVGENY = "evgeny"; private static String ASSIGNEE_SIMON = "simon"; private DefaultNotificationManager manager = mock(DefaultNotificationManager.class); private Notification notification = mock(Notification.class); private NotificationChannel emailChannel = mock(NotificationChannel.class); private NotificationChannel gtalkChannel = mock(NotificationChannel.class); private NotificationDispatcher commentOnIssueAssignedToMe = mock(NotificationDispatcher.class); private NotificationDispatcher commentOnIssueCreatedByMe = mock(NotificationDispatcher.class); private NotificationDispatcher qualityGateChange = mock(NotificationDispatcher.class); private DbClient dbClient = mock(DbClient.class); private NotificationService service = new NotificationService(dbClient, new NotificationDispatcher[] {commentOnIssueAssignedToMe, commentOnIssueCreatedByMe, qualityGateChange}); private NotificationDaemon underTest = null; private void setUpMocks() { when(emailChannel.getKey()).thenReturn("email"); when(gtalkChannel.getKey()).thenReturn("gtalk"); when(commentOnIssueAssignedToMe.getKey()).thenReturn("CommentOnIssueAssignedToMe"); when(commentOnIssueAssignedToMe.getType()).thenReturn("issue-changes"); when(commentOnIssueCreatedByMe.getKey()).thenReturn("CommentOnIssueCreatedByMe"); when(commentOnIssueCreatedByMe.getType()).thenReturn("issue-changes"); when(qualityGateChange.getKey()).thenReturn("QGateChange"); when(qualityGateChange.getType()).thenReturn("qgate-changes"); when(manager.getFromQueue()).thenReturn(notification).thenReturn(null); MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, NotificationDaemon.class)).setProperty("sonar.notifications.delay", 1L); underTest = new NotificationDaemon(settings.asConfig(), manager, service); } /** * Given: * Simon wants to receive notifications by email on comments for reviews assigned to him or created by him. * <p/> * When: * Freddy adds comment to review created by Simon and assigned to Simon. * <p/> * Then: * Only one notification should be delivered to Simon by Email. */ @Test public void scenario1() { setUpMocks(); doAnswer(addUser(ASSIGNEE_SIMON, emailChannel)).when(commentOnIssueAssignedToMe).performDispatch(same(notification), any(NotificationDispatcher.Context.class)); doAnswer(addUser(CREATOR_SIMON, emailChannel)).when(commentOnIssueCreatedByMe).performDispatch(same(notification), any(NotificationDispatcher.Context.class)); underTest.start(); verify(emailChannel, timeout(2000)).deliver(notification, ASSIGNEE_SIMON); underTest.stop(); verify(gtalkChannel, never()).deliver(notification, ASSIGNEE_SIMON); } /** * Given: * Evgeny wants to receive notification by GTalk on comments for reviews created by him. * Simon wants to receive notification by Email on comments for reviews assigned to him. * <p/> * When: * Freddy adds comment to review created by Evgeny and assigned to Simon. * <p/> * Then: * Two notifications should be delivered - one to Simon by Email and another to Evgeny by GTalk. */ @Test public void scenario2() { setUpMocks(); doAnswer(addUser(ASSIGNEE_SIMON, emailChannel)).when(commentOnIssueAssignedToMe).performDispatch(same(notification), any(NotificationDispatcher.Context.class)); doAnswer(addUser(CREATOR_EVGENY, gtalkChannel)).when(commentOnIssueCreatedByMe).performDispatch(same(notification), any(NotificationDispatcher.Context.class)); underTest.start(); verify(emailChannel, timeout(2000)).deliver(notification, ASSIGNEE_SIMON); verify(gtalkChannel, timeout(2000)).deliver(notification, CREATOR_EVGENY); underTest.stop(); verify(emailChannel, never()).deliver(notification, CREATOR_EVGENY); verify(gtalkChannel, never()).deliver(notification, ASSIGNEE_SIMON); } /** * Given: * Simon wants to receive notifications by Email and GTLak on comments for reviews assigned to him. * <p/> * When: * Freddy adds comment to review created by Evgeny and assigned to Simon. * <p/> * Then: * Two notifications should be delivered to Simon - one by Email and another by GTalk. */ @Test public void scenario3() { setUpMocks(); doAnswer(addUser(ASSIGNEE_SIMON, new NotificationChannel[]{emailChannel, gtalkChannel})) .when(commentOnIssueAssignedToMe).performDispatch(same(notification), any(NotificationDispatcher.Context.class)); underTest.start(); verify(emailChannel, timeout(2000)).deliver(notification, ASSIGNEE_SIMON); verify(gtalkChannel, timeout(2000)).deliver(notification, ASSIGNEE_SIMON); underTest.stop(); verify(emailChannel, never()).deliver(notification, CREATOR_EVGENY); verify(gtalkChannel, never()).deliver(notification, CREATOR_EVGENY); } /** * Given: * Nobody wants to receive notifications. * <p/> * When: * Freddy adds comment to review created by Evgeny and assigned to Simon. * <p/> * Then: * No notifications. */ @Test public void scenario4() { setUpMocks(); underTest.start(); underTest.stop(); verify(emailChannel, never()).deliver(any(Notification.class), anyString()); verify(gtalkChannel, never()).deliver(any(Notification.class), anyString()); } // SONAR-4548 @Test public void shouldNotStopWhenException() { setUpMocks(); when(manager.getFromQueue()).thenThrow(new RuntimeException("Unexpected exception")).thenReturn(notification).thenReturn(null); doAnswer(addUser(ASSIGNEE_SIMON, emailChannel)).when(commentOnIssueAssignedToMe).performDispatch(same(notification), any(NotificationDispatcher.Context.class)); doAnswer(addUser(CREATOR_SIMON, emailChannel)).when(commentOnIssueCreatedByMe).performDispatch(same(notification), any(NotificationDispatcher.Context.class)); underTest.start(); verify(emailChannel, timeout(2000)).deliver(notification, ASSIGNEE_SIMON); underTest.stop(); verify(gtalkChannel, never()).deliver(notification, ASSIGNEE_SIMON); } @Test public void shouldNotAddNullAsUser() { setUpMocks(); doAnswer(addUser(null, gtalkChannel)).when(commentOnIssueCreatedByMe).performDispatch(same(notification), any(NotificationDispatcher.Context.class)); underTest.start(); underTest.stop(); verify(emailChannel, never()).deliver(any(Notification.class), anyString()); verify(gtalkChannel, never()).deliver(any(Notification.class), anyString()); } @Test public void getDispatchers() { setUpMocks(); assertThat(service.getDispatchers()).containsOnly(commentOnIssueAssignedToMe, commentOnIssueCreatedByMe, qualityGateChange); } @Test public void getDispatchers_empty() { Settings settings = new MapSettings().setProperty("sonar.notifications.delay", 1L); service = new NotificationService(dbClient); assertThat(service.getDispatchers()).isEmpty(); } @Test public void shouldLogEvery10Minutes() { setUpMocks(); // Emulate 2 notifications in DB when(manager.getFromQueue()).thenReturn(notification).thenReturn(notification).thenReturn(null); when(manager.count()).thenReturn(1L).thenReturn(0L); underTest = spy(underTest); // Emulate processing of each notification take 10 min to have a log each time when(underTest.now()).thenReturn(0L).thenReturn(10 * 60 * 1000 + 1L).thenReturn(20 * 60 * 1000 + 2L); underTest.start(); verify(underTest, timeout(200)).log(0, 1, 10); verify(underTest, timeout(200)).log(0, 0, 20); underTest.stop(); } private static Answer<Object> addUser(final String user, final NotificationChannel channel) { return addUser(user, new NotificationChannel[] {channel}); } private static Answer<Object> addUser(final String user, final NotificationChannel[] channels) { return new Answer<Object>() { public Object answer(InvocationOnMock invocation) { for (NotificationChannel channel : channels) { ((NotificationDispatcher.Context) invocation.getArguments()[1]).addUser(user, channel); } return null; } }; } }
10,095
40.377049
179
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/notification/NotificationModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.notification; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class NotificationModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new NotificationModule().configure(container); assertThat(container.getAddedObjects()).hasSize(5); } }
1,273
35.4
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/notification/NotificationTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.notification; import org.junit.Before; import org.junit.Test; import org.sonar.api.notifications.Notification; import static org.assertj.core.api.Assertions.assertThat; public class NotificationTest { private Notification notification; @Before public void init() { notification = new Notification("alerts").setDefaultMessage("There are new alerts").setFieldValue("alertCount", "42"); } @Test public void shouldReturnType() { assertThat(notification.getType()).isEqualTo("alerts"); } @Test public void shouldReturnDefaultMessage() { assertThat(notification.getDefaultMessage()).isEqualTo("There are new alerts"); } @Test public void shouldReturnToStringIfDefaultMessageNotSet() { notification = new Notification("alerts").setFieldValue("alertCount", "42"); System.out.println(notification); assertThat(notification.getDefaultMessage()).contains("type='alerts'"); assertThat(notification.getDefaultMessage()).contains("fields={alertCount=42}"); } @Test public void shouldReturnField() { assertThat(notification.getFieldValue("alertCount")).isEqualTo("42"); assertThat(notification.getFieldValue("fake")).isNull(); // default message is stored as field as well assertThat(notification.getFieldValue("default_message")).isEqualTo("There are new alerts"); } @Test public void shouldEqual() { assertThat(notification.equals("")).isFalse(); assertThat(notification.equals(null)).isFalse(); assertThat(notification.equals(notification)).isTrue(); Notification otherNotif = new Notification("alerts").setDefaultMessage("There are new alerts").setFieldValue("alertCount", "42"); assertThat(otherNotif).isEqualTo(notification); otherNotif = new Notification("alerts").setDefaultMessage("There are new alerts").setFieldValue("alertCount", "15000"); assertThat(otherNotif).isNotEqualTo(notification); } }
2,784
34.705128
133
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/ClusterSystemInfoWriterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform; import java.io.StringWriter; import java.util.Collections; import org.junit.Before; import org.junit.Test; import org.sonar.api.utils.text.JsonWriter; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo.Attribute; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo.Section; import org.sonar.server.health.ClusterHealth; import org.sonar.server.health.Health; import org.sonar.server.health.HealthChecker; import org.sonar.server.platform.monitoring.cluster.AppNodesInfoLoader; import org.sonar.server.platform.monitoring.cluster.GlobalInfoLoader; import org.sonar.server.platform.monitoring.cluster.NodeInfo; import org.sonar.server.platform.monitoring.cluster.SearchNodesInfoLoader; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ClusterSystemInfoWriterTest { private final GlobalInfoLoader globalInfoLoader = mock(GlobalInfoLoader.class); private final AppNodesInfoLoader appNodesInfoLoader = mock(AppNodesInfoLoader.class); private final SearchNodesInfoLoader searchNodesInfoLoader = mock(SearchNodesInfoLoader.class); private final HealthChecker healthChecker = mock(HealthChecker.class); private final ClusterSystemInfoWriter underTest = new ClusterSystemInfoWriter(globalInfoLoader, appNodesInfoLoader, searchNodesInfoLoader, healthChecker); @Before public void before() throws InterruptedException { when(globalInfoLoader.load()).thenReturn(Collections.singletonList(createSection("globalInfo"))); when(appNodesInfoLoader.load()).thenReturn(Collections.singletonList(createNodeInfo("appNodes"))); when(searchNodesInfoLoader.load()).thenReturn(Collections.singletonList(createNodeInfo("searchNodes"))); Health health = Health.builder().setStatus(Health.Status.GREEN).build(); when(healthChecker.checkCluster()).thenReturn(new ClusterHealth(health, Collections.emptySet())); } @Test public void writeInfo() throws InterruptedException { StringWriter writer = new StringWriter(); JsonWriter jsonWriter = JsonWriter.of(writer); jsonWriter.beginObject(); underTest.write(jsonWriter); jsonWriter.endObject(); assertThat(writer).hasToString("{\"Health\":\"GREEN\"," + "\"Health Causes\":[],\"\":{\"name\":\"globalInfo\"}," + "\"Application Nodes\":[{\"Name\":\"appNodes\",\"\":{\"name\":\"appNodes\"}}]," + "\"Search Nodes\":[{\"Name\":\"searchNodes\",\"\":{\"name\":\"searchNodes\"}}]}"); } private static NodeInfo createNodeInfo(String name) { NodeInfo info = new NodeInfo(name); info.addSection(createSection(name)); return info; } private static Section createSection(String name) { return Section.newBuilder() .addAttributes(Attribute.newBuilder().setKey("name").setStringValue(name).build()) .build(); } }
3,751
43.666667
117
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/ClusterVerificationTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform; import org.junit.Test; import org.sonar.api.utils.MessageException; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ClusterVerificationTest { private static final String ERROR_MESSAGE = "Cluster mode can't be enabled. Please install the Data Center Edition. More details at https://www.sonarsource.com/plans-and-pricing/data-center/."; private NodeInformation nodeInformation = mock(NodeInformation.class); private ClusterFeature feature = mock(ClusterFeature.class); @Test public void throw_MessageException_if_cluster_is_enabled_but_HA_plugin_is_not_installed() { when(nodeInformation.isStandalone()).thenReturn(false); ClusterVerification underTest = new ClusterVerification(nodeInformation); assertThatThrownBy(underTest::start) .isInstanceOf(MessageException.class) .hasMessage(ERROR_MESSAGE); } @Test public void throw_MessageException_if_cluster_is_enabled_but_HA_feature_is_not_enabled() { when(nodeInformation.isStandalone()).thenReturn(false); when(feature.isEnabled()).thenReturn(false); ClusterVerification underTest = new ClusterVerification(nodeInformation, feature); assertThatThrownBy(underTest::start) .isInstanceOf(MessageException.class) .hasMessage(ERROR_MESSAGE); } @Test public void do_not_fail_if_cluster_is_enabled_and_HA_feature_is_enabled() { when(nodeInformation.isStandalone()).thenReturn(false); when(feature.isEnabled()).thenReturn(true); ClusterVerification underTest = new ClusterVerification(nodeInformation, feature); // no failure underTest.start(); underTest.stop(); } @Test public void do_not_fail_if_cluster_is_disabled() { when(nodeInformation.isStandalone()).thenReturn(true); ClusterVerification underTest = new ClusterVerification(nodeInformation); // no failure underTest.start(); underTest.stop(); } }
2,879
33.698795
195
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/ContainerSupportImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform; import java.util.Arrays; import java.util.Collection; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.sonar.api.utils.System2; import org.sonar.server.util.Paths2; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; @RunWith(Parameterized.class) public class ContainerSupportImplTest { private static final String CONTAINER_FILE_PATH = "/run/.containerenv"; private static final String[] MOUNT_GREP_COMMAND = {"bash", "-c", "mount | grep 'overlay on /'"}; private static final String[] CAT_COMMAND = {"bash", "-c", "cat /run/.containerenv"}; private static final String DOCKER = "docker"; private static final String PODMAN = "podman"; private static final String BUILDAH = "buildah"; private static final String CONTAINER_D = "containerd"; private static final String GENERAL_CONTAINER = "general_container"; private final Paths2 paths2 = mock(Paths2.class); private final System2 system2 = mock(System2.class); private ContainerSupportImpl underTest = new ContainerSupportImpl(paths2, system2); private String containerContext; public ContainerSupportImplTest(String containerContext) { this.containerContext = containerContext; } @Before public void setUp() { if (containerContext == null) { return; } switch (containerContext) { case DOCKER -> { underTest = spy(underTest); when(underTest.executeCommand(MOUNT_GREP_COMMAND)).thenReturn("/docker"); when(paths2.exists("/.dockerenv")).thenReturn(true); } case PODMAN -> { when(system2.envVariable("container")).thenReturn("podman"); when(paths2.exists(CONTAINER_FILE_PATH)).thenReturn(true); } case BUILDAH -> { underTest = spy(underTest); when(paths2.exists(CONTAINER_FILE_PATH)).thenReturn(true); when(underTest.executeCommand(CAT_COMMAND)).thenReturn("XXX engine=\"buildah- XXX"); } case CONTAINER_D -> { underTest = spy(underTest); when(underTest.executeCommand(MOUNT_GREP_COMMAND)).thenReturn("/containerd"); } case GENERAL_CONTAINER -> when(paths2.exists(CONTAINER_FILE_PATH)).thenReturn(true); default -> { } } underTest.populateCache(); } @Parameterized.Parameters public static Collection<String> data() { return Arrays.asList(DOCKER, PODMAN, BUILDAH, CONTAINER_D, GENERAL_CONTAINER, null); } @Test public void testGetContainerContext() { Assert.assertEquals(containerContext, underTest.getContainerContext()); } @Test public void testIsRunningInContainer() { boolean expected = containerContext != null; when(paths2.exists(CONTAINER_FILE_PATH)).thenReturn(expected); Assert.assertEquals(expected, underTest.isRunningInContainer()); } }
3,812
34.635514
99
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/DatabaseServerCompatibilityTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform; import java.util.Optional; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.MessageException; import org.sonar.server.platform.db.migration.version.DatabaseVersion; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DatabaseServerCompatibilityTest { @Rule public LogTester logTester = new LogTester(); @Test public void fail_if_requires_downgrade() { DatabaseVersion version = mock(DatabaseVersion.class); when(version.getStatus()).thenReturn(DatabaseVersion.Status.REQUIRES_DOWNGRADE); var compatibility = new DatabaseServerCompatibility(version); assertThatThrownBy(compatibility::start) .isInstanceOf(MessageException.class) .hasMessage("Database was upgraded to a more recent version of SonarQube. " + "A backup must probably be restored or the DB settings are incorrect."); } @Test public void fail_if_requires_firstly_to_upgrade_to_lts() { DatabaseVersion version = mock(DatabaseVersion.class); when(version.getStatus()).thenReturn(DatabaseVersion.Status.REQUIRES_UPGRADE); when(version.getVersion()).thenReturn(Optional.of(12L)); var compatibility = new DatabaseServerCompatibility(version); assertThatThrownBy(compatibility::start) .isInstanceOf(MessageException.class) .hasMessage("The version of SonarQube is too old. Please upgrade to the Long Term Support version first."); } @Test public void log_warning_if_requires_upgrade() { DatabaseVersion version = mock(DatabaseVersion.class); when(version.getStatus()).thenReturn(DatabaseVersion.Status.REQUIRES_UPGRADE); when(version.getVersion()).thenReturn(Optional.of(DatabaseVersion.MIN_UPGRADE_VERSION)); new DatabaseServerCompatibility(version).start(); assertThat(logTester.logs()).hasSize(4); assertThat(logTester.logs(Level.WARN)).contains( "The database must be manually upgraded. Please backup the database and browse /setup. " + "For more information: https://docs.sonarqube.org/latest/setup/upgrading", "################################################################################", "The database must be manually upgraded. Please backup the database and browse /setup. " + "For more information: https://docs.sonarqube.org/latest/setup/upgrading", "################################################################################"); } @Test public void do_nothing_if_up_to_date() { DatabaseVersion version = mock(DatabaseVersion.class); when(version.getStatus()).thenReturn(DatabaseVersion.Status.UP_TO_DATE); new DatabaseServerCompatibility(version).start(); // no error } }
3,781
42.471264
113
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/DefaultServerUpgradeStatusTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.sonar.api.config.internal.ConfigurationBridge; import org.sonar.api.config.internal.MapSettings; import org.sonar.server.platform.db.migration.step.MigrationSteps; import org.sonar.server.platform.db.migration.version.DatabaseVersion; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DefaultServerUpgradeStatusTest { private static final long LAST_VERSION = 150; private MigrationSteps migrationSteps = mock(MigrationSteps.class); private DatabaseVersion dbVersion = mock(DatabaseVersion.class); private MapSettings settings = new MapSettings(); private DefaultServerUpgradeStatus underTest = new DefaultServerUpgradeStatus(dbVersion, migrationSteps, new ConfigurationBridge(settings)); @Before public void setUp() { when(migrationSteps.getMaxMigrationNumber()).thenReturn(LAST_VERSION); } @Test public void shouldBeFreshInstallation() { when(migrationSteps.getMaxMigrationNumber()).thenReturn(150L); when(dbVersion.getVersion()).thenReturn(Optional.empty()); underTest.start(); assertThat(underTest.isFreshInstall()).isTrue(); assertThat(underTest.isUpgraded()).isFalse(); assertThat(underTest.getInitialDbVersion()).isEqualTo(-1); } @Test public void shouldBeUpgraded() { when(dbVersion.getVersion()).thenReturn(Optional.of(50L)); underTest.start(); assertThat(underTest.isFreshInstall()).isFalse(); assertThat(underTest.isUpgraded()).isTrue(); assertThat(underTest.getInitialDbVersion()).isEqualTo(50); } @Test public void shouldNotBeUpgraded() { when(dbVersion.getVersion()).thenReturn(Optional.of(LAST_VERSION)); underTest.start(); assertThat(underTest.isFreshInstall()).isFalse(); assertThat(underTest.isUpgraded()).isFalse(); assertThat(underTest.getInitialDbVersion()).isEqualTo((int) LAST_VERSION); } @Test public void isAutoDbUpgrade() { settings.clear(); assertThat(underTest.isAutoDbUpgrade()).isFalse(); settings.setProperty("sonar.autoDatabaseUpgrade", true); assertThat(underTest.isAutoDbUpgrade()).isTrue(); settings.setProperty("sonar.autoDatabaseUpgrade", false); assertThat(underTest.isAutoDbUpgrade()).isFalse(); } }
3,251
34.347826
142
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/StandaloneSystemInfoWriterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform; import java.io.StringWriter; import java.util.Optional; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito; import org.sonar.api.utils.text.JsonWriter; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.ce.http.CeHttpClient; import org.sonar.server.ce.http.CeHttpClientImpl; import org.sonar.server.health.TestStandaloneHealthChecker; import org.sonar.server.tester.UserSessionRule; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.process.systeminfo.SystemInfoUtils.setAttribute; public class StandaloneSystemInfoWriterTest { @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone() .logIn("login") .setName("name"); private final SystemInfoSection section1 = mock(SystemInfoSection.class); private final SystemInfoSection section2 = mock(SystemInfoSection.class); private final CeHttpClient ceHttpClient = mock(CeHttpClientImpl.class, Mockito.RETURNS_MOCKS); private final TestStandaloneHealthChecker healthChecker = new TestStandaloneHealthChecker(); private final StandaloneSystemInfoWriter underTest = new StandaloneSystemInfoWriter(ceHttpClient, healthChecker, section1, section2); @Test public void write_json() { logInAsSystemAdministrator(); ProtobufSystemInfo.Section.Builder attributes1 = ProtobufSystemInfo.Section.newBuilder() .setName("Section One"); setAttribute(attributes1, "foo", "bar"); when(section1.toProtobuf()).thenReturn(attributes1.build()); ProtobufSystemInfo.Section.Builder attributes2 = ProtobufSystemInfo.Section.newBuilder() .setName("Section Two"); setAttribute(attributes2, "one", 1); setAttribute(attributes2, "two", 2); when(section2.toProtobuf()).thenReturn(attributes2.build()); when(ceHttpClient.retrieveSystemInfo()).thenReturn(Optional.empty()); StringWriter writer = new StringWriter(); JsonWriter jsonWriter = JsonWriter.of(writer); jsonWriter.beginObject(); underTest.write(jsonWriter); jsonWriter.endObject(); // response does not contain empty "Section Three" assertThat(writer).hasToString("{\"Health\":\"GREEN\",\"Health Causes\":[],\"Section One\":{\"foo\":\"bar\"},\"Section Two\":{\"one\":1,\"two\":2}}"); } private void logInAsSystemAdministrator() { userSessionRule.logIn().setSystemAdministrator(); } }
3,402
41.012346
154
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/StatisticsSupportTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform; import org.junit.Test; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class StatisticsSupportTest { private final DbClient dbClient = mock(DbClient.class, RETURNS_DEEP_STUBS); private final StatisticsSupport statisticsSupport = new StatisticsSupport(dbClient); @Test public void should_return_metric_from_liveMeasureDao() { when(dbClient.projectDao().getNclocSum(any(DbSession.class))).thenReturn(1800999L); long linesOfCode = statisticsSupport.getLinesOfCode(); assertThat(linesOfCode).isEqualTo(1800999L); } }
1,680
35.543478
87
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/SystemInfoWriterModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class SystemInfoWriterModuleTest { private final NodeInformation nodeInformation = mock(NodeInformation.class); private final SystemInfoWriterModule underTest = new SystemInfoWriterModule(nodeInformation); @Test public void verify_system_info_configuration_in_cluster_mode() { when(nodeInformation.isStandalone()).thenReturn(false); ListContainer container = new ListContainer(); underTest.configure(container); assertThat(container.getAddedObjects()).hasSize(22); } @Test public void verify_system_info_configuration_in_standalone_mode() { when(nodeInformation.isStandalone()).thenReturn(true); ListContainer container = new ListContainer(); underTest.configure(container); assertThat(container.getAddedObjects()).hasSize(16); } }
1,878
36.58
95
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/WebCoreExtensionsInstallerTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.stream.Stream; import org.junit.Test; import org.sonar.api.SonarRuntime; import org.sonar.api.batch.ScannerSide; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; import org.sonar.core.extension.CoreExtension; import org.sonar.core.extension.CoreExtensionRepository; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.core.extension.CoreExtensionsInstaller.noAdditionalSideFilter; import static org.sonar.core.extension.CoreExtensionsInstaller.noExtensionFilter; public class WebCoreExtensionsInstallerTest { private final SonarRuntime sonarRuntime = mock(SonarRuntime.class); private final CoreExtensionRepository coreExtensionRepository = mock(CoreExtensionRepository.class); private final WebCoreExtensionsInstaller underTest = new WebCoreExtensionsInstaller(sonarRuntime, coreExtensionRepository); @Test public void install_only_adds_ServerSide_annotated_extension_to_container() { when(coreExtensionRepository.loadedCoreExtensions()).thenReturn(Stream.of( new CoreExtension() { @Override public String getName() { return "foo"; } @Override public void load(Context context) { context.addExtensions(CeClass.class, ScannerClass.class, WebServerClass.class, NoAnnotationClass.class, OtherAnnotationClass.class, MultipleAnnotationClass.class); } })); ListContainer container = new ListContainer(); underTest.install(container, noExtensionFilter(), noAdditionalSideFilter()); assertThat(container.getAddedObjects()).containsOnly(WebServerClass.class, MultipleAnnotationClass.class); } @ComputeEngineSide public static final class CeClass { } @ServerSide public static final class WebServerClass { } @ScannerSide public static final class ScannerClass { } @ServerSide @ComputeEngineSide @ScannerSide public static final class MultipleAnnotationClass { } public static final class NoAnnotationClass { } @DarkSide public static final class OtherAnnotationClass { } @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface DarkSide { } }
3,443
31.186916
125
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/db/CheckAnyonePermissionsAtStartupTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.db; import java.util.stream.IntStream; import org.junit.After; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.System2; import org.sonar.api.utils.log.LoggerLevel; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.GroupDto; import static org.assertj.core.api.Assertions.assertThat; public class CheckAnyonePermissionsAtStartupTest { @ClassRule public static LogTester logTester = new LogTester().setLevel(LoggerLevel.WARN); @Rule public final DbTester dbTester = DbTester.create(System2.INSTANCE); private final DbClient dbClient = dbTester.getDbClient(); private final MapSettings settings = new MapSettings(); private final CheckAnyonePermissionsAtStartup underTest = new CheckAnyonePermissionsAtStartup(dbClient, settings.asConfig()); @After public void tearDown() { logTester.clear(); underTest.stop(); } @Test public void force_auth_false_anyone_global_permissions() { setForceAuthentication(false); dbTester.users().insertPermissionOnAnyone("perm-anyone"); createPublicProjects(3, false); assertGlobalLevelAnyonePermissionWarningInLogs(); assertProjectLevelAnyonePermissionWarningNotInLogs(); } @Test public void force_auth_false_project_level_anyone_permissions_exactly_three() { setForceAuthentication(false); createPublicProjects(3, true); assertGlobalLevelAnyonePermissionWarningNotInLogs(); assertProjectLevelAnyonePermissionWarningInLogs(3, "key-1", "key-2", "key-3"); } @Test public void force_auth_false_project_level_anyone_permissions_less_than_three() { setForceAuthentication(false); createPublicProjects(1, true); assertGlobalLevelAnyonePermissionWarningNotInLogs(); assertProjectLevelAnyonePermissionWarningInLogs(1, "key-1"); } @Test public void force_auth_false_project_level_anyone_permissions_more_than_three() { setForceAuthentication(false); createPublicProjects(9, true); assertGlobalLevelAnyonePermissionWarningNotInLogs(); assertProjectLevelAnyonePermissionWarningInLogs(9, "key-1", "key-2", "key-3"); } @Test public void force_auth_false_no_projects() { setForceAuthentication(false); assertGlobalLevelAnyonePermissionWarningNotInLogs(); assertProjectLevelAnyonePermissionWarningNotInLogs(); } @Test public void force_auth_false_no_anyone_permissions() { setForceAuthentication(false); createPublicProjectsWithNonAnyoneGroupPermissions(); assertGlobalLevelAnyonePermissionWarningNotInLogs(); assertProjectLevelAnyonePermissionWarningNotInLogs(); } @Test public void force_auth_false_project_and_global_level_anyone_permissions() { setForceAuthentication(false); dbTester.users().insertPermissionOnAnyone("perm-anyone"); createPublicProjects(3, true); assertGlobalLevelAnyonePermissionWarningInLogs(); assertProjectLevelAnyonePermissionWarningInLogs(3, "key-1", "key-2", "key-3"); } @Test public void force_auth_true_anyone_global_level_permissions() { setForceAuthentication(true); dbTester.users().insertPermissionOnAnyone("perm-anyone"); createPublicProjects(3, false); assertGlobalLevelAnyonePermissionWarningNotInLogs(); assertProjectLevelAnyonePermissionWarningNotInLogs(); } @Test public void force_auth_true_project_level_anyone_permissions() { setForceAuthentication(true); createPublicProjects(3, true); assertGlobalLevelAnyonePermissionWarningNotInLogs(); assertProjectLevelAnyonePermissionWarningNotInLogs(); } @Test public void force_auth_true_no_anyone_permissions() { setForceAuthentication(true); createPublicProjectsWithNonAnyoneGroupPermissions(); assertGlobalLevelAnyonePermissionWarningNotInLogs(); assertProjectLevelAnyonePermissionWarningNotInLogs(); } @Test public void force_auth_true_project_and_global_anyone_permissions() { setForceAuthentication(true); dbTester.users().insertPermissionOnAnyone("perm-anyone"); createPublicProjects(3, true); assertGlobalLevelAnyonePermissionWarningNotInLogs(); assertProjectLevelAnyonePermissionWarningNotInLogs(); } private void setForceAuthentication(Boolean isForceAuthentication) { settings.setProperty("sonar.forceAuthentication", isForceAuthentication.toString()); } private void createPublicProjectsWithNonAnyoneGroupPermissions() { GroupDto group = dbTester.users().insertGroup(); IntStream.rangeClosed(1, 3).forEach(i -> { ComponentDto project = dbTester.components().insertPublicProject(p -> p.setKey("key-" + i)).getMainBranchComponent(); dbTester.users().insertProjectPermissionOnGroup(group, "perm-" + i, project); }); } private void createPublicProjects(int projectCount, boolean includeAnyonePerm) { IntStream.rangeClosed(1, projectCount).forEach(i -> { ProjectDto project = dbTester.components().insertPublicProject(p -> p.setKey("key-" + i)).getProjectDto(); if (includeAnyonePerm) { dbTester.users().insertEntityPermissionOnAnyone("perm-" + i, project); } }); underTest.start(); } private void assertProjectLevelAnyonePermissionWarningNotInLogs() { boolean noneMatch = logTester.logs(Level.WARN).stream() .noneMatch(s -> s.startsWith("Authentication is not enforced, and project permissions assigned to the 'Anyone' group expose")); assertThat(noneMatch).isTrue(); } private void assertProjectLevelAnyonePermissionWarningInLogs(int expectedProjectCount, String... expectedListedProjects) { String expected = String.format("Authentication is not enforced, and project permissions assigned to the 'Anyone' group expose %d " + "public project(s) to security risks, including: %s. Unauthenticated visitors have permissions on these project(s).", expectedProjectCount, String.join(", ", expectedListedProjects)); assertThat(logTester.logs(Level.WARN)).contains(expected); } private void assertGlobalLevelAnyonePermissionWarningNotInLogs() { boolean noneMatch = !logTester.logs(Level.WARN).contains( "Authentication is not enforced, and permissions assigned to the 'Anyone' group globally expose the " + "instance to security risks. Unauthenticated visitors may unintentionally have permissions on projects."); assertThat(noneMatch).isTrue(); } private void assertGlobalLevelAnyonePermissionWarningInLogs() { String expected = "Authentication is not enforced, and permissions assigned to the 'Anyone' group globally " + "expose the instance to security risks. Unauthenticated visitors may unintentionally have permissions on projects."; assertThat(logTester.logs(Level.WARN)).contains(expected); } }
7,851
39.061224
137
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/db/CheckDatabaseCharsetAtStartupTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.db; import org.junit.After; import org.junit.Test; import org.sonar.api.platform.ServerUpgradeStatus; import org.sonar.server.platform.db.migration.charset.DatabaseCharsetChecker; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class CheckDatabaseCharsetAtStartupTest { private ServerUpgradeStatus upgradeStatus = mock(ServerUpgradeStatus.class); private DatabaseCharsetChecker charsetChecker = mock(DatabaseCharsetChecker.class); private CheckDatabaseCharsetAtStartup underTest = new CheckDatabaseCharsetAtStartup(upgradeStatus, charsetChecker); @After public void tearDown() { underTest.stop(); } @Test public void test_fresh_install() { when(upgradeStatus.isFreshInstall()).thenReturn(true); underTest.start(); verify(charsetChecker).check(DatabaseCharsetChecker.State.FRESH_INSTALL); } @Test public void test_upgrade() { when(upgradeStatus.isUpgraded()).thenReturn(true); underTest.start(); verify(charsetChecker).check(DatabaseCharsetChecker.State.UPGRADE); } @Test public void test_regular_startup() { when(upgradeStatus.isFreshInstall()).thenReturn(false); underTest.start(); verify(charsetChecker).check(DatabaseCharsetChecker.State.STARTUP); } }
2,197
30.855072
117
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/db/CheckLanguageSpecificParamsAtStartupTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.db; import org.junit.After; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.CoreProperties; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.System2; import org.sonar.api.utils.log.LoggerLevel; import org.sonar.db.DbTester; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS; import static org.sonar.api.CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS_LANGUAGE_KEY; import static org.sonar.api.CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS_MAN_DAYS_KEY; public class CheckLanguageSpecificParamsAtStartupTest { @ClassRule public static LogTester logTester = new LogTester().setLevel(LoggerLevel.WARN); @Rule public final DbTester dbTester = DbTester.create(System2.INSTANCE); private final MapSettings settings = new MapSettings(); private final CheckLanguageSpecificParamsAtStartup underTest = new CheckLanguageSpecificParamsAtStartup(settings.asConfig()); @After public void tearDown() { logTester.clear(); underTest.stop(); } @Test public void log_shows_when_language_specific_params_used() { String aLanguage = "aLanguage"; String anotherLanguage = "anotherLanguage"; settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS, "0,1"); settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "0" + "." + LANGUAGE_SPECIFIC_PARAMETERS_LANGUAGE_KEY, aLanguage); settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "0" + "." + LANGUAGE_SPECIFIC_PARAMETERS_MAN_DAYS_KEY, "30"); settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "0" + "." + CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS_SIZE_METRIC_KEY, CoreMetrics.NCLOC_KEY); settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "1" + "." + LANGUAGE_SPECIFIC_PARAMETERS_LANGUAGE_KEY, anotherLanguage); settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "1" + "." + LANGUAGE_SPECIFIC_PARAMETERS_MAN_DAYS_KEY, "40"); settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "1" + "." + CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS_SIZE_METRIC_KEY, CoreMetrics.COMPLEXITY_KEY); underTest.start(); assertThat(logTester.logs(Level.WARN)) .contains("The development cost used for calculating the technical debt is currently configured with 2 language specific parameters [Key: languageSpecificParameters]. " + "Please be aware that this functionality is deprecated, and will be removed in a future version."); } @Test public void log_does_not_show_when_language_specific_params_used() { underTest.start(); boolean noneMatch = logTester.logs(Level.WARN).stream() .noneMatch(s -> s.startsWith("The development cost used for calculating the technical debt is currently configured with")); assertThat(noneMatch).isTrue(); } }
3,850
45.963415
176
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/db/EmbeddedDatabaseFactoryTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.db; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.sonar.process.ProcessProperties.Property.JDBC_URL; public class EmbeddedDatabaseFactoryTest { private MapSettings settings = new MapSettings(); private System2 system2 = mock(System2.class); @Test public void should_start_and_stop_tcp_h2_database() { settings.setProperty(JDBC_URL.getKey(), "jdbc:h2:tcp:localhost"); EmbeddedDatabase embeddedDatabase = mock(EmbeddedDatabase.class); EmbeddedDatabaseFactory databaseFactory = new EmbeddedDatabaseFactory(settings.asConfig(), system2) { @Override EmbeddedDatabase createEmbeddedDatabase() { return embeddedDatabase; } }; databaseFactory.start(); databaseFactory.stop(); verify(embeddedDatabase).start(); verify(embeddedDatabase).stop(); } @Test public void should_not_start_mem_h2_database() { settings.setProperty(JDBC_URL.getKey(), "jdbc:h2:mem"); EmbeddedDatabase embeddedDatabase = mock(EmbeddedDatabase.class); EmbeddedDatabaseFactory databaseFactory = new EmbeddedDatabaseFactory(settings.asConfig(), system2) { @Override EmbeddedDatabase createEmbeddedDatabase() { return embeddedDatabase; } }; databaseFactory.start(); verify(embeddedDatabase, never()).start(); } }
2,389
32.194444
105
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/db/EmbeddedDatabaseTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.db; import java.io.IOException; import java.net.InetAddress; import java.sql.DriverManager; import org.h2.Driver; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; import org.junit.rules.TemporaryFolder; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.process.NetworkUtilsImpl; import static junit.framework.Assert.fail; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.sonar.process.ProcessProperties.Property.JDBC_EMBEDDED_PORT; import static org.sonar.process.ProcessProperties.Property.JDBC_PASSWORD; import static org.sonar.process.ProcessProperties.Property.JDBC_URL; import static org.sonar.process.ProcessProperties.Property.JDBC_USERNAME; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; public class EmbeddedDatabaseTest { private static final String LOOPBACK_ADDRESS = InetAddress.getLoopbackAddress().getHostAddress(); @Rule public LogTester logTester = new LogTester(); @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Rule public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60)); private MapSettings settings = new MapSettings(); private System2 system2 = mock(System2.class); private EmbeddedDatabase underTest = new EmbeddedDatabase(settings.asConfig(), system2); @After public void tearDown() { if (underTest != null) { underTest.stop(); } } @Test public void start_fails_with_IAE_if_property_Data_Path_is_not_set() { assertThatThrownBy(() -> underTest.start()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Missing property " + PATH_DATA.getKey()); } @Test public void start_fails_with_IAE_if_property_Data_Path_is_empty() { settings.setProperty(PATH_DATA.getKey(), ""); assertThatThrownBy(() -> underTest.start()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Missing property " + PATH_DATA.getKey()); } @Test public void start_fails_with_IAE_if_JDBC_URL_settings_is_not_set() throws IOException { settings.setProperty(PATH_DATA.getKey(), temporaryFolder.newFolder().getAbsolutePath()); assertThatThrownBy(() -> underTest.start()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Missing property " + JDBC_URL.getKey()); } @Test public void start_fails_with_IAE_if_embedded_port_settings_is_not_set() throws IOException { settings .setProperty(PATH_DATA.getKey(), temporaryFolder.newFolder().getAbsolutePath()) .setProperty(JDBC_URL.getKey(), "jdbc url"); assertThatThrownBy(() -> underTest.start()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Missing property " + JDBC_EMBEDDED_PORT.getKey()); } @Test public void start_ignores_URL_to_create_database_and_uses_empty_username_and_password_when_then_are_not_set() throws IOException { int port = NetworkUtilsImpl.INSTANCE.getNextLoopbackAvailablePort(); settings .setProperty(PATH_DATA.getKey(), temporaryFolder.newFolder().getAbsolutePath()) .setProperty(JDBC_URL.getKey(), "jdbc url") .setProperty(JDBC_EMBEDDED_PORT.getKey(), "" + port); underTest.start(); checkDbIsUp(port, "", ""); } @Test public void start_creates_db_and_adds_tcp_listener() throws IOException { int port = NetworkUtilsImpl.INSTANCE.getNextLoopbackAvailablePort(); settings .setProperty(PATH_DATA.getKey(), temporaryFolder.newFolder().getAbsolutePath()) .setProperty(JDBC_URL.getKey(), "jdbc url") .setProperty(JDBC_EMBEDDED_PORT.getKey(), "" + port) .setProperty(JDBC_USERNAME.getKey(), "foo") .setProperty(JDBC_PASSWORD.getKey(), "bar"); underTest.start(); checkDbIsUp(port, "foo", "bar"); // H2 listens on loopback address only verify(system2).setProperty("h2.bindAddress", LOOPBACK_ADDRESS); } @Test public void start_supports_in_memory_H2_JDBC_URL() throws IOException { int port = NetworkUtilsImpl.INSTANCE.getNextLoopbackAvailablePort(); settings .setProperty(PATH_DATA.getKey(), temporaryFolder.newFolder().getAbsolutePath()) .setProperty(JDBC_URL.getKey(), "jdbc:h2:mem:sonar") .setProperty(JDBC_EMBEDDED_PORT.getKey(), "" + port) .setProperty(JDBC_USERNAME.getKey(), "foo") .setProperty(JDBC_PASSWORD.getKey(), "bar"); underTest.start(); checkDbIsUp(port, "foo", "bar"); } private void checkDbIsUp(int port, String user, String password) { try { String driverUrl = String.format("jdbc:h2:tcp://%s:%d/sonar;USER=%s;PASSWORD=%s;NON_KEYWORDS=VALUE", LOOPBACK_ADDRESS, port, user, password); DriverManager.registerDriver(new Driver()); DriverManager.getConnection(driverUrl).close(); } catch (Exception ex) { fail("Unable to connect after start"); } } }
6,006
35.852761
147
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/db/migration/AutoDbMigrationTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.db.migration; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito; import org.slf4j.event.Level; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.db.DbClient; import org.sonar.db.dialect.Dialect; import org.sonar.db.dialect.H2; import org.sonar.db.dialect.MsSql; import org.sonar.db.dialect.Oracle; import org.sonar.db.dialect.PostgreSql; import org.sonar.server.platform.DefaultServerUpgradeStatus; import org.sonar.server.platform.db.migration.engine.MigrationEngine; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class AutoDbMigrationTest { @Rule public LogTester logTester = new LogTester(); private DbClient dbClient = mock(DbClient.class, Mockito.RETURNS_DEEP_STUBS); private DefaultServerUpgradeStatus serverUpgradeStatus = mock(DefaultServerUpgradeStatus.class); private MigrationEngine migrationEngine = mock(MigrationEngine.class); private AutoDbMigration underTest = new AutoDbMigration(serverUpgradeStatus, migrationEngine); @Test public void start_runs_MigrationEngine_on_h2_if_fresh_install() { start_runs_MigrationEngine_for_dialect_if_fresh_install(new H2()); } @Test public void start_runs_MigrationEngine_on_postgre_if_fresh_install() { start_runs_MigrationEngine_for_dialect_if_fresh_install(new PostgreSql()); } @Test public void start_runs_MigrationEngine_on_Oracle_if_fresh_install() { start_runs_MigrationEngine_for_dialect_if_fresh_install(new Oracle()); } @Test public void start_runs_MigrationEngine_on_MsSQL_if_fresh_install() { start_runs_MigrationEngine_for_dialect_if_fresh_install(new MsSql()); } private void start_runs_MigrationEngine_for_dialect_if_fresh_install(Dialect dialect) { mockDialect(dialect); mockFreshInstall(true); underTest.start(); verify(migrationEngine).execute(); verifyInfoLog(); } @Test public void start_does_nothing_if_not_fresh_install() { mockFreshInstall(false); underTest.start(); verifyNoInteractions(migrationEngine); assertThat(logTester.logs(Level.INFO)).isEmpty(); } @Test public void start_runs_MigrationEngine_if_autoDbMigration_enabled() { mockFreshInstall(false); when(serverUpgradeStatus.isUpgraded()).thenReturn(true); when(serverUpgradeStatus.isAutoDbUpgrade()).thenReturn(true); underTest.start(); verify(migrationEngine).execute(); assertThat(logTester.logs(Level.INFO)).contains("Automatically perform DB migration, as automatic database upgrade is enabled"); } @Test public void start_does_nothing_if_autoDbMigration_but_no_upgrade() { mockFreshInstall(false); when(serverUpgradeStatus.isUpgraded()).thenReturn(false); when(serverUpgradeStatus.isAutoDbUpgrade()).thenReturn(true); underTest.start(); verifyNoInteractions(migrationEngine); assertThat(logTester.logs(Level.INFO)).isEmpty(); } @Test public void stop_has_no_effect() { underTest.stop(); } private void mockFreshInstall(boolean value) { when(serverUpgradeStatus.isFreshInstall()).thenReturn(value); } private void mockDialect(Dialect dialect) { when(dbClient.getDatabase().getDialect()).thenReturn(dialect); } private void verifyInfoLog() { assertThat(logTester.logs()).hasSize(1); assertThat(logTester.logs(Level.INFO)).containsExactly("Automatically perform DB migration on fresh install"); } }
4,468
32.350746
132
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/db/migration/DatabaseMigrationExecutorServiceAdaptor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.db.migration; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * Adaptor for the DatabaseMigrationExecutorService interface which implementation of methods all throw * UnsupportedOperationException. */ class DatabaseMigrationExecutorServiceAdaptor implements DatabaseMigrationExecutorService { @Override public void execute(Runnable command) { throw new UnsupportedOperationException(); } @Override public void shutdown() { throw new UnsupportedOperationException(); } @Override public List<Runnable> shutdownNow() { throw new UnsupportedOperationException(); } @Override public boolean isShutdown() { throw new UnsupportedOperationException(); } @Override public boolean isTerminated() { throw new UnsupportedOperationException(); } @Override public boolean awaitTermination(long timeout, TimeUnit unit) { throw new UnsupportedOperationException(); } @Override public <T> Future<T> submit(Callable<T> task) { throw new UnsupportedOperationException(); } @Override public <T> Future<T> submit(Runnable task, T result) { throw new UnsupportedOperationException(); } @Override public Future<?> submit(Runnable task) { throw new UnsupportedOperationException(); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) { throw new UnsupportedOperationException(); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) { throw new UnsupportedOperationException(); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks) { throw new UnsupportedOperationException(); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) { throw new UnsupportedOperationException(); } }
2,877
28.070707
110
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/db/migration/DatabaseMigrationImplAsynchronousTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.db.migration; import org.junit.Test; import org.sonar.server.platform.Platform; import org.sonar.server.platform.db.migration.engine.MigrationEngine; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class DatabaseMigrationImplAsynchronousTest { private boolean taskSuppliedForAsyncProcess = false; /** * Implementation of execute wraps specified Runnable to add a delay of 200 ms before passing it * to a SingleThread executor to execute asynchronously. */ private DatabaseMigrationExecutorService executorService = new DatabaseMigrationExecutorServiceAdaptor() { @Override public void execute(final Runnable command) { taskSuppliedForAsyncProcess = true; } }; private MutableDatabaseMigrationState migrationState = mock(MutableDatabaseMigrationState.class); private Platform platform = mock(Platform.class); private MigrationEngine migrationEngine = mock(MigrationEngine.class); private DatabaseMigrationImpl underTest = new DatabaseMigrationImpl(executorService, migrationState, migrationEngine, platform); @Test public void testName() { underTest.startIt(); assertThat(taskSuppliedForAsyncProcess).isTrue(); } }
2,111
38.111111
130
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/db/migration/DatabaseMigrationImplConcurrentAccessTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.db.migration; import com.google.common.base.Throwables; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.After; import org.junit.Test; import org.sonar.server.platform.Platform; import org.sonar.server.platform.db.migration.engine.MigrationEngine; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class DatabaseMigrationImplConcurrentAccessTest { private ExecutorService pool = Executors.newFixedThreadPool(2); /** * Latch is used to make sure both testing threads try and call {@link DatabaseMigrationImpl#startIt()} at the * same time */ private CountDownLatch latch = new CountDownLatch(2); /** * Implementation of execute runs Runnable synchronously */ private DatabaseMigrationExecutorService executorService = new DatabaseMigrationExecutorServiceAdaptor() { @Override public void execute(Runnable command) { command.run(); } }; private AtomicInteger triggerCount = new AtomicInteger(); private MigrationEngine incrementingMigrationEngine = new MigrationEngine() { @Override public void execute() { // need execute to consume some time to avoid UT to fail because it ran too fast and threads never executed concurrently try { Thread.sleep(200); } catch (InterruptedException e) { Throwables.propagate(e); } triggerCount.incrementAndGet(); } }; private MutableDatabaseMigrationState migrationState = mock(MutableDatabaseMigrationState.class); private Platform platform = mock(Platform.class); private DatabaseMigrationImpl underTest = new DatabaseMigrationImpl(executorService, migrationState, incrementingMigrationEngine, platform); @After public void tearDown() { pool.shutdownNow(); } @Test public void two_concurrent_calls_to_startit_call_migration_engine_only_once() throws Exception { pool.submit(new CallStartit()); pool.submit(new CallStartit()); pool.awaitTermination(2, TimeUnit.SECONDS); assertThat(triggerCount.get()).isOne(); } private class CallStartit implements Runnable { @Override public void run() { latch.countDown(); try { latch.await(); } catch (InterruptedException e) { // propagate interruption Thread.currentThread().interrupt(); } underTest.startIt(); } } }
3,433
33.34
142
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/db/migration/DatabaseMigrationImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.db.migration; import java.util.Date; import org.junit.Test; import org.mockito.InOrder; import org.sonar.server.platform.Platform; import org.sonar.server.platform.db.migration.engine.MigrationEngine; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; /** * Unit test for DatabaseMigrationImpl which does not test any of its concurrency management and asynchronous execution code. */ public class DatabaseMigrationImplTest { private static final Throwable AN_ERROR = new RuntimeException("runtime exception created on purpose"); /** * Implementation of execute runs Runnable synchronously. */ private DatabaseMigrationExecutorService executorService = new DatabaseMigrationExecutorServiceAdaptor() { @Override public void execute(Runnable command) { command.run(); } }; private MutableDatabaseMigrationState migrationState = new DatabaseMigrationStateImpl(); private Platform platform = mock(Platform.class); private MigrationEngine migrationEngine = mock(MigrationEngine.class); private InOrder inOrder = inOrder(platform, migrationEngine); private DatabaseMigrationImpl underTest = new DatabaseMigrationImpl(executorService, migrationState, migrationEngine, platform); @Test public void startit_calls_MigrationEngine_execute() { underTest.startIt(); inOrder.verify(migrationEngine).execute(); inOrder.verify(platform).doStart(); inOrder.verifyNoMoreInteractions(); } @Test public void status_is_SUCCEEDED_and_failure_is_null_when_trigger_runs_without_an_exception() { underTest.startIt(); assertThat(migrationState.getStatus()).isEqualTo(DatabaseMigrationState.Status.SUCCEEDED); assertThat(migrationState.getError()).isNull(); assertThat(migrationState.getStartedAt()).isNotNull(); } @Test public void status_is_FAILED_and_failure_stores_the_exception_when_trigger_throws_an_exception() { mockMigrationThrowsError(); underTest.startIt(); assertThat(migrationState.getStatus()).isEqualTo(DatabaseMigrationState.Status.FAILED); assertThat(migrationState.getError()).isSameAs(AN_ERROR); assertThat(migrationState.getStartedAt()).isNotNull(); } @Test public void successive_calls_to_startIt_reset_status_startedAt_and_failureError() { mockMigrationThrowsError(); underTest.startIt(); assertThat(migrationState.getStatus()).isEqualTo(DatabaseMigrationState.Status.FAILED); assertThat(migrationState.getError()).isSameAs(AN_ERROR); Date firstStartDate = migrationState.getStartedAt(); assertThat(firstStartDate).isNotNull(); mockMigrationDoesNothing(); underTest.startIt(); assertThat(migrationState.getStatus()).isEqualTo(DatabaseMigrationState.Status.SUCCEEDED); assertThat(migrationState.getError()).isNull(); assertThat(migrationState.getStartedAt()).isNotSameAs(firstStartDate); } private void mockMigrationThrowsError() { doThrow(AN_ERROR).when(migrationEngine).execute(); } private void mockMigrationDoesNothing() { doNothing().when(migrationEngine).execute(); } }
4,124
35.504425
130
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/AlmConfigurationSectionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring; import org.junit.Rule; import org.junit.Test; import org.sonar.db.DbTester; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo.Attribute; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; public class AlmConfigurationSectionTest { @Rule public DbTester db = DbTester.create(); private AlmConfigurationSection underTest = new AlmConfigurationSection(db.getDbClient()); @Test public void alm_are_listed() { AlmSettingDto azure = db.almSettings().insertAzureAlmSetting(); AlmSettingDto github = db.almSettings().insertGitHubAlmSetting(); AlmSettingDto gitlab = db.almSettings().insertGitlabAlmSetting(); AlmSettingDto bitbucket = db.almSettings().insertBitbucketAlmSetting(); AlmSettingDto bitbucketCloud = db.almSettings().insertBitbucketCloudAlmSetting(); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThat(section.getAttributesList()).hasSize(5); assertThat(section.getAttributesList()) .extracting(Attribute::getKey, Attribute::getStringValue) .containsExactlyInAnyOrder( tuple(azure.getKey(), String.format("Alm:%s, Url:%s", azure.getRawAlm(), azure.getUrl())), tuple(github.getKey(), String.format("Alm:%s, Url:%s, App Id:%s, Client Id:%s", github.getRawAlm(), github.getUrl(), github.getAppId(), github.getClientId())), tuple(gitlab.getKey(), String.format("Alm:%s, Url:%s", gitlab.getRawAlm(), gitlab.getUrl())), tuple(bitbucket.getKey(), String.format("Alm:%s, Url:%s", bitbucket.getRawAlm(), bitbucket.getUrl())), tuple(bitbucketCloud.getKey(), String.format("Alm:%s, Workspace Id:%s, OAuth Key:%s", bitbucketCloud.getRawAlm(), bitbucketCloud.getAppId(), bitbucketCloud.getClientId()))); } @Test public void several_alm_same_type() { AlmSettingDto gitlab1 = db.almSettings().insertGitlabAlmSetting(); AlmSettingDto gitlab2 = db.almSettings().insertGitlabAlmSetting(); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThat(section.getAttributesList()).hasSize(2); assertThat(section.getAttributesList()) .extracting(Attribute::getKey, Attribute::getStringValue) .containsExactlyInAnyOrder( tuple(gitlab1.getKey(), String.format("Alm:%s, Url:%s", gitlab1.getRawAlm(), gitlab1.getUrl())), tuple(gitlab2.getKey(), String.format("Alm:%s, Url:%s", gitlab2.getRawAlm(), gitlab2.getUrl()))); } @Test public void null_url_are_ignored() { AlmSettingDto azure = db.almSettings().insertAzureAlmSetting(a -> a.setUrl(null)); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThat(section.getAttributesList()).hasSize(1); assertThat(section.getAttributesList()) .extracting(Attribute::getKey, Attribute::getStringValue) .containsExactlyInAnyOrder( tuple(azure.getKey(), String.format("Alm:%s", azure.getRawAlm()))); } }
3,951
43.404494
181
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/BaseSectionMBeanTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring; import java.lang.management.ManagementFactory; import javax.annotation.CheckForNull; import javax.management.InstanceNotFoundException; import javax.management.ObjectInstance; import javax.management.ObjectName; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class BaseSectionMBeanTest { private final FakeSection underTest = new FakeSection(); @Test public void test_registration() throws Exception { assertThat(getMBean()).isNull(); underTest.start(); assertThat(getMBean()).isNotNull(); underTest.stop(); assertThat(getMBean()).isNull(); } @Test public void do_not_fail_when_stopping_unstarted() throws Exception { underTest.stop(); assertThat(getMBean()).isNull(); } @CheckForNull private ObjectInstance getMBean() throws Exception { try { return ManagementFactory.getPlatformMBeanServer().getObjectInstance(new ObjectName(underTest.objectName())); } catch (InstanceNotFoundException e) { return null; } } }
1,924
30.048387
114
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/BundledSectionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring; import java.util.Arrays; import org.junit.Test; import org.sonar.core.platform.PluginInfo; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.core.plugin.PluginType; import org.sonar.server.plugins.ServerPluginRepository; import org.sonar.updatecenter.common.Version; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.server.platform.monitoring.SystemInfoTesting.assertThatAttributeIs; public class BundledSectionTest { private ServerPluginRepository repo = mock(ServerPluginRepository.class); private BundledSection underTest = new BundledSection(repo); @Test public void name() { assertThat(underTest.toProtobuf().getName()).isEqualTo("Bundled"); } @Test public void toProtobuf_given3BundledPlugins_returnThree() { when(repo.getPluginsInfoByType(PluginType.BUNDLED)).thenReturn(Arrays.asList( new PluginInfo("java") .setName("Java") .setVersion(Version.create("20.0")), new PluginInfo("c++") .setName("C++") .setVersion(Version.create("1.0.2")), new PluginInfo("no-version") .setName("No Version"))); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThatAttributeIs(section, "java", "20.0 [Java]"); assertThatAttributeIs(section, "c++", "1.0.2 [C++]"); assertThatAttributeIs(section, "no-version", "[No Version]"); } }
2,377
36.15625
91
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/CommonSystemInformationTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring; import java.util.List; import java.util.Optional; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.sonar.api.CoreProperties; import org.sonar.api.config.Configuration; import org.sonar.api.security.SecurityRealm; import org.sonar.api.server.authentication.IdentityProvider; import org.sonar.server.authentication.IdentityProviderRepository; import org.sonar.server.authentication.TestIdentityProvider; import org.sonar.server.management.ManagedInstanceService; import org.sonar.server.user.SecurityRealmFactory; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.CoreProperties.CORE_FORCE_AUTHENTICATION_DEFAULT_VALUE; @RunWith(MockitoJUnitRunner.class) public class CommonSystemInformationTest { @Mock private Configuration config; @Mock private IdentityProviderRepository identityProviderRepository; @Mock private ManagedInstanceService managedInstanceService; @Mock private SecurityRealmFactory securityRealmFactory; @InjectMocks private CommonSystemInformation commonSystemInformation; @Test public void getForceAuthentication_whenNotDefined_shouldUseDefault() { assertThat(commonSystemInformation.getForceAuthentication()) .isEqualTo(CORE_FORCE_AUTHENTICATION_DEFAULT_VALUE); } @Test public void getForceAuthentication_whenDefined_shouldBeUsed() { when(config.getBoolean(CoreProperties.CORE_FORCE_AUTHENTICATION_PROPERTY)).thenReturn(Optional.of(false)); assertThat(commonSystemInformation.getForceAuthentication()) .isFalse(); } @Test public void getEnabledIdentityProviders_whenNonDefined_shouldReturnEmpty() { mockIdentityProviders(List.of()); assertThat(commonSystemInformation.getEnabledIdentityProviders()) .isEmpty(); } @Test public void getEnabledIdentityProviders_whenDefined_shouldReturnOnlyEnabled() { mockIdentityProviders(List.of( new TestIdentityProvider().setKey("saml").setName("Okta").setEnabled(true), new TestIdentityProvider().setKey("github").setName("GitHub").setEnabled(true), new TestIdentityProvider().setKey("bitbucket").setName("BitBucket").setEnabled(false) )); assertThat(commonSystemInformation.getEnabledIdentityProviders()) .containsExactlyInAnyOrder("Okta", "GitHub"); } @Test public void getAllowsToSignUpEnabledIdentityProviders_whenNonDefined_shouldReturnEmpty() { mockIdentityProviders(List.of()); assertThat(commonSystemInformation.getAllowsToSignUpEnabledIdentityProviders()) .isEmpty(); } @Test public void getAllowsToSignUpEnabledIdentityProviders_whenDefinedButInstanceManaged_shouldReturnNull() { mockIdentityProviders(List.of( new TestIdentityProvider().setKey("saml").setName("Okta").setEnabled(true).setAllowsUsersToSignUp(true), new TestIdentityProvider().setKey("github").setName("GitHub").setEnabled(true).setAllowsUsersToSignUp(false), new TestIdentityProvider().setKey("bitbucket").setName("BitBucket").setEnabled(false).setAllowsUsersToSignUp(false) )); mockManagedInstance(true); assertThat(commonSystemInformation.getAllowsToSignUpEnabledIdentityProviders()) .isEmpty(); } @Test public void getAllowsToSignUpEnabledIdentityProviders_whenDefined_shouldReturnOnlyEnabled() { mockIdentityProviders(List.of( new TestIdentityProvider().setKey("saml").setName("Okta").setEnabled(true).setAllowsUsersToSignUp(true), new TestIdentityProvider().setKey("github").setName("GitHub").setEnabled(true).setAllowsUsersToSignUp(false), new TestIdentityProvider().setKey("bitbucket").setName("BitBucket").setEnabled(false).setAllowsUsersToSignUp(false) )); assertThat(commonSystemInformation.getAllowsToSignUpEnabledIdentityProviders()) .containsExactly("Okta"); } @Test public void getManagedInstanceProvider_whenInstanceNotManaged_shouldReturnNull() { mockIdentityProviders(List.of()); mockManagedInstance(false); assertThat(commonSystemInformation.getManagedInstanceProviderName()) .isNull(); } @Test public void getManagedInstanceProvider_whenInstanceManaged_shouldReturnName() { mockManagedInstance(true); assertThat(commonSystemInformation.getManagedInstanceProviderName()) .isEqualTo("Provider"); } @Test public void getExternalUserAuthentication_whenNotDefined_shouldReturnNull() { assertThat(commonSystemInformation.getExternalUserAuthentication()) .isNull(); } @Test public void getExternalUserAuthentication_whenDefined_shouldReturnName() { mockSecurityRealmFactory("Security Realm"); assertThat(commonSystemInformation.getExternalUserAuthentication()) .isEqualTo("Security Realm"); } private void mockIdentityProviders(List<IdentityProvider> identityProviders) { when(identityProviderRepository.getAllEnabledAndSorted()).thenReturn(identityProviders); } private void mockManagedInstance(boolean managed) { when(managedInstanceService.isInstanceExternallyManaged()).thenReturn(managed); when(managedInstanceService.getProviderName()).thenReturn("Provider"); } private void mockSecurityRealmFactory(String name) { SecurityRealm securityRealm = mock(SecurityRealm.class); when(securityRealm.getName()).thenReturn(name); when(securityRealmFactory.getRealm()).thenReturn(securityRealm); } }
6,431
37.059172
121
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/DbConnectionSectionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring; import org.junit.Rule; import org.junit.Test; import org.sonar.api.SonarQubeSide; import org.sonar.api.SonarRuntime; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.platform.db.migration.version.DatabaseVersion; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.process.systeminfo.SystemInfoUtils.attribute; public class DbConnectionSectionIT { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); private final DatabaseVersion databaseVersion = mock(DatabaseVersion.class); private final SonarRuntime runtime = mock(SonarRuntime.class); private final DbConnectionSection underTest = new DbConnectionSection(databaseVersion, dbTester.getDbClient(), runtime); @Test public void jmx_name_is_not_empty() { assertThat(underTest.name()).isEqualTo("Database"); } @Test public void pool_info() { ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThat(attribute(section, "Pool Total Connections").getLongValue()).isNotNegative(); assertThat(attribute(section, "Pool Active Connections").getLongValue()).isNotNegative(); assertThat(attribute(section, "Pool Idle Connections").getLongValue()).isNotNegative(); assertThat(attribute(section, "Pool Max Connections").getLongValue()).isNotNegative(); assertThat(attribute(section, "Pool Min Idle Connections")).isNotNull(); assertThat(attribute(section, "Pool Max Lifetime (ms)")).isNotNull(); } @Test public void section_name_depends_on_runtime_side() { when(runtime.getSonarQubeSide()).thenReturn(SonarQubeSide.COMPUTE_ENGINE); assertThat(underTest.toProtobuf().getName()).isEqualTo("Compute Engine Database Connection"); when(runtime.getSonarQubeSide()).thenReturn(SonarQubeSide.SERVER); assertThat(underTest.toProtobuf().getName()).isEqualTo("Web Database Connection"); } }
2,939
41
122
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/EsIndexesSectionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring; import org.elasticsearch.ElasticsearchException; import org.junit.Rule; import org.junit.Test; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.es.EsClient; import org.sonar.server.es.EsTester; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.process.systeminfo.SystemInfoUtils.attribute; import static org.sonar.server.platform.monitoring.SystemInfoTesting.assertThatAttributeIs; public class EsIndexesSectionTest { @Rule public EsTester es = EsTester.create(); private EsIndexesSection underTest = new EsIndexesSection(es.client()); @Test public void name() { assertThat(underTest.toProtobuf().getName()).isEqualTo("Search Indexes"); } @Test public void index_attributes() { ProtobufSystemInfo.Section section = underTest.toProtobuf(); // one index "issues" assertThat(attribute(section, "Index issues - Docs").getLongValue()).isZero(); assertThat(attribute(section, "Index issues - Shards").getLongValue()).isPositive(); assertThat(attribute(section, "Index issues - Store Size").getStringValue()).isNotNull(); } @Test public void attributes_displays_exception_message_when_cause_null_when_client_fails() { EsClient esClientMock = mock(EsClient.class); EsIndexesSection underTest = new EsIndexesSection(esClientMock); when(esClientMock.indicesStats()).thenThrow(new RuntimeException("RuntimeException with no cause")); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThatAttributeIs(section, "Error", "RuntimeException with no cause"); } @Test public void attributes_displays_exception_message_when_cause_is_not_ElasticSearchException_when_client_fails() { EsClient esClientMock = mock(EsClient.class); EsIndexesSection underTest = new EsIndexesSection(esClientMock); when(esClientMock.indicesStats()).thenThrow(new RuntimeException("RuntimeException with cause not ES", new IllegalArgumentException("some cause message"))); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThatAttributeIs(section, "Error", "RuntimeException with cause not ES"); } @Test public void attributes_displays_cause_message_when_cause_is_ElasticSearchException_when_client_fails() { EsClient esClientMock = mock(EsClient.class); EsIndexesSection underTest = new EsIndexesSection(esClientMock); when(esClientMock.indicesStats()).thenThrow(new RuntimeException("RuntimeException with ES cause", new ElasticsearchException("some cause message"))); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThatAttributeIs(section, "Error", "some cause message"); } }
3,666
41.149425
160
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/EsStateSectionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.junit.Rule; import org.junit.Test; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.es.EsClient; import org.sonar.server.es.EsTester; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.process.systeminfo.SystemInfoUtils.attribute; import static org.sonar.server.platform.monitoring.SystemInfoTesting.assertThatAttributeIs; public class EsStateSectionTest { @Rule public EsTester es = EsTester.create(); private EsStateSection underTest = new EsStateSection(es.client()); @Test public void name() { assertThat(underTest.toProtobuf().getName()).isEqualTo("Search State"); } @Test public void es_state() { assertThatAttributeIs(underTest.toProtobuf(), "State", ClusterHealthStatus.GREEN.name()); } @Test public void node_attributes() { ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThat(attribute(section, "CPU Usage (%)")).isNotNull(); assertThat(attribute(section, "Disk Available")).isNotNull(); assertThat(attribute(section, "Store Size")).isNotNull(); assertThat(attribute(section, "Translog Size")).isNotNull(); } @Test public void attributes_displays_exception_message_when_cause_null_when_client_fails() { EsClient esClientMock = mock(EsClient.class); EsStateSection underTest = new EsStateSection(esClientMock); when(esClientMock.clusterHealth(any())).thenThrow(new RuntimeException("RuntimeException with no cause")); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThatAttributeIs(section, "State", "RuntimeException with no cause"); } @Test public void attributes_displays_exception_message_when_cause_is_not_ElasticSearchException_when_client_fails() { EsClient esClientMock = mock(EsClient.class); EsStateSection underTest = new EsStateSection(esClientMock); when(esClientMock.clusterHealth(any())).thenThrow(new RuntimeException("RuntimeException with cause not ES", new IllegalArgumentException("some cause message"))); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThatAttributeIs(section, "State", "RuntimeException with cause not ES"); } @Test public void attributes_displays_cause_message_when_cause_is_ElasticSearchException_when_client_fails() { EsClient esClientMock = mock(EsClient.class); EsStateSection underTest = new EsStateSection(esClientMock); when(esClientMock.clusterHealth(any())).thenThrow(new RuntimeException("RuntimeException with ES cause", new ElasticsearchException("some cause message"))); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThatAttributeIs(section, "State", "some cause message"); } }
3,871
40.634409
166
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/FakeSection.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring; import org.sonar.process.systeminfo.BaseSectionMBean; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; public class FakeSection extends BaseSectionMBean implements FakeSectionMBean { @Override public int getFake() { return 42; } @Override public String name() { return "fake"; } @Override public ProtobufSystemInfo.Section toProtobuf() { return ProtobufSystemInfo.Section.newBuilder().build(); } }
1,338
30.880952
79
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/FakeSectionMBean.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring; public interface FakeSectionMBean { int getFake(); }
945
36.84
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/PluginsSectionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring; import java.util.Arrays; import org.junit.Test; import org.sonar.core.platform.PluginInfo; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.core.plugin.PluginType; import org.sonar.server.plugins.ServerPluginRepository; import org.sonar.updatecenter.common.Version; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.server.platform.monitoring.SystemInfoTesting.assertThatAttributeIs; public class PluginsSectionTest { private ServerPluginRepository repo = mock(ServerPluginRepository.class); private PluginsSection underTest = new PluginsSection(repo); @Test public void name() { assertThat(underTest.toProtobuf().getName()).isEqualTo("Plugins"); } @Test public void plugin_name_and_version() { when(repo.getPluginsInfoByType(PluginType.EXTERNAL)).thenReturn(Arrays.asList( new PluginInfo("key-1") .setName("Plugin 1") .setVersion(Version.create("1.1")), new PluginInfo("key-2") .setName("Plugin 2") .setVersion(Version.create("2.2")), new PluginInfo("no-version") .setName("No Version"))); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThatAttributeIs(section, "key-1", "1.1 [Plugin 1]"); assertThatAttributeIs(section, "key-2", "2.2 [Plugin 2]"); assertThatAttributeIs(section, "no-version", "[No Version]"); } }
2,376
36.140625
91
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/ServerPushSectionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring; import org.junit.Test; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.platform.monitoring.cluster.ServerPushSection; import org.sonar.server.pushapi.sonarlint.SonarLintClientsRegistry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ServerPushSectionTest { private final SonarLintClientsRegistry sonarLintClientsRegistry = mock(SonarLintClientsRegistry.class); private final ServerPushSection underTest = new ServerPushSection(sonarLintClientsRegistry); @Test public void toProtobuf_with5ConnectedSonarLintClients() { when(sonarLintClientsRegistry.countConnectedClients()).thenReturn(5L); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThat(section.getName()).isEqualTo("Server Push Connections"); assertThat(section.getAttributesList()) .extracting(ProtobufSystemInfo.Attribute::getKey, ProtobufSystemInfo.Attribute::getLongValue) .containsExactlyInAnyOrder(tuple("SonarLint Connected Clients", 5L)); } }
2,060
39.411765
105
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/SettingsSectionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.PropertyType; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.config.internal.Settings; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.newcodeperiod.NewCodePeriodType; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.platform.NodeInformation; import static org.apache.commons.lang.StringUtils.repeat; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.process.ProcessProperties.Property.CE_JAVA_OPTS; import static org.sonar.process.ProcessProperties.Property.SEARCH_JAVA_OPTS; import static org.sonar.process.ProcessProperties.Property.WEB_JAVA_OPTS; import static org.sonar.process.systeminfo.SystemInfoUtils.attribute; import static org.sonar.server.platform.monitoring.SystemInfoTesting.assertThatAttributeDoesNotExist; import static org.sonar.server.platform.monitoring.SystemInfoTesting.assertThatAttributeIs; public class SettingsSectionTest { private static final String PASSWORD_PROPERTY = "sonar.password"; @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); private PropertyDefinitions defs = new PropertyDefinitions(System2.INSTANCE, PropertyDefinition.builder(PASSWORD_PROPERTY).type(PropertyType.PASSWORD).build()); private Settings settings = new MapSettings(defs); private NodeInformation nodeInformation = mock(NodeInformation.class); private SettingsSection underTest= new SettingsSection(dbTester.getDbClient(), settings, nodeInformation); @Before public void setup(){ when(nodeInformation.isStandalone()).thenReturn(true); } @Test public void should_show_java_settings_in_standalone(){ settings.setProperty(WEB_JAVA_OPTS.getKey(), WEB_JAVA_OPTS.getDefaultValue()); settings.setProperty(CE_JAVA_OPTS.getKey(), CE_JAVA_OPTS.getDefaultValue()); settings.setProperty(SEARCH_JAVA_OPTS.getKey(), SEARCH_JAVA_OPTS.getDefaultValue()); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, WEB_JAVA_OPTS.getKey(), WEB_JAVA_OPTS.getDefaultValue()); assertThatAttributeIs(protobuf, CE_JAVA_OPTS.getKey(), CE_JAVA_OPTS.getDefaultValue()); assertThatAttributeIs(protobuf, SEARCH_JAVA_OPTS.getKey(), SEARCH_JAVA_OPTS.getDefaultValue()); } @Test public void should_not_show_java_settings_in_cluster(){ when(nodeInformation.isStandalone()).thenReturn(false); settings.setProperty(WEB_JAVA_OPTS.getKey(), WEB_JAVA_OPTS.getDefaultValue()); settings.setProperty(CE_JAVA_OPTS.getKey(), CE_JAVA_OPTS.getDefaultValue()); settings.setProperty(SEARCH_JAVA_OPTS.getKey(), SEARCH_JAVA_OPTS.getDefaultValue()); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeDoesNotExist(protobuf, WEB_JAVA_OPTS.getKey()); assertThatAttributeDoesNotExist(protobuf, CE_JAVA_OPTS.getKey()); assertThatAttributeDoesNotExist(protobuf, SEARCH_JAVA_OPTS.getKey()); } @Test public void return_properties_and_sort_by_key() { settings.setProperty("foo", "foo value"); settings.setProperty("bar", "bar value"); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "bar", "bar value"); assertThatAttributeIs(protobuf, "foo", "foo value"); assertThatAttributeIs(protobuf, "Default New Code Definition", "PREVIOUS_VERSION"); // keys are ordered alphabetically assertThat(protobuf.getAttributesList()) .extracting(ProtobufSystemInfo.Attribute::getKey) .containsExactly("bar", "foo", "Default New Code Definition"); } @Test public void return_default_new_code_definition_with_no_specified_value() { dbTester.newCodePeriods().insert(NewCodePeriodType.PREVIOUS_VERSION,null); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "Default New Code Definition", "PREVIOUS_VERSION"); } @Test public void return_default_new_code_definition_with_specified_value() { dbTester.newCodePeriods().insert(NewCodePeriodType.NUMBER_OF_DAYS,"30"); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "Default New Code Definition", "NUMBER_OF_DAYS: 30"); } @Test public void long_property_values_are_not_truncated() { String value = repeat("abcde", 1_000); settings.setProperty("foo", value); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); String actualValue = attribute(protobuf, "foo").getStringValue(); assertThat(actualValue).isEqualTo(value); } @Test public void value_is_obfuscated_if_key_matches_patterns() { verifyObfuscated(PASSWORD_PROPERTY); verifyObfuscated("foo.password.something"); // case insensitive search of "password" term verifyObfuscated("bar.CheckPassword"); verifyObfuscated("foo.passcode.something"); // case insensitive search of "passcode" term verifyObfuscated("bar.CheckPassCode"); verifyObfuscated("foo.something.secured"); verifyObfuscated("bar.something.Secured"); verifyObfuscated("sonar.auth.jwtBase64Hs256Secret"); verifyNotObfuscated("securedStuff"); verifyNotObfuscated("foo"); } private void verifyObfuscated(String key) { settings.setProperty(key, "foo"); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, key, "xxxxxxxx"); } private void verifyNotObfuscated(String key) { settings.setProperty(key, "foo"); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, key, "foo"); } @Test public void test_monitor_name() { assertThat(underTest.toProtobuf().getName()).isEqualTo("Settings"); } }
6,905
40.60241
162
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/StandaloneSystemSectionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.SonarEdition; import org.sonar.api.SonarRuntime; import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.platform.Server; import org.sonar.api.utils.log.LoggerLevel; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.log.ServerLogging; import org.sonar.server.platform.ContainerSupport; import org.sonar.server.platform.OfficialDistribution; import org.sonar.server.platform.StatisticsSupport; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.SonarEdition.COMMUNITY; import static org.sonar.api.SonarEdition.DATACENTER; import static org.sonar.api.SonarEdition.DEVELOPER; import static org.sonar.api.SonarEdition.ENTERPRISE; import static org.sonar.process.systeminfo.SystemInfoUtils.attribute; import static org.sonar.server.platform.monitoring.SystemInfoTesting.assertThatAttributeDoesNotExist; import static org.sonar.server.platform.monitoring.SystemInfoTesting.assertThatAttributeIs; @RunWith(DataProviderRunner.class) public class StandaloneSystemSectionTest { private final MapSettings settings = new MapSettings(); private final Configuration config = settings.asConfig(); private final Server server = mock(Server.class); private final ServerLogging serverLogging = mock(ServerLogging.class); private final OfficialDistribution officialDistribution = mock(OfficialDistribution.class); private final ContainerSupport containerSupport = mock(ContainerSupport.class); private final StatisticsSupport statisticsSupport = mock(StatisticsSupport.class); private final SonarRuntime sonarRuntime = mock(SonarRuntime.class); private final CommonSystemInformation commonSystemInformation = mock(CommonSystemInformation.class); private final StandaloneSystemSection underTest = new StandaloneSystemSection(config, server, serverLogging, officialDistribution, containerSupport, statisticsSupport, sonarRuntime, commonSystemInformation); @Before public void setUp() { when(serverLogging.getRootLoggerLevel()).thenReturn(LoggerLevel.DEBUG); when(sonarRuntime.getEdition()).thenReturn(COMMUNITY); } @Test public void name_is_not_empty() { assertThat(underTest.name()).isNotEmpty(); } @Test public void test_getServerId() { when(server.getId()).thenReturn("ABC"); assertThat(underTest.getServerId()).isEqualTo("ABC"); } @Test public void official_distribution() { when(officialDistribution.check()).thenReturn(true); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "Official Distribution", true); } @Test public void not_an_official_distribution() { when(officialDistribution.check()).thenReturn(false); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "Official Distribution", false); } @Test public void toProtobuf_whenNoExternalUserAuthentication_shouldWriteNothing() { when(commonSystemInformation.getExternalUserAuthentication()).thenReturn(null); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeDoesNotExist(protobuf, "External User Authentication"); } @Test public void toProtobuf_whenExternalUserAuthentication_shouldWriteIt() { when(commonSystemInformation.getExternalUserAuthentication()).thenReturn("LDAP"); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "External User Authentication", "LDAP"); } @Test public void toProtobuf_whenNoIdentityProviders_shouldWriteNothing() { when(commonSystemInformation.getEnabledIdentityProviders()).thenReturn(emptyList()); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeDoesNotExist(protobuf, "Accepted external identity providers"); } @Test public void toProtobuf_whenEnabledIdentityProviders_shouldWriteThem() { when(commonSystemInformation.getEnabledIdentityProviders()).thenReturn(List.of("Bitbucket, GitHub")); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "Accepted external identity providers", "Bitbucket, GitHub"); } @Test public void toProtobuf_whenNoAllowsToSignUpEnabledIdentityProviders_shouldWriteNothing() { when(commonSystemInformation.getAllowsToSignUpEnabledIdentityProviders()).thenReturn(emptyList()); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeDoesNotExist(protobuf, "External identity providers whose users are allowed to sign themselves up"); } @Test public void toProtobuf_whenAllowsToSignUpEnabledIdentityProviders_shouldWriteThem() { when(commonSystemInformation.getAllowsToSignUpEnabledIdentityProviders()).thenReturn(List.of("GitHub")); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "External identity providers whose users are allowed to sign themselves up", "GitHub"); } @Test public void return_nb_of_processors() { ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThat(attribute(protobuf, "Processors").getLongValue()).isPositive(); } @Test public void toProtobuf_whenForceAuthentication_returnIt() { when(commonSystemInformation.getForceAuthentication()).thenReturn(false); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "Force authentication", false); } @Test public void return_Lines_of_Codes_from_StatisticsSupport(){ when(statisticsSupport.getLinesOfCode()).thenReturn(17752L); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf,"Lines of Code", 17752L); } @Test @UseDataProvider("trueOrFalse") public void toProtobuf_whenRunningOrNotRunningInContainer_shouldReturnCorrectFlag(boolean flag) { when(containerSupport.isRunningInContainer()).thenReturn(flag); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThat(attribute(protobuf, "Container").getBooleanValue()).isEqualTo(flag); } @Test @UseDataProvider("editions") public void get_edition(SonarEdition sonarEdition, String editionLabel) { when(sonarRuntime.getEdition()).thenReturn(sonarEdition); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "Edition", editionLabel); } @Test public void toProtobuf_whenInstanceIsNotManaged_shouldWriteNothing() { when(commonSystemInformation.getManagedInstanceProviderName()).thenReturn(null); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeDoesNotExist(protobuf, "External Users and Groups Provisioning"); } @Test public void toProtobuf_whenInstanceIsManaged_shouldWriteItsProviderName() { when(commonSystemInformation.getManagedInstanceProviderName()).thenReturn("Okta"); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "External Users and Groups Provisioning", "Okta"); } @DataProvider public static Object[][] trueOrFalse() { return new Object[][] { {true}, {false} }; } @DataProvider public static Object[][] editions() { return new Object[][] { {COMMUNITY, COMMUNITY.getLabel()}, {DEVELOPER, DEVELOPER.getLabel()}, {ENTERPRISE, ENTERPRISE.getLabel()}, {DATACENTER, DATACENTER.getLabel()}, }; } }
8,844
39.388128
123
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/cluster/AppNodesInfoLoaderImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring.cluster; import com.hazelcast.cluster.Address; import com.hazelcast.cluster.Member; import com.hazelcast.cluster.MemberSelector; import java.io.IOException; import java.net.InetAddress; import java.util.Collection; import org.junit.Test; import org.mockito.Mockito; import org.sonar.process.cluster.hz.DistributedAnswer; import org.sonar.process.cluster.hz.DistributedCall; import org.sonar.process.cluster.hz.HazelcastMember; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo.Section; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo.SystemInfo; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class AppNodesInfoLoaderImplTest { private static final InetAddress AN_ADDRESS = InetAddress.getLoopbackAddress(); private final HazelcastMember hzMember = mock(HazelcastMember.class); private final AppNodesInfoLoaderImpl underTest = new AppNodesInfoLoaderImpl(hzMember); @Test public void load_info_from_all_nodes() throws Exception { DistributedAnswer<SystemInfo> answer = new DistributedAnswer<>(); answer.setAnswer(newMember("foo"), SystemInfo.newBuilder().addSections(Section.newBuilder().build()).build()); answer.setTimedOut(newMember("bar")); answer.setFailed(newMember("baz"), new IOException("BOOM")); when(hzMember.call(any(DistributedCall.class), any(MemberSelector.class), anyLong())).thenReturn(answer); Collection<NodeInfo> nodes = underTest.load(); assertThat(nodes).hasSize(3); NodeInfo successfulNodeInfo = findNode(nodes, "foo"); assertThat(successfulNodeInfo.getName()).isEqualTo("foo"); assertThat(successfulNodeInfo.getHost()).hasValue(AN_ADDRESS.getHostAddress()); assertThat(successfulNodeInfo.getErrorMessage()).isEmpty(); assertThat(successfulNodeInfo.getSections()).hasSize(1); NodeInfo timedOutNodeInfo = findNode(nodes, "bar"); assertThat(timedOutNodeInfo.getName()).isEqualTo("bar"); assertThat(timedOutNodeInfo.getErrorMessage()).hasValue("Failed to retrieve information on time"); assertThat(timedOutNodeInfo.getSections()).isEmpty(); NodeInfo failedNodeInfo = findNode(nodes, "baz"); assertThat(failedNodeInfo.getName()).isEqualTo("baz"); assertThat(failedNodeInfo.getErrorMessage()).hasValue("Failed to retrieve information: BOOM"); assertThat(failedNodeInfo.getSections()).isEmpty(); } private NodeInfo findNode(Collection<NodeInfo> nodes, String name) { return nodes.stream() .filter(n -> n.getName().equals(name)) .findFirst() .orElseThrow(IllegalStateException::new); } private Member newMember(String name) { Member member = mock(Member.class, Mockito.RETURNS_MOCKS); when(member.getAttribute(HazelcastMember.Attribute.NODE_NAME.getKey())).thenReturn(name); when(member.getAddress()).thenReturn(new Address(AN_ADDRESS, 6789)); return member; } }
3,946
41.44086
114
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/cluster/CeQueueGlobalSectionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring.cluster; import java.util.Optional; import org.junit.Test; import org.mockito.Mockito; import org.sonar.ce.configuration.WorkerCountProvider; import org.sonar.db.DbClient; import org.sonar.db.ce.CeQueueDto; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.property.InternalProperties; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.server.platform.monitoring.SystemInfoTesting.assertThatAttributeIs; public class CeQueueGlobalSectionTest { private final DbClient dbClient = mock(DbClient.class, Mockito.RETURNS_DEEP_STUBS); private final WorkerCountProvider workerCountProvider = mock(WorkerCountProvider.class); @Test public void test_queue_state_with_default_settings() { when(dbClient.ceQueueDao().countByStatus(any(), eq(CeQueueDto.Status.PENDING))).thenReturn(10); when(dbClient.ceQueueDao().countByStatus(any(), eq(CeQueueDto.Status.IN_PROGRESS))).thenReturn(1); CeQueueGlobalSection underTest = new CeQueueGlobalSection(dbClient, null); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThatAttributeIs(section, "Total Pending", 10); assertThatAttributeIs(section, "Total In Progress", 1); assertThatAttributeIs(section, "Max Workers per Node", 1); } @Test public void test_queue_state_with_overridden_settings() { when(dbClient.ceQueueDao().countByStatus(any(), eq(CeQueueDto.Status.PENDING))).thenReturn(10); when(dbClient.ceQueueDao().countByStatus(any(), eq(CeQueueDto.Status.IN_PROGRESS))).thenReturn(2); when(workerCountProvider.get()).thenReturn(5); CeQueueGlobalSection underTest = new CeQueueGlobalSection(dbClient, workerCountProvider); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThatAttributeIs(section, "Total Pending", 10); assertThatAttributeIs(section, "Total In Progress", 2); assertThatAttributeIs(section, "Max Workers per Node", 5); } @Test public void test_workers_not_paused() { CeQueueGlobalSection underTest = new CeQueueGlobalSection(dbClient, workerCountProvider); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThatAttributeIs(section, "Workers Paused", false); } @Test public void test_workers_paused() { when(dbClient.internalPropertiesDao().selectByKey(any(), eq(InternalProperties.COMPUTE_ENGINE_PAUSE))).thenReturn(Optional.of("true")); CeQueueGlobalSection underTest = new CeQueueGlobalSection(dbClient, workerCountProvider); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThatAttributeIs(section, "Workers Paused", true); } }
3,658
41.057471
139
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/cluster/EsClusterStateSectionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring.cluster; import org.junit.Rule; import org.junit.Test; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.es.EsTester; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.process.systeminfo.SystemInfoUtils.attribute; public class EsClusterStateSectionTest { @Rule public EsTester es = EsTester.create(); private EsClusterStateSection underTest = new EsClusterStateSection(es.client()); @Test public void test_name() { assertThat(underTest.toProtobuf().getName()).isEqualTo("Search State"); } @Test public void test_attributes() { ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThat(attribute(section, "Nodes").getLongValue()).isPositive(); assertThat(attribute(section, "State").getStringValue()).isIn("RED", "YELLOW", "GREEN"); } }
1,750
34.734694
92
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/cluster/GlobalInfoLoaderTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring.cluster; import java.util.List; import org.junit.Test; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import static org.assertj.core.api.Assertions.assertThat; public class GlobalInfoLoaderTest { @Test public void call_only_SystemInfoSection_that_inherit_Global() { // two globals and one standard SystemInfoSection[] sections = new SystemInfoSection[] { new TestGlobalSystemInfoSection("foo"), new TestSystemInfoSection("bar"), new TestGlobalSystemInfoSection("baz")}; GlobalInfoLoader underTest = new GlobalInfoLoader(sections); List<ProtobufSystemInfo.Section> loadedInfo = underTest.load(); assertThat(loadedInfo).extracting(ProtobufSystemInfo.Section::getName) .containsExactlyInAnyOrder("foo", "baz"); } }
1,718
37.2
120
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/cluster/GlobalSystemSectionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring.cluster; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.SonarRuntime; import org.sonar.api.platform.Server; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.platform.ContainerSupport; import org.sonar.server.platform.StatisticsSupport; import org.sonar.server.platform.monitoring.CommonSystemInformation; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.SonarEdition.COMMUNITY; import static org.sonar.server.platform.monitoring.SystemInfoTesting.assertThatAttributeDoesNotExist; import static org.sonar.server.platform.monitoring.SystemInfoTesting.assertThatAttributeIs; @RunWith(DataProviderRunner.class) public class GlobalSystemSectionTest { private final Server server = mock(Server.class); private final ContainerSupport containerSupport = mock(ContainerSupport.class); private final StatisticsSupport statisticsSupport = mock(StatisticsSupport.class); private final SonarRuntime sonarRuntime = mock(SonarRuntime.class); private final CommonSystemInformation commonSystemInformation = mock(CommonSystemInformation.class); private final GlobalSystemSection underTest = new GlobalSystemSection(server, containerSupport, statisticsSupport, sonarRuntime, commonSystemInformation); @Before public void setUp() { when(sonarRuntime.getEdition()).thenReturn(COMMUNITY); } @Test public void name_is_not_empty() { assertThat(underTest.toProtobuf().getName()).isEqualTo("System"); } @Test public void toProtobuf_whenNoExternalUserAuthentication_shouldWriteNothing() { when(commonSystemInformation.getExternalUserAuthentication()).thenReturn(null); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeDoesNotExist(protobuf, "External User Authentication"); } @Test public void toProtobuf_whenExternalUserAuthentication_shouldWriteIt() { when(commonSystemInformation.getExternalUserAuthentication()).thenReturn("LDAP"); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "External User Authentication", "LDAP"); } @Test public void toProtobuf_whenNoIdentityProviders_shouldWriteNothing() { when(commonSystemInformation.getEnabledIdentityProviders()).thenReturn(emptyList()); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeDoesNotExist(protobuf, "Accepted external identity providers"); } @Test public void toProtobuf_whenEnabledIdentityProviders_shouldWriteThem() { when(commonSystemInformation.getEnabledIdentityProviders()).thenReturn(List.of("Bitbucket, GitHub")); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "Accepted external identity providers", "Bitbucket, GitHub"); } @Test public void toProtobuf_whenNoAllowsToSignUpEnabledIdentityProviders_shouldWriteNothing() { when(commonSystemInformation.getAllowsToSignUpEnabledIdentityProviders()).thenReturn(emptyList()); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeDoesNotExist(protobuf, "External identity providers whose users are allowed to sign themselves up"); } @Test public void toProtobuf_whenAllowsToSignUpEnabledIdentityProviders_shouldWriteThem() { when(commonSystemInformation.getAllowsToSignUpEnabledIdentityProviders()).thenReturn(List.of("GitHub")); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "External identity providers whose users are allowed to sign themselves up", "GitHub"); } @Test public void toProtobuf_whenInstanceIsNotManaged_shouldWriteNothing() { when(commonSystemInformation.getManagedInstanceProviderName()).thenReturn(null); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeDoesNotExist(protobuf, "External Users and Groups Provisioning"); } @Test public void toProtobuf_whenInstanceIsManaged_shouldWriteItsProviderName() { when(commonSystemInformation.getManagedInstanceProviderName()).thenReturn("Okta"); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "External Users and Groups Provisioning", "Okta"); } @Test public void toProtobuf_whenForceAuthentication_returnIt() { when(commonSystemInformation.getForceAuthentication()).thenReturn(false); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "Force authentication", false); } @Test public void return_Lines_of_Codes_from_StatisticsSupport(){ when(statisticsSupport.getLinesOfCode()).thenReturn(17752L); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf,"Lines of Code", 17752L); } @Test @UseDataProvider("trueOrFalse") public void toProtobuf_whenRunningOrNotRunningInContainer_shouldReturnCorrectFlag(boolean flag) { when(containerSupport.isRunningInContainer()).thenReturn(flag); ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "Container", flag); } @Test public void get_edition() { ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); assertThatAttributeIs(protobuf, "Edition", COMMUNITY.getLabel()); } @DataProvider public static Object[][] trueOrFalse() { return new Object[][] { {true}, {false}, }; } }
6,754
39.939394
156
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/cluster/NodeInfoTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring.cluster; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class NodeInfoTest { @Test public void test_equals_and_hashCode() { NodeInfo foo = new NodeInfo("foo"); NodeInfo bar = new NodeInfo("bar"); NodeInfo bar2 = new NodeInfo("bar"); assertThat(foo.equals(foo)).isTrue(); assertThat(foo.equals(bar)).isFalse(); assertThat(bar.equals(bar2)).isTrue(); assertThat(bar) .hasSameHashCodeAs(bar) .hasSameHashCodeAs(bar2); } }
1,401
30.863636
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/cluster/NodeSystemSectionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring.cluster; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.platform.Server; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.platform.OfficialDistribution; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; import static org.sonar.process.ProcessProperties.Property.PATH_HOME; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; import static org.sonar.process.ProcessProperties.Property.PATH_TEMP; import static org.sonar.process.ProcessProperties.Property.PATH_WEB; import static org.sonar.process.systeminfo.SystemInfoUtils.attribute; import static org.sonar.server.platform.monitoring.SystemInfoTesting.assertThatAttributeIs; public class NodeSystemSectionTest { private MapSettings settings = new MapSettings(); private Server server = mock(Server.class, RETURNS_DEEP_STUBS); private OfficialDistribution officialDistrib = mock(OfficialDistribution.class); private NodeSystemSection underTest = new NodeSystemSection(settings.asConfig(), server, officialDistrib); @Test public void test_section_name() { ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThat(section.getName()).isEqualTo("System"); } @Test public void return_server_version() { when(server.getVersion()).thenReturn("6.6"); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThatAttributeIs(section, "Version", "6.6"); } @Test public void return_official_distribution_flag() { when(officialDistrib.check()).thenReturn(true); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThatAttributeIs(section, "Official Distribution", true); } @Test public void return_nb_of_processors() { ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThat(attribute(section, "Processors").getLongValue()).isPositive(); } @Test public void return_dir_paths() { settings.setProperty(PATH_HOME.getKey(), "/home"); settings.setProperty(PATH_DATA.getKey(), "/data"); settings.setProperty(PATH_TEMP.getKey(), "/temp"); settings.setProperty(PATH_LOGS.getKey(), "/logs"); settings.setProperty(PATH_WEB.getKey(), "/web"); ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThatAttributeIs(section, "Home Dir", "/home"); assertThatAttributeIs(section, "Data Dir", "/data"); assertThatAttributeIs(section, "Temp Dir", "/temp"); // logs dir is part of LoggingSection assertThat(attribute(section, "Logs Dir")).isNull(); // for internal usage assertThat(attribute(section, "Web Dir")).isNull(); } }
3,771
35.980392
108
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/cluster/SearchNodesInfoLoaderImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.monitoring.cluster; import java.util.Collection; import org.junit.Rule; import org.junit.Test; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.es.EsTester; import org.sonar.server.es.newindex.FakeIndexDefinition; import static org.assertj.core.api.Assertions.assertThat; public class SearchNodesInfoLoaderImplTest { @Rule public EsTester es = EsTester.createCustom(new FakeIndexDefinition()); private SearchNodesInfoLoaderImpl underTest = new SearchNodesInfoLoaderImpl(es.client()); @Test public void return_info_from_elasticsearch_api() { Collection<NodeInfo> nodes = underTest.load(); assertThat(nodes).hasSize(1); NodeInfo node = nodes.iterator().next(); assertThat(node.getName()).isNotEmpty(); assertThat(node.getHost()).isNotEmpty(); assertThat(node.getSections()).hasSize(1); ProtobufSystemInfo.Section stateSection = node.getSections().get(0); assertThat(stateSection.getAttributesList()) .extracting(ProtobufSystemInfo.Attribute::getKey) .contains( "Disk Available", "Store Size", "JVM Heap Usage", "JVM Heap Used", "JVM Heap Max", "JVM Non Heap Used", "JVM Threads", "Field Data Memory", "Field Data Circuit Breaker Limit", "Field Data Circuit Breaker Estimation", "Request Circuit Breaker Limit", "Request Circuit Breaker Estimation", "Query Cache Memory", "Request Cache Memory"); } }
2,327
37.8
105
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/serverid/ServerIdFactoryImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.serverid; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.text.SimpleDateFormat; import java.util.Date; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.MapSettings; import org.sonar.core.platform.ServerId; import org.sonar.core.util.UuidFactory; import org.sonar.core.util.Uuids; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.core.platform.ServerId.DATABASE_ID_LENGTH; import static org.sonar.core.platform.ServerId.NOT_UUID_DATASET_ID_LENGTH; import static org.sonar.core.platform.ServerId.UUID_DATASET_ID_LENGTH; import static org.sonar.process.ProcessProperties.Property.JDBC_URL; import static org.sonar.server.platform.serverid.ServerIdFactoryImpl.crc32Hex; @RunWith(DataProviderRunner.class) public class ServerIdFactoryImplTest { private static final ServerId A_SERVERID = ServerId.of(randomAlphabetic(DATABASE_ID_LENGTH), randomAlphabetic(UUID_DATASET_ID_LENGTH)); private MapSettings settings = new MapSettings(); private Configuration config = settings.asConfig(); private UuidFactory uuidFactory = mock(UuidFactory.class); private JdbcUrlSanitizer jdbcUrlSanitizer = mock(JdbcUrlSanitizer.class); private ServerIdFactoryImpl underTest = new ServerIdFactoryImpl(config, uuidFactory, jdbcUrlSanitizer); @Test public void create_from_scratch_fails_with_ISE_if_JDBC_property_not_set() { expectMissingJdbcUrlISE(() -> underTest.create()); } @Test public void create_from_scratch_creates_ServerId_from_JDBC_URL_and_new_uuid() { String jdbcUrl = "jdbc"; String uuid = Uuids.create(); String sanitizedJdbcUrl = "sanitized_jdbc"; settings.setProperty(JDBC_URL.getKey(), jdbcUrl); when(uuidFactory.create()).thenReturn(uuid); when(jdbcUrlSanitizer.sanitize(jdbcUrl)).thenReturn(sanitizedJdbcUrl); ServerId serverId = underTest.create(); assertThat(serverId.getDatabaseId()).contains(crc32Hex(sanitizedJdbcUrl)); assertThat(serverId.getDatasetId()).isEqualTo(uuid); } @Test public void create_from_ServerId_fails_with_ISE_if_JDBC_property_not_set() { expectMissingJdbcUrlISE(() -> underTest.create(A_SERVERID)); } @Test @UseDataProvider("anyFormatServerId") public void create_from_ServerId_creates_ServerId_from_JDBC_URL_and_serverId_datasetId(ServerId currentServerId) { String jdbcUrl = "jdbc"; String sanitizedJdbcUrl = "sanitized_jdbc"; settings.setProperty(JDBC_URL.getKey(), jdbcUrl); when(uuidFactory.create()).thenThrow(new IllegalStateException("UuidFactory.create() should not be called")); when(jdbcUrlSanitizer.sanitize(jdbcUrl)).thenReturn(sanitizedJdbcUrl); ServerId serverId = underTest.create(currentServerId); assertThat(serverId.getDatabaseId()).contains(crc32Hex(sanitizedJdbcUrl)); assertThat(serverId.getDatasetId()).isEqualTo(currentServerId.getDatasetId()); } @DataProvider public static Object[][] anyFormatServerId() { return new Object[][] { {ServerId.parse(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()))}, {ServerId.parse(randomAlphabetic(NOT_UUID_DATASET_ID_LENGTH))}, {ServerId.parse(randomAlphabetic(UUID_DATASET_ID_LENGTH))}, {ServerId.of(randomAlphabetic(DATABASE_ID_LENGTH), randomAlphabetic(NOT_UUID_DATASET_ID_LENGTH))}, {ServerId.of(randomAlphabetic(DATABASE_ID_LENGTH), randomAlphabetic(UUID_DATASET_ID_LENGTH))} }; } private void expectMissingJdbcUrlISE(ThrowingCallable callback) { assertThatThrownBy(callback) .isInstanceOf(IllegalStateException.class) .hasMessage("Missing JDBC URL"); } }
4,964
42.173913
137
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/serverid/ServerIdModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.serverid; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class ServerIdModuleTest { private final ServerIdModule underTest = new ServerIdModule(); @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); underTest.configure(container); assertThat(container.getAddedObjects()).hasSize(4); } }
1,325
34.837838
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/web/RootFilterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.web; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.List; import java.util.stream.IntStream; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.slf4j.event.Level; import org.sonar.api.testfixtures.log.LogTester; import static java.util.stream.Collectors.joining; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class RootFilterTest { private static final String PAYLOAD = "payload"; @Rule public LogTester logTester = new LogTester(); private FilterChain chain = mock(FilterChain.class); private RootFilter underTest; @Before public void initialize() { FilterConfig filterConfig = mock(FilterConfig.class); ServletContext context = mock(ServletContext.class); when(context.getContextPath()).thenReturn("/context"); when(filterConfig.getServletContext()).thenReturn(context); underTest = new RootFilter(); underTest.init(filterConfig); } @Test public void throwable_in_doFilter_is_caught_and_500_error_returned_if_response_is_not_committed() throws Exception { doThrow(new RuntimeException()).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); HttpServletResponse response = mockHttpResponse(false); underTest.doFilter(request("POST", "/context/service/call", "param=value"), response, chain); verify(response).sendError(500); } @Test public void throwable_in_doFilter_is_caught_but_no_500_response_is_sent_if_response_already_committed() throws Exception { doThrow(new RuntimeException()).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); HttpServletResponse response = mockHttpResponse(true); underTest.doFilter(request("POST", "/context/service/call", "param=value"), response, chain); verify(response, never()).sendError(500); } @Test public void throwable_in_doFilter_is_logged_in_debug_if_response_is_already_committed() throws Exception { logTester.setLevel(Level.DEBUG); doThrow(new RuntimeException()).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); HttpServletResponse response = mockHttpResponse(true); underTest.doFilter(request("POST", "/context/service/call", "param=value"), response, chain); List<String> debugLogs = logTester.logs(Level.DEBUG); assertThat(debugLogs.size()).isOne(); assertThat(debugLogs.get(0)).contains("Processing of request", "failed"); } @Test public void request_used_in_chain_do_filter_is_a_servlet_wrapper_when_static_resource() throws Exception { underTest.doFilter(request("GET", "/context/static/image.png", null), mock(HttpServletResponse.class), chain); ArgumentCaptor<ServletRequest> requestArgumentCaptor = ArgumentCaptor.forClass(ServletRequest.class); verify(chain).doFilter(requestArgumentCaptor.capture(), any(HttpServletResponse.class)); assertThat(requestArgumentCaptor.getValue()).isInstanceOf(RootFilter.ServletRequestWrapper.class); } @Test public void request_used_in_chain_do_filter_is_a_servlet_wrapper_when_service_call() throws Exception { underTest.doFilter(request("POST", "/context/service/call", "param=value"), mock(HttpServletResponse.class), chain); ArgumentCaptor<ServletRequest> requestArgumentCaptor = ArgumentCaptor.forClass(ServletRequest.class); verify(chain).doFilter(requestArgumentCaptor.capture(), any(HttpServletResponse.class)); assertThat(requestArgumentCaptor.getValue()).isInstanceOf(RootFilter.ServletRequestWrapper.class); } @Test public void fail_to_get_session_from_request() throws Exception { underTest.doFilter(request("GET", "/context/static/image.png", null), mock(HttpServletResponse.class), chain); ArgumentCaptor<ServletRequest> requestArgumentCaptor = ArgumentCaptor.forClass(ServletRequest.class); verify(chain).doFilter(requestArgumentCaptor.capture(), any(ServletResponse.class)); ServletRequest actualServletRequest = requestArgumentCaptor.getValue(); assertThatThrownBy(() -> ((HttpServletRequest) actualServletRequest).getSession()) .isInstanceOf(UnsupportedOperationException.class); } @Test public void fail_to_get_session_with_create_from_request() throws Exception { underTest.doFilter(request("GET", "/context/static/image.png", null), mock(HttpServletResponse.class), chain); ArgumentCaptor<ServletRequest> requestArgumentCaptor = ArgumentCaptor.forClass(ServletRequest.class); verify(chain).doFilter(requestArgumentCaptor.capture(), any(ServletResponse.class)); ServletRequest actualServletRequest = requestArgumentCaptor.getValue(); assertThatThrownBy(() -> ((HttpServletRequest) actualServletRequest).getSession(true)) .isInstanceOf(UnsupportedOperationException.class); } private HttpServletRequest request(String method, String path, String query) { HttpServletRequest request = mock(HttpServletRequest.class); when(request.getMethod()).thenReturn(method); when(request.getRequestURI()).thenReturn(path); when(request.getQueryString()).thenReturn(query); return request; } private static HttpServletResponse mockHttpResponse(boolean committed) { HttpServletResponse response = mock(HttpServletResponse.class); when(response.isCommitted()).thenReturn(committed); return response; } @Test public void body_can_be_read_several_times() { HttpServletRequest request = mockRequestWithBody(); RootFilter.ServletRequestWrapper servletRequestWrapper = new RootFilter.ServletRequestWrapper(request); IntStream.range(0,3).forEach(i -> assertThat(readBody(servletRequestWrapper)).isEqualTo(PAYLOAD)); } @Test public void getReader_whenIoExceptionThrown_rethrows() throws IOException { HttpServletRequest request = mockRequestWithBody(); IOException ioException = new IOException(); when(request.getReader()).thenThrow(ioException); RootFilter.ServletRequestWrapper servletRequestWrapper = new RootFilter.ServletRequestWrapper(request); assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> readBody(servletRequestWrapper)) .withCause(ioException); } private static HttpServletRequest mockRequestWithBody() { HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); try { StringReader stringReader = new StringReader(PAYLOAD); BufferedReader bufferedReader = new BufferedReader(stringReader); when(httpServletRequest.getReader()).thenReturn(bufferedReader); } catch (IOException e) { fail("mockRequest threw an exception: " + e.getMessage()); } return httpServletRequest; } private static String readBody(HttpServletRequest request) { try { return request.getReader().lines().collect(joining(System.lineSeparator())); } catch (IOException e) { throw new RuntimeException("unexpected failure", e); } } }
8,582
41.701493
124
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/web/requestid/HttpRequestIdModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.web.requestid; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class HttpRequestIdModuleTest { private final HttpRequestIdModule underTest = new HttpRequestIdModule(); @Test public void count_components_in_module() { ListContainer container = new ListContainer(); underTest.configure(container); assertThat(container.getAddedObjects()).hasSize(3); } }
1,339
35.216216
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/web/requestid/RequestIdConfigurationTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.web.requestid; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class RequestIdConfigurationTest { private RequestIdConfiguration underTest = new RequestIdConfiguration(50); @Test public void getUidGeneratorRenewalCount_returns_value_provided_from_constructor() { assertThat(underTest.getUidGeneratorRenewalCount()).isEqualTo(50); } }
1,267
36.294118
85
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/web/requestid/RequestIdGeneratorImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.platform.web.requestid; import org.junit.Test; import org.sonar.core.util.UuidGenerator; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class RequestIdGeneratorImplTest { private UuidGenerator.WithFixedBase generator1 = increment -> new byte[] {124, 22, 66, 96, 55, 88, 2, 9}; private UuidGenerator.WithFixedBase generator2 = increment -> new byte[] {0, 5, 88, 81, 8, 6, 44, 19}; private UuidGenerator.WithFixedBase generator3 = increment -> new byte[] {126, 9, 35, 76, 2, 1, 2}; private RequestIdGeneratorBase uidGeneratorBase = mock(RequestIdGeneratorBase.class); private IllegalStateException expected = new IllegalStateException("Unexpected third call to createNew"); @Test public void generate_renews_inner_UuidGenerator_instance_every_number_of_calls_to_generate_specified_in_RequestIdConfiguration_supports_2() { when(uidGeneratorBase.createNew()) .thenReturn(generator1) .thenReturn(generator2) .thenReturn(generator3) .thenThrow(expected); RequestIdGeneratorImpl underTest = new RequestIdGeneratorImpl(uidGeneratorBase, new RequestIdConfiguration(2)); assertThat(underTest.generate()).isEqualTo("fBZCYDdYAgk="); // using generator1 assertThat(underTest.generate()).isEqualTo("fBZCYDdYAgk="); // still using generator1 assertThat(underTest.generate()).isEqualTo("AAVYUQgGLBM="); // renewing generator and using generator2 assertThat(underTest.generate()).isEqualTo("AAVYUQgGLBM="); // still using generator2 assertThat(underTest.generate()).isEqualTo("fgkjTAIBAg=="); // renewing generator and using generator3 assertThat(underTest.generate()).isEqualTo("fgkjTAIBAg=="); // using generator3 assertThatThrownBy(() -> { underTest.generate(); // renewing generator and failing }) .isInstanceOf(IllegalStateException.class) .hasMessage(expected.getMessage()); } @Test public void generate_renews_inner_UuidGenerator_instance_every_number_of_calls_to_generate_specified_in_RequestIdConfiguration_supports_3() { when(uidGeneratorBase.createNew()) .thenReturn(generator1) .thenReturn(generator2) .thenReturn(generator3) .thenThrow(expected); RequestIdGeneratorImpl underTest = new RequestIdGeneratorImpl(uidGeneratorBase, new RequestIdConfiguration(3)); assertThat(underTest.generate()).isEqualTo("fBZCYDdYAgk="); // using generator1 assertThat(underTest.generate()).isEqualTo("fBZCYDdYAgk="); // still using generator1 assertThat(underTest.generate()).isEqualTo("fBZCYDdYAgk="); // still using generator1 assertThat(underTest.generate()).isEqualTo("AAVYUQgGLBM="); // renewing generator and using it assertThat(underTest.generate()).isEqualTo("AAVYUQgGLBM="); // still using generator2 assertThat(underTest.generate()).isEqualTo("AAVYUQgGLBM="); // still using generator2 assertThat(underTest.generate()).isEqualTo("fgkjTAIBAg=="); // renewing generator and using it assertThat(underTest.generate()).isEqualTo("fgkjTAIBAg=="); // using generator3 assertThat(underTest.generate()).isEqualTo("fgkjTAIBAg=="); // using generator3 assertThatThrownBy(() -> { underTest.generate(); // renewing generator and failing }) .isInstanceOf(IllegalStateException.class) .hasMessage(expected.getMessage()); } }
4,340
47.775281
143
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/plugins/PluginsRiskConsentFilterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.plugins; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.sonar.api.config.Configuration; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.api.web.FilterChain; import org.sonar.api.web.UrlPattern; import org.sonar.core.extension.PluginRiskConsent; import org.sonar.server.user.ThreadLocalUserSession; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.core.config.CorePropertyDefinitions.PLUGINS_RISK_CONSENT; public class PluginsRiskConsentFilterTest { private Configuration configuration; private ThreadLocalUserSession userSession; private HttpRequest request; private HttpResponse response; private FilterChain chain; @Before public void before() { configuration = mock(Configuration.class); when(configuration.get(PLUGINS_RISK_CONSENT)).thenReturn(Optional.of(PluginRiskConsent.REQUIRED.name())); userSession = mock(ThreadLocalUserSession.class); request = mock(HttpRequest.class); response = mock(HttpResponse.class); chain = mock(FilterChain.class); } @Test public void doFilter_givenNoUserSession_dontRedirect() throws Exception { PluginsRiskConsentFilter consentFilter = new PluginsRiskConsentFilter(configuration, userSession); when(userSession.hasSession()).thenReturn(true); consentFilter.doFilter(request, response, chain); verify(response, times(0)).sendRedirect(Mockito.anyString()); } @Test public void doFilter_givenNotLoggedIn_dontRedirect() throws Exception { PluginsRiskConsentFilter consentFilter = new PluginsRiskConsentFilter(configuration, userSession); when(userSession.hasSession()).thenReturn(true); when(userSession.isLoggedIn()).thenReturn(false); consentFilter.doFilter(request, response, chain); verify(response, times(0)).sendRedirect(Mockito.anyString()); } @Test public void doFilter_givenNotLoggedInAndRequired_dontRedirect() throws Exception { PluginsRiskConsentFilter consentFilter = new PluginsRiskConsentFilter(configuration, userSession); when(userSession.hasSession()).thenReturn(true); when(userSession.isLoggedIn()).thenReturn(false); when(configuration.get(PLUGINS_RISK_CONSENT)).thenReturn(Optional.of(PluginRiskConsent.REQUIRED.name())); consentFilter.doFilter(request, response, chain); verify(response, times(0)).sendRedirect(Mockito.anyString()); } @Test public void doFilter_givenNotLoggedInAndConsentAccepted_dontRedirect() throws Exception { PluginsRiskConsentFilter consentFilter = new PluginsRiskConsentFilter(configuration, userSession); when(userSession.hasSession()).thenReturn(true); when(userSession.isLoggedIn()).thenReturn(false); when(configuration.get(PLUGINS_RISK_CONSENT)).thenReturn(Optional.of(PluginRiskConsent.ACCEPTED.name())); consentFilter.doFilter(request, response, chain); verify(response, times(0)).sendRedirect(Mockito.anyString()); } @Test public void doFilter_givenLoggedInNotAdmin_dontRedirect() throws Exception { PluginsRiskConsentFilter consentFilter = new PluginsRiskConsentFilter(configuration, userSession); when(userSession.hasSession()).thenReturn(true); when(userSession.isLoggedIn()).thenReturn(true); when(userSession.isSystemAdministrator()).thenReturn(false); consentFilter.doFilter(request, response, chain); verify(response, times(0)).sendRedirect(Mockito.anyString()); } @Test public void doFilter_givenLoggedInNotAdminAndRequiredConsent_dontRedirect() throws Exception { PluginsRiskConsentFilter consentFilter = new PluginsRiskConsentFilter(configuration, userSession); when(userSession.hasSession()).thenReturn(true); when(userSession.isLoggedIn()).thenReturn(true); when(userSession.isSystemAdministrator()).thenReturn(false); when(configuration.get(PLUGINS_RISK_CONSENT)).thenReturn(Optional.of(PluginRiskConsent.REQUIRED.name())); consentFilter.doFilter(request, response, chain); verify(response, times(0)).sendRedirect(Mockito.anyString()); } @Test public void doFilter_givenLoggedInAdminAndConsentRequired_redirect() throws Exception { PluginsRiskConsentFilter consentFilter = new PluginsRiskConsentFilter(configuration, userSession); when(userSession.hasSession()).thenReturn(true); when(userSession.isLoggedIn()).thenReturn(true); when(userSession.isSystemAdministrator()).thenReturn(true); consentFilter.doFilter(request, response, chain); verify(response, times(1)).sendRedirect(Mockito.anyString()); } @Test public void doFilter_givenLoggedInAdminAndConsentNotRequired_dontRedirect() throws Exception { PluginsRiskConsentFilter consentFilter = new PluginsRiskConsentFilter(configuration, userSession); when(userSession.hasSession()).thenReturn(true); when(userSession.isLoggedIn()).thenReturn(true); when(userSession.isSystemAdministrator()).thenReturn(true); when(configuration.get(PLUGINS_RISK_CONSENT)).thenReturn(Optional.of(PluginRiskConsent.ACCEPTED.name())); consentFilter.doFilter(request, response, chain); verify(response, times(0)).sendRedirect(Mockito.anyString()); } @Test public void doGetPattern_excludesNotEmpty() { PluginsRiskConsentFilter consentFilter = new PluginsRiskConsentFilter(configuration, userSession); UrlPattern urlPattern = consentFilter.doGetPattern(); assertThat(urlPattern.getExclusions()).isNotEmpty(); } }
6,576
36.798851
109
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/project/ProjectQGChangeEventListenerTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.project; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.Supplier; import org.junit.Before; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.api.measures.Metric; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDao; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.SnapshotDao; import org.sonar.db.component.SnapshotDto; import org.sonar.db.event.EventDao; import org.sonar.db.project.ProjectDto; import org.sonar.server.qualitygate.Condition; import org.sonar.server.qualitygate.EvaluatedCondition; import org.sonar.server.qualitygate.EvaluatedQualityGate; import org.sonar.server.qualitygate.QualityGate; import org.sonar.server.qualitygate.changeevent.QGChangeEvent; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class ProjectQGChangeEventListenerTest { private final DbClient dbClient = mock(DbClient.class); private final SnapshotDao snapshotDao = mock(SnapshotDao.class); private final EventDao eventDao = mock(EventDao.class); private final ComponentDao componentDao = mock(ComponentDao.class); private final Configuration projectConfiguration = mock(Configuration.class); private final BranchDto branch = new BranchDto(); private final Condition defaultCondition = new Condition("bugs", Condition.Operator.GREATER_THAN, "10"); private final ProjectQGChangeEventListener underTest = new ProjectQGChangeEventListener(dbClient); private ProjectDto project; private SnapshotDto analysis; @Before public void before() { project = new ProjectDto(); project.setUuid("uuid"); analysis = new SnapshotDto(); when(dbClient.componentDao()).thenReturn(componentDao); when(dbClient.eventDao()).thenReturn(eventDao); when(dbClient.snapshotDao()).thenReturn(snapshotDao); when(dbClient.openSession(false)).thenReturn(mock(DbSession.class)); } @Test public void onIssueChanges_givenEmptyEvent_doNotInteractWithDatabase() { Supplier<Optional<EvaluatedQualityGate>> qualityGateSupplier = Optional::empty; QGChangeEvent qualityGateEvent = new QGChangeEvent(project, branch, analysis, projectConfiguration, Metric.Level.OK, qualityGateSupplier); underTest.onIssueChanges(qualityGateEvent, Set.of()); verifyNoInteractions(dbClient); } @Test public void onIssueChanges_givenEventWithNoPreviousStatus_doNotInteractWithDatabase() { EvaluatedQualityGate value = EvaluatedQualityGate.newBuilder() .setQualityGate(createDefaultQualityGate()) .addEvaluatedCondition(createEvaluatedCondition()) .setStatus(Metric.Level.ERROR) .build(); Supplier<Optional<EvaluatedQualityGate>> qualityGateSupplier = () -> Optional.of(value); QGChangeEvent qualityGateEvent = new QGChangeEvent(project, branch, analysis, projectConfiguration, null, qualityGateSupplier); underTest.onIssueChanges(qualityGateEvent, Set.of()); verifyNoInteractions(dbClient); } @Test public void onIssueChanges_givenCurrentStatusTheSameAsPrevious_doNotInteractWithDatabase() { EvaluatedQualityGate value = EvaluatedQualityGate.newBuilder() .setQualityGate(createDefaultQualityGate()) .addEvaluatedCondition(createEvaluatedCondition()) .setStatus(Metric.Level.ERROR) .build(); Supplier<Optional<EvaluatedQualityGate>> qualityGateSupplier = () -> Optional.of(value); QGChangeEvent qualityGateEvent = new QGChangeEvent(project, branch, analysis, projectConfiguration, Metric.Level.ERROR, qualityGateSupplier); underTest.onIssueChanges(qualityGateEvent, Set.of()); verifyNoInteractions(dbClient); } @Test public void onIssueChanges_whenValidEvent_insertEventAndSnapshotToDatabase() { EvaluatedQualityGate value = EvaluatedQualityGate.newBuilder() .setQualityGate(createDefaultQualityGate()) .addEvaluatedCondition(createEvaluatedCondition()) .setStatus(Metric.Level.OK) .build(); Supplier<Optional<EvaluatedQualityGate>> qualityGateSupplier = () -> Optional.of(value); QGChangeEvent qualityGateEvent = new QGChangeEvent(project, branch, analysis, projectConfiguration, Metric.Level.ERROR, qualityGateSupplier); ComponentDto projectComponentDto = new ComponentDto(); projectComponentDto.setQualifier("TRK"); projectComponentDto.setUuid("uuid"); when(componentDao.selectByBranchUuid(anyString(), any())).thenReturn(List.of(projectComponentDto)); underTest.onIssueChanges(qualityGateEvent, Set.of()); verify(eventDao, times(1)).insert(any(), any()); verify(snapshotDao, times(1)).insert(any(DbSession.class), any(SnapshotDto.class)); } private EvaluatedCondition createEvaluatedCondition() { return new EvaluatedCondition(defaultCondition, EvaluatedCondition.EvaluationStatus.ERROR, "5"); } private QualityGate createDefaultQualityGate() { return new QualityGate("id", "name", Set.of(defaultCondition)); } }
6,186
38.407643
145
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/qualitygate/ProjectsInWarningDaemonTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.qualitygate; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.measures.Metric; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.System2; import org.sonar.api.utils.log.LoggerLevel; import org.sonar.db.DbTester; import org.sonar.db.component.ProjectData; import org.sonar.db.metric.MetricDto; import org.sonar.server.es.EsTester; import org.sonar.server.measure.index.ProjectMeasuresIndex; import org.sonar.server.measure.index.ProjectMeasuresIndexer; import org.sonar.server.permission.index.PermissionIndexerTester; import org.sonar.server.permission.index.WebAuthorizationTypeSupport; import org.sonar.server.util.GlobalLockManager; import org.sonar.server.util.GlobalLockManagerImpl; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.measures.Metric.Level.WARN; import static org.sonar.db.measure.MeasureTesting.newLiveMeasure; import static org.sonar.server.qualitygate.ProjectsInWarningDaemon.PROJECTS_IN_WARNING_INTERNAL_PROPERTY; public class ProjectsInWarningDaemonTest { @Rule public DbTester db = DbTester.create(); @Rule public EsTester es = EsTester.create(); @Rule public LogTester logger = new LogTester().setLevel(LoggerLevel.DEBUG); private final PermissionIndexerTester authorizationIndexerTester = new PermissionIndexerTester(es, new ProjectMeasuresIndexer(db.getDbClient(), es.client())); private final ProjectMeasuresIndexer projectMeasuresIndexer = new ProjectMeasuresIndexer(db.getDbClient(), es.client()); private final ProjectMeasuresIndex projectMeasuresIndex = new ProjectMeasuresIndex(es.client(), new WebAuthorizationTypeSupport(null), System2.INSTANCE); private final MapSettings settings = new MapSettings(); private final GlobalLockManager lockManager = mock(GlobalLockManagerImpl.class); private final ProjectsInWarning projectsInWarning = new ProjectsInWarning(); private final ProjectsInWarningDaemon underTest = new ProjectsInWarningDaemon(db.getDbClient(), projectMeasuresIndex, settings.asConfig(), lockManager, projectsInWarning); @Before public void setUp() { settings.setProperty("sonar.projectsInWarning.frequencyInMilliseconds", "100"); } @After public void tearDown() { underTest.stop(); } @Test public void store_projects_in_warning() throws InterruptedException { allowLockToBeAcquired(); MetricDto qualityGateStatus = insertQualityGateStatusMetric(); insertProjectInWarning(qualityGateStatus); insertProjectInWarning(qualityGateStatus); // Setting does not exist assertThat(db.getDbClient().internalPropertiesDao().selectByKey(db.getSession(), PROJECTS_IN_WARNING_INTERNAL_PROPERTY)).isEmpty(); underTest.notifyStart(); assertProjectsInWarningValue(2L); assertThat(logger.logs(Level.INFO)).contains("Counting number of projects in warning is enabled."); } @Test public void update_projects_in_warning_when_new_project_in_warning() throws InterruptedException { allowLockToBeAcquired(); MetricDto qualityGateStatus = insertQualityGateStatusMetric(); insertProjectInWarning(qualityGateStatus); insertProjectInWarning(qualityGateStatus); // Setting does not exist assertThat(db.getDbClient().internalPropertiesDao().selectByKey(db.getSession(), PROJECTS_IN_WARNING_INTERNAL_PROPERTY)).isEmpty(); underTest.notifyStart(); // Add a project in warning after the start in order to let the thread do his job insertProjectInWarning(qualityGateStatus); assertProjectsInWarningValue(3L); assertThat(logger.logs(Level.INFO)).contains("Counting number of projects in warning is enabled."); } @Test public void stop_thread_when_number_of_projects_in_warning_reach_zero() throws InterruptedException { allowLockToBeAcquired(); MetricDto qualityGateStatus = insertQualityGateStatusMetric(); ProjectData project = insertProjectInWarning(qualityGateStatus); underTest.notifyStart(); assertProjectsInWarningValue(1L); // Set quality gate status of the project to OK => No more projects in warning db.getDbClient().liveMeasureDao().insertOrUpdate(db.getSession(), newLiveMeasure(project.getMainBranchComponent(), qualityGateStatus).setData(Metric.Level.OK.name()).setValue(null)); db.commit(); projectMeasuresIndexer.indexOnAnalysis(project.mainBranchUuid()); assertProjectsInWarningValue(0L); assertThat(logger.logs(Level.INFO)) .contains( "Counting number of projects in warning is enabled.", "Counting number of projects in warning will be disabled as there are no more projects in warning."); } @Test public void update_internal_properties_when_already_exits_and_projects_in_warnings_more_than_zero() throws InterruptedException { allowLockToBeAcquired(); MetricDto qualityGateStatus = insertQualityGateStatusMetric(); insertProjectInWarning(qualityGateStatus); insertProjectInWarning(qualityGateStatus); // Setting contains 10, it should be updated with new value db.getDbClient().internalPropertiesDao().save(db.getSession(), PROJECTS_IN_WARNING_INTERNAL_PROPERTY, "10"); db.commit(); underTest.notifyStart(); assertProjectsInWarningValue(2L); assertThat(logger.logs(Level.INFO)).contains("Counting number of projects in warning is enabled."); } @Test public void store_zero_projects_in_warning_when_no_projects() throws InterruptedException { allowLockToBeAcquired(); assertThat(db.getDbClient().internalPropertiesDao().selectByKey(db.getSession(), PROJECTS_IN_WARNING_INTERNAL_PROPERTY)).isEmpty(); underTest.notifyStart(); assertProjectsInWarningValue(0L); assertThat(logger.logs(Level.INFO)).contains("Counting number of projects in warning is enabled."); } @Test public void do_not_compute_projects_in_warning_when_internal_property_is_zero() throws InterruptedException { allowLockToBeAcquired(); MetricDto qualityGateStatus = insertQualityGateStatusMetric(); insertProjectInWarning(qualityGateStatus); // Setting contains 0, even if there are projects in warning it will stay 0 (as it's not possible to have new projects in warning) db.getDbClient().internalPropertiesDao().save(db.getSession(), PROJECTS_IN_WARNING_INTERNAL_PROPERTY, "0"); db.commit(); underTest.notifyStart(); assertProjectsInWarningValue(0L); assertThat(logger.logs(Level.INFO)).contains("Counting number of projects in warning is not started as there are no projects in this situation."); } @Test public void do_not_store_projects_in_warning_in_db_when_cannot_acquire_lock() throws InterruptedException { when(lockManager.tryLock(any(), anyInt())).thenReturn(false); MetricDto qualityGateStatus = insertQualityGateStatusMetric(); insertProjectInWarning(qualityGateStatus); underTest.notifyStart(); waitForValueToBeComputed(1L); assertThat(projectsInWarning.count()).isOne(); assertThat(countNumberOfProjectsInWarning()).isZero(); } private void waitForValueToBeComputed(long expectedValue) throws InterruptedException { for (int i = 0; i < 1000; i++) { if (projectsInWarning.isInitialized() && projectsInWarning.count() == expectedValue) { break; } Thread.sleep(100); } } private void assertProjectsInWarningValue(long expectedValue) throws InterruptedException { waitForValueToBeComputed(expectedValue); assertThat(projectsInWarning.count()).isEqualTo(expectedValue); assertThat(countNumberOfProjectsInWarning()).isEqualTo(expectedValue); } private long countNumberOfProjectsInWarning() { return db.getDbClient().internalPropertiesDao().selectByKey(db.getSession(), PROJECTS_IN_WARNING_INTERNAL_PROPERTY) .map(Long::valueOf) .orElse(0L); } private ProjectData insertProjectInWarning(MetricDto qualityGateStatus) { ProjectData project = db.components().insertPrivateProject(); db.measures().insertLiveMeasure(project, qualityGateStatus, lm -> lm.setData(WARN.name()).setValue(null)); authorizationIndexerTester.allowOnlyAnyone(project.getProjectDto()); projectMeasuresIndexer.indexOnAnalysis(project.mainBranchUuid()); return project; } private MetricDto insertQualityGateStatusMetric() { return db.measures().insertMetric(m -> m.setKey(CoreMetrics.ALERT_STATUS_KEY).setValueType(Metric.ValueType.LEVEL.name())); } private void allowLockToBeAcquired() { when(lockManager.tryLock(any(), anyInt())).thenReturn(true); } }
9,744
41.741228
173
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/qualitygate/ProjectsInWarningModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.qualitygate; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class ProjectsInWarningModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new ProjectsInWarningModule().configure(container); assertThat(container.getAddedObjects()).hasSize(2); } }
1,282
35.657143
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/rule/AdvancedRuleDescriptionSectionsGeneratorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.rule; import java.util.List; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.sonar.api.server.rule.Context; import org.sonar.api.server.rule.RuleDescriptionSection; import org.sonar.api.server.rule.RuleDescriptionSectionBuilder; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.core.util.UuidFactory; import org.sonar.db.rule.RuleDescriptionSectionContextDto; import org.sonar.db.rule.RuleDescriptionSectionDto; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.HOW_TO_FIX_SECTION_KEY; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.RESOURCES_SECTION_KEY; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.ROOT_CAUSE_SECTION_KEY; @RunWith(MockitoJUnitRunner.class) public class AdvancedRuleDescriptionSectionsGeneratorTest { private static final String UUID_1 = "uuid1"; private static final String UUID_2 = "uuid2"; private static final String HTML_CONTENT = "html content"; private static final RuleDescriptionSection SECTION_1 = new RuleDescriptionSectionBuilder().sectionKey(HOW_TO_FIX_SECTION_KEY).htmlContent(HTML_CONTENT).build(); private static final RuleDescriptionSection SECTION_2 = new RuleDescriptionSectionBuilder().sectionKey(ROOT_CAUSE_SECTION_KEY).htmlContent(HTML_CONTENT + "2").build(); private static final Context CONTEXT_1 = new Context("ctx_1", "ctx 1 display name"); private static final RuleDescriptionSection SECTION_3_WITH_CTX_1 = new RuleDescriptionSectionBuilder() .sectionKey(RESOURCES_SECTION_KEY) .htmlContent(HTML_CONTENT) .context(CONTEXT_1) .build(); private static final Context CONTEXT_2 = new Context("ctx_2", "ctx 2 display name"); private static final RuleDescriptionSection SECTION_3_WITH_CTX_2 = new RuleDescriptionSectionBuilder() .sectionKey(RESOURCES_SECTION_KEY) .htmlContent(HTML_CONTENT + "2") .context(CONTEXT_2) .build(); private static final RuleDescriptionSectionDto EXPECTED_SECTION_1 = RuleDescriptionSectionDto.builder().uuid(UUID_1).key(HOW_TO_FIX_SECTION_KEY).content(HTML_CONTENT).build(); private static final RuleDescriptionSectionDto EXPECTED_SECTION_2 = RuleDescriptionSectionDto.builder().uuid(UUID_2).key(ROOT_CAUSE_SECTION_KEY) .content(HTML_CONTENT + "2").build(); private static final RuleDescriptionSectionDto EXPECTED_SECTION_3_WITH_CTX_1 = RuleDescriptionSectionDto.builder() .uuid(UUID_1) .key(SECTION_3_WITH_CTX_1.getKey()) .content(SECTION_3_WITH_CTX_1.getHtmlContent()) .context(RuleDescriptionSectionContextDto.of(CONTEXT_1.getKey(), CONTEXT_1.getDisplayName())) .build(); private static final RuleDescriptionSectionDto EXPECTED_SECTION_3_WITH_CTX_2 = RuleDescriptionSectionDto.builder() .uuid(UUID_2) .key(SECTION_3_WITH_CTX_2.getKey()) .content(SECTION_3_WITH_CTX_2.getHtmlContent()) .context(RuleDescriptionSectionContextDto.of(CONTEXT_2.getKey(), CONTEXT_2.getDisplayName())) .build(); @Mock private UuidFactory uuidFactory; @Mock private RulesDefinition.Rule rule; @Mock private RuleDescriptionSectionDto LEGACY_SECTION; @Mock private LegacyIssueRuleDescriptionSectionsGenerator legacyIssueRuleDescriptionSectionsGenerator; @InjectMocks private AdvancedRuleDescriptionSectionsGenerator generator; @Before public void before() { when(uuidFactory.create()).thenReturn(UUID_1).thenReturn(UUID_2); when(legacyIssueRuleDescriptionSectionsGenerator.generateSections(rule)).thenReturn(Set.of(LEGACY_SECTION)); } @Test public void generateSections_whenOneSection_createsOneSectionAndDefault() { when(rule.ruleDescriptionSections()).thenReturn(List.of(SECTION_1)); Set<RuleDescriptionSectionDto> ruleDescriptionSectionDtos = generator.generateSections(rule); assertThat(ruleDescriptionSectionDtos) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder(EXPECTED_SECTION_1, LEGACY_SECTION); } @Test public void generateSections_whenTwoSections_createsTwoSectionsAndDefault() { when(rule.ruleDescriptionSections()).thenReturn(List.of(SECTION_1, SECTION_2)); Set<RuleDescriptionSectionDto> ruleDescriptionSectionDtos = generator.generateSections(rule); assertThat(ruleDescriptionSectionDtos) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder(EXPECTED_SECTION_1, EXPECTED_SECTION_2, LEGACY_SECTION); } @Test public void generateSections_whenTwoContextSpecificSections_createsTwoSectionsAndDefault() { when(rule.ruleDescriptionSections()).thenReturn(List.of(SECTION_3_WITH_CTX_1, SECTION_3_WITH_CTX_2)); Set<RuleDescriptionSectionDto> ruleDescriptionSectionDtos = generator.generateSections(rule); assertThat(ruleDescriptionSectionDtos) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder(EXPECTED_SECTION_3_WITH_CTX_1, EXPECTED_SECTION_3_WITH_CTX_2, LEGACY_SECTION); } @Test public void generateSections_whenContextSpecificSectionsAndNonContextSpecificSection_createsTwoSectionsAndDefault() { when(rule.ruleDescriptionSections()).thenReturn(List.of(SECTION_1, SECTION_3_WITH_CTX_2)); Set<RuleDescriptionSectionDto> ruleDescriptionSectionDtos = generator.generateSections(rule); assertThat(ruleDescriptionSectionDtos) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrder(EXPECTED_SECTION_1, EXPECTED_SECTION_3_WITH_CTX_2, LEGACY_SECTION); } @Test public void generateSections_whenNoSections_returnsDefault() { when(rule.ruleDescriptionSections()).thenReturn(emptyList()); Set<RuleDescriptionSectionDto> ruleDescriptionSectionDtos = generator.generateSections(rule); assertThat(ruleDescriptionSectionDtos).containsOnly(LEGACY_SECTION); } }
7,020
42.07362
177
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/rule/LegacyHotspotRuleDescriptionSectionsGeneratorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.rule; import java.util.Map; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.core.util.UuidFactory; import org.sonar.db.rule.RuleDescriptionSectionDto; import org.sonar.markdown.Markdown; import static java.util.stream.Collectors.toMap; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.ASSESS_THE_PROBLEM_SECTION_KEY; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.HOW_TO_FIX_SECTION_KEY; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.ROOT_CAUSE_SECTION_KEY; public class LegacyHotspotRuleDescriptionSectionsGeneratorTest { /* * Bunch of static constant to create rule description. */ private static final String DESCRIPTION = "<p>The use of operators pairs ( <code>=+</code>, <code>=-</code> or <code>=!</code> ) where the reversed, single operator was meant (<code>+=</code>,\n" + "<code>-=</code> or <code>!=</code>) will compile and run, but not produce the expected results.</p>\n" + "<p>This rule raises an issue when <code>=+</code>, <code>=-</code>, or <code>=!</code> is used without any spacing between the two operators and when\n" + "there is at least one whitespace character after.</p>\n"; private static final String NONCOMPLIANTCODE = "<h2>Noncompliant Code Example</h2>\n" + "<pre>Integer target = -5;\n" + "Integer num = 3;\n" + "\n" + "target =- num; // Noncompliant; target = -3. Is that really what's meant?\n" + "target =+ num; // Noncompliant; target = 3\n" + "</pre>\n"; private static final String COMPLIANTCODE = "<h2>Compliant Solution</h2>\n" + "<pre>Integer target = -5;\n" + "Integer num = 3;\n" + "\n" + "target = -num; // Compliant; intent to assign inverse value of num is clear\n" + "target += num;\n" + "</pre>\n"; private static final String SEE = "<h2>See</h2>\n" + "<ul>\n" + " <li> <a href=\"https://cwe.mitre.org/data/definitions/352.html\">MITRE, CWE-352</a> - Cross-Site Request Forgery (CSRF) </li>\n" + " <li> <a href=\"https://www.owasp.org/index.php/Top_10-2017_A6-Security_Misconfiguration\">OWASP Top 10 2017 Category A6</a> - Security\n" + " Misconfiguration </li>\n" + " <li> <a href=\"https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29\">OWASP: Cross-Site Request Forgery</a> </li>\n" + " <li> <a href=\"https://www.sans.org/top25-software-errors/#cat1\">SANS Top 25</a> - Insecure Interaction Between Components </li>\n" + " <li> Derived from FindSecBugs rule <a href=\"https://find-sec-bugs.github.io/bugs.htm#SPRING_CSRF_PROTECTION_DISABLED\">SPRING_CSRF_PROTECTION_DISABLED</a> </li>\n" + " <li> <a href=\"https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#when-to-use-csrf-protection\">Spring Security\n" + " Official Documentation: When to use CSRF protection</a> </li>\n" + "</ul>\n"; private static final String RECOMMENTEDCODINGPRACTICE = "<h2>Recommended Secure Coding Practices</h2>\n" + "<ul>\n" + " <li> activate Spring Security's CSRF protection. </li>\n" + "</ul>\n"; private static final String ASKATRISK = "<h2>Ask Yourself Whether</h2>\n" + "<ul>\n" + " <li> Any URLs responding with <code>Access-Control-Allow-Origin: *</code> include sensitive content. </li>\n" + " <li> Any domains specified in <code>Access-Control-Allow-Origin</code> headers are checked against a whitelist. </li>\n" + "</ul>\n"; private static final String SENSITIVECODE = "<h2>Sensitive Code Example</h2>\n" + "<pre>\n" + "// === Java Servlet ===\n" + "@Override\n" + "protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {\n" + " resp.setHeader(\"Content-Type\", \"text/plain; charset=utf-8\");\n" + " resp.setHeader(\"Access-Control-Allow-Origin\", \"http://localhost:8080\"); // Questionable\n" + " resp.setHeader(\"Access-Control-Allow-Credentials\", \"true\"); // Questionable\n" + " resp.setHeader(\"Access-Control-Allow-Methods\", \"GET\"); // Questionable\n" + " resp.getWriter().write(\"response\");\n" + "}\n" + "</pre>\n" + "<pre>\n" + "// === Spring MVC Controller annotation ===\n" + "@CrossOrigin(origins = \"http://domain1.com\") // Questionable\n" + "@RequestMapping(\"\")\n" + "public class TestController {\n" + " public String home(ModelMap model) {\n" + " model.addAttribute(\"message\", \"ok \");\n" + " return \"view\";\n" + " }\n" + "\n" + " @CrossOrigin(origins = \"http://domain2.com\") // Questionable\n" + " @RequestMapping(value = \"/test1\")\n" + " public ResponseEntity&lt;String&gt; test1() {\n" + " return ResponseEntity.ok().body(\"ok\");\n" + " }\n" + "}\n" + "</pre>\n"; private static final String DEFAULT_SECTION_KEY = "default"; private final UuidFactory uuidFactory = mock(UuidFactory.class); private final RulesDefinition.Rule rule = mock(RulesDefinition.Rule.class); private final LegacyHotspotRuleDescriptionSectionsGenerator generator = new LegacyHotspotRuleDescriptionSectionsGenerator(uuidFactory); @Before public void setUp() { when(rule.htmlDescription()).thenReturn(null); when(rule.markdownDescription()).thenReturn(null); } @Test public void parse_returns_all_empty_fields_when_no_description() { when(rule.htmlDescription()).thenReturn(null); Set<RuleDescriptionSectionDto> results = generator.generateSections(rule); assertThat(results).isEmpty(); } @Test public void parse_returns_all_empty_fields_when_empty_description() { when(rule.htmlDescription()).thenReturn(""); Set<RuleDescriptionSectionDto> results = generator.generateSections(rule); assertThat(results).isEmpty(); } @Test public void parse_to_risk_description_fields_when_desc_contains_no_section() { String descriptionWithoutTitles = "description without titles"; when(rule.htmlDescription()).thenReturn(descriptionWithoutTitles); Set<RuleDescriptionSectionDto> results = generator.generateSections(rule); Map<String, String> sectionKeyToContent = results.stream().collect(toMap(RuleDescriptionSectionDto::getKey, RuleDescriptionSectionDto::getContent)); assertThat(sectionKeyToContent).hasSize(2) .containsEntry(ROOT_CAUSE_SECTION_KEY, descriptionWithoutTitles) .containsEntry(DEFAULT_SECTION_KEY, rule.htmlDescription()); } @Test public void parse_return_null_risk_when_desc_starts_with_ask_yourself_title() { when(rule.htmlDescription()).thenReturn(ASKATRISK + RECOMMENTEDCODINGPRACTICE); Set<RuleDescriptionSectionDto> results = generator.generateSections(rule); Map<String, String> sectionKeyToContent = results.stream().collect(toMap(RuleDescriptionSectionDto::getKey, RuleDescriptionSectionDto::getContent)); assertThat(sectionKeyToContent).hasSize(3) .containsEntry(DEFAULT_SECTION_KEY, rule.htmlDescription()) .containsEntry(ASSESS_THE_PROBLEM_SECTION_KEY, ASKATRISK) .containsEntry(HOW_TO_FIX_SECTION_KEY, RECOMMENTEDCODINGPRACTICE); } @Test public void parse_return_null_vulnerable_when_no_ask_yourself_whether_title() { when(rule.htmlDescription()).thenReturn(DESCRIPTION + RECOMMENTEDCODINGPRACTICE); Set<RuleDescriptionSectionDto> results = generator.generateSections(rule); Map<String, String> sectionKeyToContent = results.stream().collect(toMap(RuleDescriptionSectionDto::getKey, RuleDescriptionSectionDto::getContent)); assertThat(sectionKeyToContent).hasSize(3) .containsEntry(DEFAULT_SECTION_KEY, rule.htmlDescription()) .containsEntry(ROOT_CAUSE_SECTION_KEY, DESCRIPTION) .containsEntry(HOW_TO_FIX_SECTION_KEY, RECOMMENTEDCODINGPRACTICE); } @Test public void parse_return_null_fixIt_when_desc_has_no_Recommended_Secure_Coding_Practices_title() { when(rule.htmlDescription()).thenReturn(DESCRIPTION + ASKATRISK); Set<RuleDescriptionSectionDto> results = generator.generateSections(rule); Map<String, String> sectionKeyToContent = results.stream().collect(toMap(RuleDescriptionSectionDto::getKey, RuleDescriptionSectionDto::getContent)); assertThat(sectionKeyToContent).hasSize(3) .containsEntry(DEFAULT_SECTION_KEY, rule.htmlDescription()) .containsEntry(ROOT_CAUSE_SECTION_KEY, DESCRIPTION) .containsEntry(ASSESS_THE_PROBLEM_SECTION_KEY, ASKATRISK); } @Test public void parse_with_noncompliant_section_not_removed() { when(rule.htmlDescription()).thenReturn(DESCRIPTION + NONCOMPLIANTCODE + COMPLIANTCODE); Set<RuleDescriptionSectionDto> results = generator.generateSections(rule); Map<String, String> sectionKeyToContent = results.stream().collect(toMap(RuleDescriptionSectionDto::getKey, RuleDescriptionSectionDto::getContent)); assertThat(sectionKeyToContent).hasSize(4) .containsEntry(DEFAULT_SECTION_KEY, rule.htmlDescription()) .containsEntry(ROOT_CAUSE_SECTION_KEY, DESCRIPTION) .containsEntry(ASSESS_THE_PROBLEM_SECTION_KEY, NONCOMPLIANTCODE) .containsEntry(HOW_TO_FIX_SECTION_KEY, COMPLIANTCODE); } @Test public void parse_moved_noncompliant_code() { when(rule.htmlDescription()).thenReturn(DESCRIPTION + RECOMMENTEDCODINGPRACTICE + NONCOMPLIANTCODE + SEE); Set<RuleDescriptionSectionDto> results = generator.generateSections(rule); Map<String, String> sectionKeyToContent = results.stream().collect(toMap(RuleDescriptionSectionDto::getKey, RuleDescriptionSectionDto::getContent)); assertThat(sectionKeyToContent).hasSize(4) .containsEntry(DEFAULT_SECTION_KEY, rule.htmlDescription()) .containsEntry(ROOT_CAUSE_SECTION_KEY, DESCRIPTION) .containsEntry(ASSESS_THE_PROBLEM_SECTION_KEY, NONCOMPLIANTCODE) .containsEntry(HOW_TO_FIX_SECTION_KEY, RECOMMENTEDCODINGPRACTICE + SEE); } @Test public void parse_moved_sensitivecode_code() { when(rule.htmlDescription()).thenReturn(DESCRIPTION + ASKATRISK + RECOMMENTEDCODINGPRACTICE + SENSITIVECODE + SEE); Set<RuleDescriptionSectionDto> results = generator.generateSections(rule); Map<String, String> sectionKeyToContent = results.stream().collect(toMap(RuleDescriptionSectionDto::getKey, RuleDescriptionSectionDto::getContent)); assertThat(sectionKeyToContent).hasSize(4) .containsEntry(DEFAULT_SECTION_KEY, rule.htmlDescription()) .containsEntry(ROOT_CAUSE_SECTION_KEY, DESCRIPTION) .containsEntry(ASSESS_THE_PROBLEM_SECTION_KEY, ASKATRISK + SENSITIVECODE) .containsEntry(HOW_TO_FIX_SECTION_KEY, RECOMMENTEDCODINGPRACTICE + SEE); } @Test public void parse_md_rule_description() { String ruleDescription = "This is the custom rule description"; String exceptionsContent = "This the exceptions section content"; String askContent = "This is the ask section content"; String recommendedContent = "This is the recommended section content"; when(rule.markdownDescription()).thenReturn(ruleDescription + "\n" + "== Exceptions" + "\n" + exceptionsContent + "\n" + "== Ask Yourself Whether" + "\n" + askContent + "\n" + "== Recommended Secure Coding Practices" + "\n" + recommendedContent + "\n"); Set<RuleDescriptionSectionDto> results = generator.generateSections(rule); Map<String, String> sectionKeyToContent = results.stream().collect(toMap(RuleDescriptionSectionDto::getKey, RuleDescriptionSectionDto::getContent)); assertThat(sectionKeyToContent).hasSize(4) .containsEntry(DEFAULT_SECTION_KEY, Markdown.convertToHtml(rule.markdownDescription())) .containsEntry(ROOT_CAUSE_SECTION_KEY, ruleDescription + "<br/>" + "<h2>Exceptions</h2>" + exceptionsContent + "<br/>") .containsEntry(ASSESS_THE_PROBLEM_SECTION_KEY,"<h2>Ask Yourself Whether</h2>" + askContent + "<br/>") .containsEntry(HOW_TO_FIX_SECTION_KEY, "<h2>Recommended Secure Coding Practices</h2>" + recommendedContent + "<br/>"); } }
13,081
53.508333
180
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/rule/RegisterRulesTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.rule; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.elasticsearch.common.util.set.Sets; import org.jetbrains.annotations.Nullable; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.resources.Language; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleScope; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rules.RuleType; import org.sonar.api.server.debt.DebtRemediationFunction; import org.sonar.api.server.rule.Context; import org.sonar.api.server.rule.RuleDescriptionSection; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.api.utils.DateUtils; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.core.util.UuidFactory; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.qualityprofile.ActiveRuleDto; import org.sonar.db.qualityprofile.QProfileChangeDto; import org.sonar.db.qualityprofile.QProfileChangeQuery; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.rule.DeprecatedRuleKeyDto; import org.sonar.db.rule.RuleDescriptionSectionContextDto; import org.sonar.db.rule.RuleDescriptionSectionDto; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleDto.Scope; import org.sonar.db.rule.RuleParamDto; import org.sonar.db.rule.RuleRepositoryDto; import org.sonar.server.es.EsTester; import org.sonar.server.es.SearchIdResult; import org.sonar.server.es.SearchOptions; import org.sonar.server.es.metadata.MetadataIndex; import org.sonar.server.plugins.ServerPluginRepository; import org.sonar.server.qualityprofile.ActiveRuleChange; import org.sonar.server.qualityprofile.QProfileRules; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.rule.index.RuleIndex; import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.rule.index.RuleQuery; import static com.google.common.collect.Sets.newHashSet; import static java.lang.String.format; import static java.lang.String.valueOf; import static java.util.Collections.emptySet; import static java.util.Collections.singletonList; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.sonar.api.rule.RuleStatus.READY; import static org.sonar.api.rule.RuleStatus.REMOVED; import static org.sonar.api.rule.Severity.BLOCKER; import static org.sonar.api.rule.Severity.INFO; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.ASSESS_THE_PROBLEM_SECTION_KEY; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.HOW_TO_FIX_SECTION_KEY; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.RESOURCES_SECTION_KEY; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.ROOT_CAUSE_SECTION_KEY; import static org.sonar.api.server.rule.RulesDefinition.NewRepository; import static org.sonar.api.server.rule.RulesDefinition.NewRule; import static org.sonar.api.server.rule.RulesDefinition.OwaspTop10; import static org.sonar.api.server.rule.RulesDefinition.OwaspTop10Version.Y2021; import static org.sonar.db.rule.RuleDescriptionSectionDto.DEFAULT_KEY; import static org.sonar.db.rule.RuleDescriptionSectionDto.builder; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; import static org.sonar.server.qualityprofile.ActiveRuleChange.Type.DEACTIVATED; @RunWith(DataProviderRunner.class) public class RegisterRulesTest { private static final String FAKE_PLUGIN_KEY = "unittest"; private static final Date DATE1 = DateUtils.parseDateTime("2014-01-01T19:10:03+0100"); private static final Date DATE2 = DateUtils.parseDateTime("2014-02-01T12:10:03+0100"); private static final Date DATE3 = DateUtils.parseDateTime("2014-03-01T12:10:03+0100"); private static final RuleKey EXTERNAL_RULE_KEY1 = RuleKey.of("external_eslint", "rule1"); private static final RuleKey EXTERNAL_HOTSPOT_RULE_KEY = RuleKey.of("external_eslint", "hotspot"); private static final RuleKey RULE_KEY1 = RuleKey.of("fake", "rule1"); private static final RuleKey RULE_KEY2 = RuleKey.of("fake", "rule2"); private static final RuleKey RULE_KEY3 = RuleKey.of("fake", "rule3"); private static final RuleKey HOTSPOT_RULE_KEY = RuleKey.of("fake", "hotspot"); private final TestSystem2 system = new TestSystem2().setNow(DATE1.getTime()); @org.junit.Rule public DbTester db = DbTester.create(system); @org.junit.Rule public EsTester es = EsTester.create(); @org.junit.Rule public LogTester logTester = new LogTester(); private final QProfileRules qProfileRules = mock(QProfileRules.class); private final WebServerRuleFinder webServerRuleFinder = mock(WebServerRuleFinder.class); private final DbClient dbClient = db.getDbClient(); private final MetadataIndex metadataIndex = mock(MetadataIndex.class); private final UuidFactory uuidFactory = UuidFactoryFast.getInstance(); private RuleIndexer ruleIndexer; private ActiveRuleIndexer activeRuleIndexer; private RuleIndex ruleIndex; private final RuleDescriptionSectionsGenerator ruleDescriptionSectionsGenerator = mock(RuleDescriptionSectionsGenerator.class); private final RuleDescriptionSectionsGeneratorResolver resolver = mock(RuleDescriptionSectionsGeneratorResolver.class); @Before public void before() { ruleIndexer = new RuleIndexer(es.client(), dbClient); ruleIndex = new RuleIndex(es.client(), system); activeRuleIndexer = new ActiveRuleIndexer(dbClient, es.client()); when(resolver.getRuleDescriptionSectionsGenerator(any())).thenReturn(ruleDescriptionSectionsGenerator); when(ruleDescriptionSectionsGenerator.generateSections(any())).thenAnswer(answer -> { RulesDefinition.Rule rule = answer.getArgument(0, RulesDefinition.Rule.class); String description = rule.htmlDescription() == null ? rule.markdownDescription() : rule.htmlDescription(); Set<RuleDescriptionSectionDto> ruleDescriptionSectionDtos = rule.ruleDescriptionSections().stream() // .map(s -> builder() .uuid(UuidFactoryFast.getInstance().create()) .key(s.getKey()) .content(s.getHtmlContent()) .context(s.getContext().map(c -> RuleDescriptionSectionContextDto.of(c.getKey(), c.getDisplayName())).orElse(null)) .build() ) .collect(Collectors.toSet()); return Sets.union(ruleDescriptionSectionDtos, Set.of(builder().uuid(UuidFactoryFast.getInstance().create()).key("default").content(description).build())); }); when(ruleDescriptionSectionsGenerator.isGeneratorForRule(any())).thenReturn(true); } @Test public void insert_new_rules() { execute(new FakeRepositoryV1()); // verify db assertThat(dbClient.ruleDao().selectAll(db.getSession())).hasSize(3); RuleDto rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY1); verifyRule(rule1); assertThat(rule1.isExternal()).isFalse(); assertThat(rule1.getDefRemediationFunction()).isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET.name()); assertThat(rule1.getDefRemediationGapMultiplier()).isEqualTo("5d"); assertThat(rule1.getDefRemediationBaseEffort()).isEqualTo("10h"); RuleDto hotspotRule = dbClient.ruleDao().selectOrFailByKey(db.getSession(), HOTSPOT_RULE_KEY); verifyHotspot(hotspotRule); List<RuleParamDto> params = dbClient.ruleDao().selectRuleParamsByRuleKey(db.getSession(), RULE_KEY1); assertThat(params).hasSize(2); RuleParamDto param = getParam(params, "param1"); assertThat(param.getDescription()).isEqualTo("parameter one"); assertThat(param.getDefaultValue()).isEqualTo("default1"); // verify index RuleDto rule2 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY2); assertThat(ruleIndex.search(new RuleQuery(), new SearchOptions()).getUuids()).containsOnly(rule1.getUuid(), rule2.getUuid(), hotspotRule.getUuid()); verifyIndicesMarkedAsInitialized(); // verify repositories assertThat(dbClient.ruleRepositoryDao().selectAll(db.getSession())).extracting(RuleRepositoryDto::getKey).containsOnly("fake"); } private void verifyHotspot(RuleDto hotspotRule) { assertThat(hotspotRule.getName()).isEqualTo("Hotspot"); assertThat(hotspotRule.getDefaultRuleDescriptionSection().getContent()).isEqualTo("Minimal hotspot"); assertThat(hotspotRule.getCreatedAt()).isEqualTo(RegisterRulesTest.DATE1.getTime()); assertThat(hotspotRule.getUpdatedAt()).isEqualTo(RegisterRulesTest.DATE1.getTime()); assertThat(hotspotRule.getType()).isEqualTo(RuleType.SECURITY_HOTSPOT.getDbConstant()); assertThat(hotspotRule.getSecurityStandards()).containsExactly("cwe:1", "cwe:123", "cwe:863", "owaspTop10-2021:a1", "owaspTop10-2021:a3"); } @Test public void insert_new_external_rule() { execute(new ExternalRuleRepository()); // verify db assertThat(dbClient.ruleDao().selectAll(db.getSession())).hasSize(2); RuleDto rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), EXTERNAL_RULE_KEY1); verifyRule(rule1); assertThat(rule1.isExternal()).isTrue(); assertThat(rule1.getDefRemediationFunction()).isNull(); assertThat(rule1.getDefRemediationGapMultiplier()).isNull(); assertThat(rule1.getDefRemediationBaseEffort()).isNull(); RuleDto hotspotRule = dbClient.ruleDao().selectOrFailByKey(db.getSession(), EXTERNAL_HOTSPOT_RULE_KEY); verifyHotspot(hotspotRule); } private void verifyRule(RuleDto rule) { assertThat(rule.getName()).isEqualTo("One"); assertThat(rule.getDefaultRuleDescriptionSection().getContent()).isEqualTo("Description of One"); assertThat(rule.getSeverityString()).isEqualTo(BLOCKER); assertThat(rule.getTags()).isEmpty(); assertThat(rule.getSystemTags()).containsOnly("tag1", "tag2", "tag3"); assertThat(rule.getConfigKey()).isEqualTo("config1"); assertThat(rule.getStatus()).isEqualTo(RuleStatus.BETA); assertThat(rule.getCreatedAt()).isEqualTo(DATE1.getTime()); assertThat(rule.getScope()).isEqualTo(Scope.ALL); assertThat(rule.getUpdatedAt()).isEqualTo(DATE1.getTime()); assertThat(rule.getType()).isEqualTo(RuleType.CODE_SMELL.getDbConstant()); assertThat(rule.getPluginKey()).isEqualTo(FAKE_PLUGIN_KEY); assertThat(rule.isAdHoc()).isFalse(); assertThat(rule.getEducationPrinciples()).containsOnly("concept1", "concept2", "concept3"); } @Test public void insert_then_remove_rule() { String ruleKey = randomAlphanumeric(5); // register one rule execute(context -> { NewRepository repo = context.createRepository("fake", "java"); repo.createRule(ruleKey) .setName(randomAlphanumeric(5)) .setHtmlDescription(randomAlphanumeric(20)); repo.done(); }); // verify db List<RuleDto> rules = dbClient.ruleDao().selectAll(db.getSession()); assertThat(rules) .extracting(RuleDto::getKey) .extracting(RuleKey::rule) .containsExactly(ruleKey); RuleDto rule = rules.iterator().next(); // verify index assertThat(ruleIndex.search(new RuleQuery(), new SearchOptions()).getUuids()) .containsExactly(rule.getUuid()); verifyIndicesMarkedAsInitialized(); // register no rule execute(context -> context.createRepository("fake", "java").done()); // verify db assertThat(dbClient.ruleDao().selectAll(db.getSession())) .extracting(RuleDto::getKey) .extracting(RuleKey::rule) .containsExactly(ruleKey); assertThat(dbClient.ruleDao().selectAll(db.getSession())) .extracting(RuleDto::getStatus) .containsExactly(REMOVED); // verify index assertThat(ruleIndex.search(new RuleQuery(), new SearchOptions()).getUuids()) .isEmpty(); verifyIndicesNotMarkedAsInitialized(); } @Test public void mass_insert_then_remove_rule() { int numberOfRules = 5000; // register many rules execute(context -> { NewRepository repo = context.createRepository("fake", "java"); IntStream.range(0, numberOfRules) .mapToObj(i -> "rule-" + i) .forEach(ruleKey -> repo.createRule(ruleKey) .setName(randomAlphanumeric(20)) .setHtmlDescription(randomAlphanumeric(20))); repo.done(); }); // verify db assertThat(dbClient.ruleDao().selectAll(db.getSession())) .hasSize(numberOfRules) .extracting(RuleDto::getStatus) .containsOnly(READY); // verify index assertThat(es.countDocuments(RuleIndexDefinition.TYPE_RULE)).isEqualTo(numberOfRules); assertThat(ruleIndex.search(new RuleQuery(), new SearchOptions()).getUuids()) .isNotEmpty(); // register no rule execute(context -> context.createRepository("fake", "java").done()); // verify db assertThat(dbClient.ruleDao().selectAll(db.getSession())) .hasSize(numberOfRules) .extracting(RuleDto::getStatus) .containsOnly(REMOVED); // verify index (documents are still in the index, but all are removed) assertThat(es.countDocuments(RuleIndexDefinition.TYPE_RULE)).isEqualTo(numberOfRules); assertThat(ruleIndex.search(new RuleQuery(), new SearchOptions()).getUuids()) .isEmpty(); } @Test public void delete_repositories_that_have_been_uninstalled() { RuleRepositoryDto repository = new RuleRepositoryDto("findbugs", "java", "Findbugs"); DbSession dbSession = db.getSession(); db.getDbClient().ruleRepositoryDao().insert(dbSession, singletonList(repository)); dbSession.commit(); execute(new FakeRepositoryV1()); assertThat(db.getDbClient().ruleRepositoryDao().selectAll(dbSession)).extracting(RuleRepositoryDto::getKey).containsOnly("fake"); } @Test public void update_and_remove_rules_on_changes() { execute(new FakeRepositoryV1()); assertThat(dbClient.ruleDao().selectAll(db.getSession())).hasSize(3); RuleDto rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY1); RuleDto rule2 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY2); RuleDto hotspotRule = dbClient.ruleDao().selectOrFailByKey(db.getSession(), HOTSPOT_RULE_KEY); assertThat(es.getIds(RuleIndexDefinition.TYPE_RULE)).containsOnly(valueOf(rule1.getUuid()), valueOf(rule2.getUuid()), valueOf(hotspotRule.getUuid())); verifyIndicesMarkedAsInitialized(); // user adds tags and sets markdown note rule1.setTags(newHashSet("usertag1", "usertag2")); rule1.setNoteData("user *note*"); rule1.setNoteUserUuid("marius"); dbClient.ruleDao().update(db.getSession(), rule1); db.getSession().commit(); system.setNow(DATE2.getTime()); execute(new FakeRepositoryV2()); verifyIndicesNotMarkedAsInitialized(); // rule1 has been updated rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY1); assertThatRule1IsV2(rule1); List<RuleParamDto> params = dbClient.ruleDao().selectRuleParamsByRuleKey(db.getSession(), RULE_KEY1); assertThat(params).hasSize(2); RuleParamDto param = getParam(params, "param1"); assertThat(param.getDescription()).isEqualTo("parameter one v2"); assertThat(param.getDefaultValue()).isEqualTo("default1 v2"); // rule2 has been removed -> status set to REMOVED but db row is not deleted rule2 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY2); assertThat(rule2.getStatus()).isEqualTo(REMOVED); assertThat(rule2.getUpdatedAt()).isEqualTo(DATE2.getTime()); // rule3 has been created RuleDto rule3 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY3); assertThat(rule3).isNotNull(); assertThat(rule3.getStatus()).isEqualTo(READY); // verify index assertThat(ruleIndex.search(new RuleQuery(), new SearchOptions()).getUuids()).containsOnly(rule1.getUuid(), rule3.getUuid()); // verify repositories assertThat(dbClient.ruleRepositoryDao().selectAll(db.getSession())).extracting(RuleRepositoryDto::getKey).containsOnly("fake"); system.setNow(DATE3.getTime()); execute(new FakeRepositoryV3()); rule3 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY3); assertThat(rule3.getDefaultRuleDescriptionSection().getContent()).isEqualTo("Rule Three V2"); assertThat(rule3.getDescriptionFormat()).isEqualTo(RuleDto.Format.MARKDOWN); } private void assertThatRule1IsV2(RuleDto rule1) { assertThat(rule1.getName()).isEqualTo("One v2"); RuleDescriptionSectionDto defaultRuleDescriptionSection = rule1.getDefaultRuleDescriptionSection(); assertThat(defaultRuleDescriptionSection.getContent()).isEqualTo("Description of One v2"); assertThat(defaultRuleDescriptionSection.getKey()).isEqualTo(DEFAULT_KEY); assertThat(rule1.getDescriptionFormat()).isEqualTo(RuleDto.Format.HTML); assertThat(rule1.getSeverityString()).isEqualTo(INFO); assertThat(rule1.getTags()).containsOnly("usertag1", "usertag2"); assertThat(rule1.getSystemTags()).containsOnly("tag1", "tag4"); assertThat(rule1.getConfigKey()).isEqualTo("config1 v2"); assertThat(rule1.getNoteData()).isEqualTo("user *note*"); assertThat(rule1.getNoteUserUuid()).isEqualTo("marius"); assertThat(rule1.getStatus()).isEqualTo(READY); assertThat(rule1.getType()).isEqualTo(RuleType.BUG.getDbConstant()); assertThat(rule1.getCreatedAt()).isEqualTo(DATE1.getTime()); assertThat(rule1.getUpdatedAt()).isEqualTo(DATE2.getTime()); assertThat(rule1.getEducationPrinciples()).containsOnly("concept1","concept4"); } @Test public void add_new_tag() { execute(context -> { NewRepository repo = context.createRepository("fake", "java"); repo.createRule("rule1") .setName("Rule One") .setHtmlDescription("Description of Rule One") .setTags("tag1"); repo.done(); }); RuleDto rule = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY1); assertThat(rule.getSystemTags()).containsOnly("tag1"); execute(context -> { NewRepository repo = context.createRepository("fake", "java"); repo.createRule("rule1") .setName("Rule One") .setHtmlDescription("Description of Rule One") .setTags("tag1", "tag2"); repo.done(); }); rule = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY1); assertThat(rule.getSystemTags()).containsOnly("tag1", "tag2"); } @Test public void add_new_security_standards() { execute(context -> { NewRepository repo = context.createRepository("fake", "java"); repo.createRule("rule1") .setName("Rule One") .setHtmlDescription("Description of Rule One") .addOwaspTop10(Y2021, OwaspTop10.A1) .addCwe(123); repo.done(); }); RuleDto rule = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY1); assertThat(rule.getSecurityStandards()).containsOnly("cwe:123", "owaspTop10-2021:a1"); execute(context -> { NewRepository repo = context.createRepository("fake", "java"); repo.createRule("rule1") .setName("Rule One") .setHtmlDescription("Description of Rule One") .addOwaspTop10(Y2021, OwaspTop10.A1, OwaspTop10.A3) .addCwe(1, 123, 863); repo.done(); }); rule = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY1); assertThat(rule.getSecurityStandards()).containsOnly("cwe:1", "cwe:123", "cwe:863", "owaspTop10-2021:a1", "owaspTop10-2021:a3"); } @Test public void update_only_rule_name() { system.setNow(DATE1.getTime()); execute(context -> { NewRepository repo = context.createRepository("fake", "java"); repo.createRule("rule") .setName("Name1") .setHtmlDescription("Description"); repo.done(); }); system.setNow(DATE2.getTime()); execute(context -> { NewRepository repo = context.createRepository("fake", "java"); repo.createRule("rule") .setName("Name2") .setHtmlDescription("Description"); repo.done(); }); // rule1 has been updated RuleDto rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RuleKey.of("fake", "rule")); assertThat(rule1.getName()).isEqualTo("Name2"); assertThat(rule1.getDefaultRuleDescriptionSection().getContent()).isEqualTo("Description"); assertThat(ruleIndex.search(new RuleQuery().setQueryText("Name2"), new SearchOptions()).getTotal()).isOne(); assertThat(ruleIndex.search(new RuleQuery().setQueryText("Name1"), new SearchOptions()).getTotal()).isZero(); } @Test public void update_template_rule_key_should_also_update_custom_rules() { system.setNow(DATE1.getTime()); execute(context -> { NewRepository repo = context.createRepository("squid", "java"); repo.createRule("rule") .setName("Name1") .setHtmlDescription("Description") .setTemplate(true); repo.done(); }); RuleDto rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RuleKey.of("squid", "rule")); // insert custom rule db.rules().insert(new RuleDto() .setRuleKey(RuleKey.of("squid", "custom")) .setLanguage("java") .setScope(Scope.ALL) .setTemplateUuid(rule1.getUuid()) .setName("custom1")); db.commit(); // re-key rule execute(context -> { NewRepository repo = context.createRepository("java", "java"); repo.createRule("rule") .setName("Name1") .setHtmlDescription("Description") .addDeprecatedRuleKey("squid", "rule") .setTemplate(true); repo.done(); }); // template rule and custom rule have been updated rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RuleKey.of("java", "rule")); RuleDto custom = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RuleKey.of("java", "custom")); } @Test public void update_if_rule_key_renamed_and_deprecated_key_declared() { String ruleKey1 = "rule1"; String ruleKey2 = "rule2"; String repository = "fake"; system.setNow(DATE1.getTime()); execute(context -> { NewRepository repo = context.createRepository(repository, "java"); repo.createRule(ruleKey1) .setName("Name1") .setHtmlDescription("Description"); repo.done(); }); RuleDto rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RuleKey.of(repository, ruleKey1)); SearchIdResult<String> searchRule1 = ruleIndex.search(new RuleQuery().setQueryText("Name1"), new SearchOptions()); assertThat(searchRule1.getUuids()).containsOnly(rule1.getUuid()); assertThat(searchRule1.getTotal()).isOne(); system.setNow(DATE2.getTime()); execute(context -> { NewRepository repo = context.createRepository(repository, "java"); repo.createRule(ruleKey2) .setName("Name2") .setHtmlDescription("Description") .addDeprecatedRuleKey(repository, ruleKey1); repo.done(); }); // rule2 is actually rule1 RuleDto rule2 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RuleKey.of(repository, ruleKey2)); assertThat(rule2.getUuid()).isEqualTo(rule1.getUuid()); assertThat(rule2.getName()).isEqualTo("Name2"); assertThat(rule2.getDefaultRuleDescriptionSection().getContent()).isEqualTo(rule1.getDefaultRuleDescriptionSection().getContent()); SearchIdResult<String> searchRule2 = ruleIndex.search(new RuleQuery().setQueryText("Name2"), new SearchOptions()); assertThat(searchRule2.getUuids()).containsOnly(rule2.getUuid()); assertThat(searchRule2.getTotal()).isOne(); assertThat(ruleIndex.search(new RuleQuery().setQueryText("Name1"), new SearchOptions()).getTotal()).isZero(); } @Test public void update_if_repository_changed_and_deprecated_key_declared() { String ruleKey = "rule"; String repository1 = "fake1"; String repository2 = "fake2"; system.setNow(DATE1.getTime()); execute(context -> { NewRepository repo = context.createRepository(repository1, "java"); repo.createRule(ruleKey) .setName("Name1") .setHtmlDescription("Description"); repo.done(); }); RuleDto rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RuleKey.of(repository1, ruleKey)); SearchIdResult<String> searchRule1 = ruleIndex.search(new RuleQuery().setQueryText("Name1"), new SearchOptions()); assertThat(searchRule1.getUuids()).containsOnly(rule1.getUuid()); assertThat(searchRule1.getTotal()).isOne(); system.setNow(DATE2.getTime()); execute(context -> { NewRepository repo = context.createRepository(repository2, "java"); repo.createRule(ruleKey) .setName("Name2") .setHtmlDescription("Description") .addDeprecatedRuleKey(repository1, ruleKey); repo.done(); }); // rule2 is actually rule1 RuleDto rule2 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RuleKey.of(repository2, ruleKey)); assertThat(rule2.getUuid()).isEqualTo(rule1.getUuid()); assertThat(rule2.getName()).isEqualTo("Name2"); assertThat(rule2.getDefaultRuleDescriptionSection().getContent()).isEqualTo(rule1.getDefaultRuleDescriptionSection().getContent()); SearchIdResult<String> searchRule2 = ruleIndex.search(new RuleQuery().setQueryText("Name2"), new SearchOptions()); assertThat(searchRule2.getUuids()).containsOnly(rule2.getUuid()); assertThat(searchRule2.getTotal()).isOne(); assertThat(ruleIndex.search(new RuleQuery().setQueryText("Name1"), new SearchOptions()).getTotal()).isZero(); } @Test @UseDataProvider("allRenamingCases") public void update_if_only_renamed_and_deprecated_key_declared(String ruleKey1, String repo1, String ruleKey2, String repo2) { String name = "Name1"; String description = "Description"; system.setNow(DATE1.getTime()); execute(context -> { NewRepository repo = context.createRepository(repo1, "java"); repo.createRule(ruleKey1) .setName(name) .setHtmlDescription(description); repo.done(); }); RuleDto rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RuleKey.of(repo1, ruleKey1)); assertThat(ruleIndex.search(new RuleQuery().setQueryText(name), new SearchOptions()).getUuids()) .containsOnly(rule1.getUuid()); system.setNow(DATE2.getTime()); execute(context -> { NewRepository repo = context.createRepository(repo2, "java"); repo.createRule(ruleKey2) .setName(name) .setHtmlDescription(description) .addDeprecatedRuleKey(repo1, ruleKey1); repo.done(); }); // rule2 is actually rule1 RuleDto rule2 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RuleKey.of(repo2, ruleKey2)); assertThat(rule2.getUuid()).isEqualTo(rule1.getUuid()); assertThat(rule2.getName()).isEqualTo(rule1.getName()); assertThat(rule2.getDefaultRuleDescriptionSection().getContent()).isEqualTo(rule1.getDefaultRuleDescriptionSection().getContent()); assertThat(ruleIndex.search(new RuleQuery().setQueryText(name), new SearchOptions()).getUuids()) .containsOnly(rule2.getUuid()); } @DataProvider public static Object[][] allRenamingCases() { return new Object[][]{ {"repo1", "rule1", "repo1", "rule2"}, {"repo1", "rule1", "repo2", "rule1"}, {"repo1", "rule1", "repo2", "rule2"}, }; } @Test public void update_if_repository_and_key_changed_and_deprecated_key_declared_among_others() { String ruleKey1 = "rule1"; String ruleKey2 = "rule2"; String repository1 = "fake1"; String repository2 = "fake2"; system.setNow(DATE1.getTime()); execute(context -> { NewRepository repo = context.createRepository(repository1, "java"); repo.createRule(ruleKey1) .setName("Name1") .setHtmlDescription("Description"); repo.done(); }); RuleDto rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RuleKey.of(repository1, ruleKey1)); assertThat(ruleIndex.search(new RuleQuery().setQueryText("Name1"), new SearchOptions()).getUuids()) .containsOnly(rule1.getUuid()); system.setNow(DATE2.getTime()); execute(context -> { NewRepository repo = context.createRepository(repository2, "java"); repo.createRule(ruleKey2) .setName("Name2") .setHtmlDescription("Description") .addDeprecatedRuleKey("foo", "bar") .addDeprecatedRuleKey(repository1, ruleKey1) .addDeprecatedRuleKey("some", "noise"); repo.done(); }); // rule2 is actually rule1 RuleDto rule2 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RuleKey.of(repository2, ruleKey2)); assertThat(rule2.getUuid()).isEqualTo(rule1.getUuid()); assertThat(ruleIndex.search(new RuleQuery().setQueryText("Name2"), new SearchOptions()).getUuids()) .containsOnly(rule1.getUuid()); } @Test public void update_only_rule_description() { system.setNow(DATE1.getTime()); execute(context -> { NewRepository repo = context.createRepository("fake", "java"); repo.createRule("rule") .setName("Name") .setHtmlDescription("Desc1"); repo.done(); }); system.setNow(DATE2.getTime()); execute(context -> { NewRepository repo = context.createRepository("fake", "java"); repo.createRule("rule") .setName("Name") .setHtmlDescription("Desc2"); repo.done(); }); // rule1 has been updated RuleDto rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RuleKey.of("fake", "rule")); assertThat(rule1.getName()).isEqualTo("Name"); assertThat(rule1.getDefaultRuleDescriptionSection().getContent()).isEqualTo("Desc2"); assertThat(ruleIndex.search(new RuleQuery().setQueryText("Desc2"), new SearchOptions()).getTotal()).isOne(); assertThat(ruleIndex.search(new RuleQuery().setQueryText("Desc1"), new SearchOptions()).getTotal()).isZero(); } @Test public void update_several_rule_descriptions() { system.setNow(DATE1.getTime()); RuleDescriptionSection section1context1 = createRuleDescriptionSection(HOW_TO_FIX_SECTION_KEY, "section1 ctx1 content", "ctx_1"); RuleDescriptionSection section1context2 = createRuleDescriptionSection(HOW_TO_FIX_SECTION_KEY, "section1 ctx2 content", "ctx_2"); RuleDescriptionSection section2context1 = createRuleDescriptionSection(RESOURCES_SECTION_KEY, "section2 content", "ctx_1"); RuleDescriptionSection section2context2 = createRuleDescriptionSection(RESOURCES_SECTION_KEY,"section2 ctx2 content", "ctx_2"); RuleDescriptionSection section3noContext = createRuleDescriptionSection(ASSESS_THE_PROBLEM_SECTION_KEY, "section3 content", null); RuleDescriptionSection section4noContext = createRuleDescriptionSection(ROOT_CAUSE_SECTION_KEY, "section4 content", null); execute(context -> { NewRepository repo = context.createRepository("fake", "java"); repo.createRule("rule") .setName("Name") .addDescriptionSection(section1context1) .addDescriptionSection(section1context2) .addDescriptionSection(section2context1) .addDescriptionSection(section2context2) .addDescriptionSection(section3noContext) .addDescriptionSection(section4noContext) .setHtmlDescription("Desc1"); repo.done(); }); RuleDescriptionSection section1context2updated = createRuleDescriptionSection(HOW_TO_FIX_SECTION_KEY, "section1 ctx2 updated content", "ctx_2"); RuleDescriptionSection section2updatedWithoutContext = createRuleDescriptionSection(RESOURCES_SECTION_KEY, section2context1.getHtmlContent(), null); RuleDescriptionSection section4updatedWithContext1 = createRuleDescriptionSection(ROOT_CAUSE_SECTION_KEY, section4noContext.getHtmlContent(), "ctx_1"); RuleDescriptionSection section4updatedWithContext2 = createRuleDescriptionSection(ROOT_CAUSE_SECTION_KEY, section4noContext.getHtmlContent(), "ctx_2"); system.setNow(DATE2.getTime()); execute(context -> { NewRepository repo = context.createRepository("fake", "java"); repo.createRule("rule") .setName("Name") .addDescriptionSection(section1context1) .addDescriptionSection(section1context2updated) .addDescriptionSection(section2updatedWithoutContext) .addDescriptionSection(section3noContext) .addDescriptionSection(section4updatedWithContext1) .addDescriptionSection(section4updatedWithContext2) .setHtmlDescription("Desc2"); repo.done(); }); RuleDto rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RuleKey.of("fake", "rule")); assertThat(rule1.getName()).isEqualTo("Name"); assertThat(rule1.getDefaultRuleDescriptionSection().getContent()).isEqualTo("Desc2"); Set<RuleDescriptionSection> expectedSections = Set.of(section1context1, section1context2updated, section2updatedWithoutContext, section3noContext, section4updatedWithContext1, section4updatedWithContext2); assertThat(rule1.getRuleDescriptionSectionDtos()).hasSize(expectedSections.size() + 1); expectedSections.forEach(apiSection -> assertSectionExists(apiSection, rule1.getRuleDescriptionSectionDtos())); } private static RuleDescriptionSection createRuleDescriptionSection(String sectionKey, String description, @Nullable String contextKey) { Context context = Optional.ofNullable(contextKey).map(key -> new Context(contextKey, contextKey + randomAlphanumeric(10))).orElse(null); return RuleDescriptionSection.builder().sectionKey(sectionKey) .htmlContent(description) .context(context) .build(); } private static void assertSectionExists(RuleDescriptionSection apiSection, Set<RuleDescriptionSectionDto> sectionDtos) { sectionDtos.stream() .filter(sectionDto -> sectionDto.getKey().equals(apiSection.getKey()) && sectionDto.getContent().equals(apiSection.getHtmlContent())) .filter(sectionDto -> isSameContext(apiSection.getContext(), sectionDto.getContext())) .findAny() .orElseThrow(() -> new AssertionError(format("Impossible to find a section dto matching the API section %s", apiSection.getKey()))); } private static boolean isSameContext(Optional<Context> apiContext, @Nullable RuleDescriptionSectionContextDto contextDto) { if (apiContext.isEmpty() && contextDto == null) { return true; } return apiContext.filter(context -> isSameContext(context, contextDto)).isPresent(); } private static boolean isSameContext(Context apiContext, @Nullable RuleDescriptionSectionContextDto contextDto) { if (contextDto == null) { return false; } return Objects.equals(apiContext.getKey(), contextDto.getKey()) && Objects.equals(apiContext.getDisplayName(), contextDto.getDisplayName()); } @Test public void rule_previously_created_as_adhoc_becomes_none_adhoc() { RuleDto rule = db.rules().insert(r -> r.setRepositoryKey("external_fake").setIsExternal(true).setIsAdHoc(true)); system.setNow(DATE2.getTime()); execute(context -> { NewRepository repo = context.createExternalRepository("fake", rule.getLanguage()); repo.createRule(rule.getRuleKey()) .setName(rule.getName()) .setHtmlDescription(rule.getDefaultRuleDescriptionSection().getContent()); repo.done(); }); RuleDto reloaded = dbClient.ruleDao().selectByKey(db.getSession(), rule.getKey()).get(); assertThat(reloaded.isAdHoc()).isFalse(); } @Test public void remove_no_more_defined_external_rule() { RuleDto rule = db.rules().insert(r -> r.setRepositoryKey("external_fake") .setStatus(READY) .setIsExternal(true) .setIsAdHoc(false)); execute(); RuleDto reloaded = dbClient.ruleDao().selectByKey(db.getSession(), rule.getKey()).get(); assertThat(reloaded.getStatus()).isEqualTo(REMOVED); } @Test public void do_not_remove_no_more_defined_ad_hoc_rule() { RuleDto rule = db.rules().insert(r -> r.setRepositoryKey("external_fake") .setStatus(READY) .setIsExternal(true) .setIsAdHoc(true)); execute(); RuleDto reloaded = dbClient.ruleDao().selectByKey(db.getSession(), rule.getKey()).get(); assertThat(reloaded.getStatus()).isEqualTo(READY); } @Test public void disable_then_enable_rule() { // Install rule system.setNow(DATE1.getTime()); execute(new FakeRepositoryV1()); // Uninstall rule system.setNow(DATE2.getTime()); execute(); RuleDto rule = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY1); assertThat(rule.getStatus()).isEqualTo(REMOVED); assertThat(ruleIndex.search(new RuleQuery().setKey(RULE_KEY1.toString()), new SearchOptions()).getTotal()).isZero(); // Re-install rule system.setNow(DATE3.getTime()); execute(new FakeRepositoryV1()); rule = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY1); assertThat(rule.getStatus()).isEqualTo(RuleStatus.BETA); assertThat(ruleIndex.search(new RuleQuery().setKey(RULE_KEY1.toString()), new SearchOptions()).getTotal()).isOne(); } @Test public void do_not_update_rules_when_no_changes() { execute(new FakeRepositoryV1()); assertThat(dbClient.ruleDao().selectAll(db.getSession())).hasSize(3); system.setNow(DATE2.getTime()); execute(new FakeRepositoryV1()); RuleDto rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY1); assertThat(rule1.getCreatedAt()).isEqualTo(DATE1.getTime()); assertThat(rule1.getUpdatedAt()).isEqualTo(DATE1.getTime()); } @Test public void do_not_update_already_removed_rules() { execute(new FakeRepositoryV1()); assertThat(dbClient.ruleDao().selectAll(db.getSession())).hasSize(3); RuleDto rule1 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY1); RuleDto rule2 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY2); RuleDto hotspotRule = dbClient.ruleDao().selectOrFailByKey(db.getSession(), HOTSPOT_RULE_KEY); assertThat(es.getIds(RuleIndexDefinition.TYPE_RULE)).containsOnly(valueOf(rule1.getUuid()), valueOf(rule2.getUuid()), valueOf(hotspotRule.getUuid())); assertThat(rule2.getStatus()).isEqualTo(READY); system.setNow(DATE2.getTime()); execute(new FakeRepositoryV2()); // On MySQL, need to update a rule otherwise rule2 will be seen as READY, but why ??? dbClient.ruleDao().update(db.getSession(), rule1); db.getSession().commit(); // rule2 is removed rule2 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY2); RuleDto rule3 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY3); assertThat(rule2.getStatus()).isEqualTo(REMOVED); assertThat(ruleIndex.search(new RuleQuery(), new SearchOptions()).getUuids()).containsOnly(rule1.getUuid(), rule3.getUuid()); system.setNow(DATE3.getTime()); execute(new FakeRepositoryV2()); db.getSession().commit(); // -> rule2 is still removed, but not update at DATE3 rule2 = dbClient.ruleDao().selectOrFailByKey(db.getSession(), RULE_KEY2); assertThat(rule2.getStatus()).isEqualTo(REMOVED); assertThat(rule2.getUpdatedAt()).isEqualTo(DATE2.getTime()); assertThat(ruleIndex.search(new RuleQuery(), new SearchOptions()).getUuids()).containsOnly(rule1.getUuid(), rule3.getUuid()); } @Test public void mass_insert() { execute(new BigRepository()); assertThat(db.countRowsOfTable("rules")).isEqualTo(BigRepository.SIZE); assertThat(db.countRowsOfTable("rules_parameters")).isEqualTo(BigRepository.SIZE * 20); assertThat(es.getIds(RuleIndexDefinition.TYPE_RULE)).hasSize(BigRepository.SIZE); } @Test public void manage_repository_extensions() { execute(new FindbugsRepository(), new FbContribRepository()); List<RuleDto> rules = dbClient.ruleDao().selectAll(db.getSession()); assertThat(rules).hasSize(2); for (RuleDto rule : rules) { assertThat(rule.getRepositoryKey()).isEqualTo("findbugs"); } } @Test public void remove_system_tags_when_plugin_does_not_provide_any() { // Rule already exists in DB, with some system tags db.rules().insert(new RuleDto() .setRuleKey("rule1") .setRepositoryKey("findbugs") .setName("Rule One") .setScope(Scope.ALL) .addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "Rule one description")) .setDescriptionFormat(RuleDto.Format.HTML) .setSystemTags(newHashSet("tag1", "tag2"))); db.getSession().commit(); // Synchronize rule without tag execute(new FindbugsRepository()); List<RuleDto> rules = dbClient.ruleDao().selectAll(db.getSession()); assertThat(rules).hasSize(1).extracting(RuleDto::getKey, RuleDto::getSystemTags) .containsOnly(tuple(RuleKey.of("findbugs", "rule1"), emptySet())); } @Test public void rules_that_deprecate_previous_rule_must_be_recorded() { execute(context -> { NewRepository repo = context.createRepository("fake", "java"); createRule(repo, "rule1"); repo.done(); }); execute(context -> { NewRepository repo = context.createRepository("fake", "java"); createRule(repo, "newKey") .addDeprecatedRuleKey("fake", "rule1") .addDeprecatedRuleKey("fake", "rule2"); repo.done(); }); List<RuleDto> rules = dbClient.ruleDao().selectAll(db.getSession()); Set<DeprecatedRuleKeyDto> deprecatedRuleKeys = dbClient.ruleDao().selectAllDeprecatedRuleKeys(db.getSession()); assertThat(rules).hasSize(1); assertThat(deprecatedRuleKeys).hasSize(2); } @Test public void rules_that_remove_deprecated_key_must_remove_records() { execute(context -> { NewRepository repo = context.createRepository("fake", "java"); createRule(repo, "rule1"); repo.done(); }); execute(context -> { NewRepository repo = context.createRepository("fake", "java"); createRule(repo, "newKey") .addDeprecatedRuleKey("fake", "rule1") .addDeprecatedRuleKey("fake", "rule2"); repo.done(); }); assertThat(dbClient.ruleDao().selectAll(db.getSession())).hasSize(1); Set<DeprecatedRuleKeyDto> deprecatedRuleKeys = dbClient.ruleDao().selectAllDeprecatedRuleKeys(db.getSession()); assertThat(deprecatedRuleKeys).hasSize(2); execute(context -> { NewRepository repo = context.createRepository("fake", "java"); createRule(repo, "newKey"); repo.done(); }); assertThat(dbClient.ruleDao().selectAll(db.getSession())).hasSize(1); deprecatedRuleKeys = dbClient.ruleDao().selectAllDeprecatedRuleKeys(db.getSession()); assertThat(deprecatedRuleKeys).isEmpty(); } @Test public void declaring_two_rules_with_same_deprecated_RuleKey_should_throw_ISE() { assertThatThrownBy(() -> { execute(context -> { NewRepository repo = context.createRepository("fake", "java"); createRule(repo, "newKey1") .addDeprecatedRuleKey("fake", "old"); createRule(repo, "newKey2") .addDeprecatedRuleKey("fake", "old"); repo.done(); }); }) .isInstanceOf(IllegalStateException.class) .hasMessage("The following deprecated rule keys are declared at least twice [fake:old]"); } @Test public void declaring_a_rule_with_a_deprecated_RuleKey_still_used_should_throw_ISE() { assertThatThrownBy(() -> { execute(context -> { NewRepository repo = context.createRepository("fake", "java"); createRule(repo, "newKey1"); createRule(repo, "newKey2") .addDeprecatedRuleKey("fake", "newKey1"); repo.done(); }); }) .isInstanceOf(IllegalStateException.class) .hasMessage("The following rule keys are declared both as deprecated and used key [fake:newKey1]"); } @Test public void updating_the_deprecated_to_a_new_ruleKey_should_throw_an_ISE() { // On this new rule add a deprecated key execute(context -> createRule(context, "javascript", "javascript", "s103", r -> r.addDeprecatedRuleKey("javascript", "linelength"))); assertThatThrownBy(() -> { // This rule should have been moved to another repository execute(context -> createRule(context, "javascript", "sonarjs", "s103", r -> r.addDeprecatedRuleKey("javascript", "linelength"))); }) .isInstanceOf(IllegalStateException.class) .hasMessage("An incorrect state of deprecated rule keys has been detected.\n " + "The deprecated rule key [javascript:linelength] was previously deprecated by [javascript:s103]. [javascript:s103] should be a deprecated key of [sonarjs:s103],"); } @Test public void deprecate_rule_that_deprecated_another_rule() { execute(context -> createRule(context, "javascript", "javascript", "s103")); execute(context -> createRule(context, "javascript", "javascript", "s104", r -> r.addDeprecatedRuleKey("javascript", "s103"))); // This rule should have been moved to another repository execute(context -> createRule(context, "javascript", "sonarjs", "s105", r -> r.addDeprecatedRuleKey("javascript", "s103") .addDeprecatedRuleKey("javascript", "s104"))); } @Test public void declaring_a_rule_with_an_existing_RuleKey_still_used_should_throw_IAE() { assertThatThrownBy(() -> { execute(context -> { NewRepository repo = context.createRepository("fake", "java"); createRule(repo, "newKey1"); createRule(repo, "newKey1"); repo.done(); }); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The rule 'newKey1' of repository 'fake' is declared several times"); } @Test public void removed_rule_should_appear_in_changelog() { //GIVEN QProfileDto qProfileDto = db.qualityProfiles().insert(); RuleDto ruleDto = db.rules().insert(RULE_KEY1); db.qualityProfiles().activateRule(qProfileDto, ruleDto); ActiveRuleChange arChange = new ActiveRuleChange(DEACTIVATED, ActiveRuleDto.createFor(qProfileDto, ruleDto), ruleDto); when(qProfileRules.deleteRule(any(DbSession.class), eq(ruleDto))).thenReturn(List.of(arChange)); //WHEN execute(context -> context.createRepository("fake", "java").done()); //THEN List<QProfileChangeDto> qProfileChangeDtos = dbClient.qProfileChangeDao().selectByQuery(db.getSession(), new QProfileChangeQuery(qProfileDto.getKee())); assertThat(qProfileChangeDtos).extracting(QProfileChangeDto::getRulesProfileUuid, QProfileChangeDto::getChangeType) .contains(tuple(qProfileDto.getRulesProfileUuid(), "DEACTIVATED")); } @Test public void removed_rule_should_be_deleted_when_renamed_repository() { //GIVEN RuleDto removedRuleDto = db.rules().insert(RuleKey.of("old_repo", "removed_rule")); RuleDto renamedRuleDto = db.rules().insert(RuleKey.of("old_repo", "renamed_rule")); //WHEN execute(context -> createRule(context, "java", "new_repo", renamedRuleDto.getRuleKey(), rule -> rule.addDeprecatedRuleKey(renamedRuleDto.getRepositoryKey(), renamedRuleDto.getRuleKey()))); //THEN verify(qProfileRules).deleteRule(any(DbSession.class), eq(removedRuleDto)); } private void execute(RulesDefinition... defs) { ServerPluginRepository pluginRepository = mock(ServerPluginRepository.class); when(pluginRepository.getPluginKey(any(RulesDefinition.class))).thenReturn(FAKE_PLUGIN_KEY); RuleDefinitionsLoader loader = new RuleDefinitionsLoader(pluginRepository, defs); Languages languages = mock(Languages.class); when(languages.get(any())).thenReturn(mock(Language.class)); reset(webServerRuleFinder); RegisterRules task = new RegisterRules(loader, qProfileRules, dbClient, ruleIndexer, activeRuleIndexer, languages, system, webServerRuleFinder, uuidFactory, metadataIndex, resolver); task.start(); // Execute a commit to refresh session state as the task is using its own session db.getSession().commit(); verify(webServerRuleFinder).startCaching(); } private NewRule createRule(NewRepository repo, String key) { return repo.createRule(key) .setName(key + " name") .setHtmlDescription("Description of " + key) .setSeverity(BLOCKER) .setInternalKey("config1") .setTags("tag1", "tag2", "tag3") .setType(RuleType.CODE_SMELL) .setStatus(RuleStatus.BETA); } @SafeVarargs private void createRule(RulesDefinition.Context context, String language, String repositoryKey, String ruleKey, Consumer<NewRule>... consumers) { NewRepository repo = context.createRepository(repositoryKey, language); NewRule newRule = repo.createRule(ruleKey) .setName(ruleKey) .setHtmlDescription("Description of One") .setSeverity(BLOCKER) .setType(RuleType.CODE_SMELL) .setStatus(RuleStatus.BETA); Arrays.stream(consumers).forEach(c -> c.accept(newRule)); repo.done(); } private void verifyIndicesMarkedAsInitialized() { verify(metadataIndex).setInitialized(RuleIndexDefinition.TYPE_RULE, true); verify(metadataIndex).setInitialized(RuleIndexDefinition.TYPE_ACTIVE_RULE, true); reset(metadataIndex); } private void verifyIndicesNotMarkedAsInitialized() { verifyNoInteractions(metadataIndex); } private RuleParamDto getParam(List<RuleParamDto> params, String key) { for (RuleParamDto param : params) { if (param.getName().equals(key)) { return param; } } return null; } static class FakeRepositoryV1 implements RulesDefinition { @Override public void define(Context context) { NewRepository repo = context.createRepository("fake", "java"); NewRule rule1 = repo.createRule(RULE_KEY1.rule()) .setName("One") .setHtmlDescription("Description of One") .setSeverity(BLOCKER) .setInternalKey("config1") .setTags("tag1", "tag2", "tag3") .setScope(RuleScope.ALL) .setType(RuleType.CODE_SMELL) .setStatus(RuleStatus.BETA) .setGapDescription("java.S115.effortToFix") .addEducationPrincipleKeys("concept1", "concept2", "concept3"); rule1.setDebtRemediationFunction(rule1.debtRemediationFunctions().linearWithOffset("5d", "10h")); rule1.createParam("param1").setDescription("parameter one").setDefaultValue("default1"); rule1.createParam("param2").setDescription("parameter two").setDefaultValue("default2"); repo.createRule(HOTSPOT_RULE_KEY.rule()) .setName("Hotspot") .setHtmlDescription("Minimal hotspot") .setType(RuleType.SECURITY_HOTSPOT) .addOwaspTop10(Y2021, OwaspTop10.A1, OwaspTop10.A3) .addCwe(1, 123, 863); repo.createRule(RULE_KEY2.rule()) .setName("Two") .setHtmlDescription("Minimal rule"); repo.done(); } } /** * FakeRepositoryV1 with some changes */ static class FakeRepositoryV2 implements RulesDefinition { @Override public void define(Context context) { NewRepository repo = context.createRepository("fake", "java"); // almost all the attributes of rule1 are changed NewRule rule1 = repo.createRule(RULE_KEY1.rule()) .setName("One v2") .setHtmlDescription("Description of One v2") .setSeverity(INFO) .setInternalKey("config1 v2") // tag2 and tag3 removed, tag4 added .setTags("tag1", "tag4") .setType(RuleType.BUG) .setStatus(READY) .setGapDescription("java.S115.effortToFix.v2") .addEducationPrincipleKeys("concept1", "concept4"); rule1.setDebtRemediationFunction(rule1.debtRemediationFunctions().linearWithOffset("6d", "2h")); rule1.createParam("param1").setDescription("parameter one v2").setDefaultValue("default1 v2"); rule1.createParam("param2").setDescription("parameter two v2").setDefaultValue("default2 v2"); // rule2 is dropped, rule3 is new repo.createRule(RULE_KEY3.rule()) .setName("Three") .setHtmlDescription("Rule Three"); repo.done(); } } static class FakeRepositoryV3 implements RulesDefinition { @Override public void define(Context context) { NewRepository repo = context.createRepository("fake", "java"); // rule 3 is dropped repo.createRule(RULE_KEY3.rule()) .setName("Three") .setMarkdownDescription("Rule Three V2"); repo.done(); } } static class ExternalRuleRepository implements RulesDefinition { @Override public void define(Context context) { NewRepository repo = context.createExternalRepository("eslint", "js"); repo.createRule(RULE_KEY1.rule()) .setName("One") .setHtmlDescription("Description of One") .setSeverity(BLOCKER) .setInternalKey("config1") .setTags("tag1", "tag2", "tag3") .setScope(RuleScope.ALL) .setType(RuleType.CODE_SMELL) .setStatus(RuleStatus.BETA) .addEducationPrincipleKeys("concept1", "concept2", "concept3"); repo.createRule(EXTERNAL_HOTSPOT_RULE_KEY.rule()) .setName("Hotspot") .setHtmlDescription("Minimal hotspot") .setType(RuleType.SECURITY_HOTSPOT) .addOwaspTop10(Y2021, OwaspTop10.A1, OwaspTop10.A3) .addCwe(1, 123, 863); repo.done(); } } static class BigRepository implements RulesDefinition { static final int SIZE = 500; @Override public void define(Context context) { NewRepository repo = context.createRepository("big", "java"); for (int i = 0; i < SIZE; i++) { NewRule rule = repo.createRule("rule" + i) .setName("name of " + i) .setHtmlDescription("description of " + i); for (int j = 0; j < 20; j++) { rule.createParam("param" + j); } } repo.done(); } } static class FindbugsRepository implements RulesDefinition { @Override public void define(Context context) { NewRepository repo = context.createRepository("findbugs", "java"); repo.createRule("rule1") .setName("Rule One") .setHtmlDescription("Description of Rule One"); repo.done(); } } static class FbContribRepository implements RulesDefinition { @Override public void define(Context context) { NewExtendedRepository repo = context.createRepository("findbugs", "java"); repo.createRule("rule2") .setName("Rule Two") .setHtmlDescription("Description of Rule Two"); repo.done(); } } }
56,510
41.015613
175
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/rule/RuleDefinitionsLoaderTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.rule; import org.junit.Test; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.server.plugins.ServerPluginRepository; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class RuleDefinitionsLoaderTest { @Test public void no_definitions() { RulesDefinition.Context context = new RuleDefinitionsLoader(mock(ServerPluginRepository.class)).load(); assertThat(context.repositories()).isEmpty(); } @Test public void load_definitions() { RulesDefinition.Context context = new RuleDefinitionsLoader(mock(ServerPluginRepository.class), new RulesDefinition[] { new FindbugsDefinitions(), new JavaDefinitions() }).load(); assertThat(context.repositories()).hasSize(2); assertThat(context.repository("findbugs")).isNotNull(); assertThat(context.repository("java")).isNotNull(); } static class FindbugsDefinitions implements RulesDefinition { @Override public void define(Context context) { NewRepository repo = context.createRepository("findbugs", "java"); repo.setName("Findbugs"); repo.createRule("ABC") .setName("ABC") .setHtmlDescription("Description of ABC"); repo.done(); } } static class JavaDefinitions implements RulesDefinition { @Override public void define(Context context) { NewRepository repo = context.createRepository("java", "java"); repo.setName("Sava"); repo.createRule("DEF") .setName("DEF") .setHtmlDescription("Description of DEF"); repo.done(); } } }
2,478
32.5
107
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/rule/RuleDescriptionGeneratorTestData.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.rule; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringJoiner; import javax.annotation.Nullable; import org.sonar.api.rules.RuleType; import org.sonar.api.server.rule.RuleDescriptionSection; import org.sonar.db.rule.RuleDescriptionSectionDto; class RuleDescriptionGeneratorTestData { enum RuleDescriptionSectionGeneratorIdentifier { LEGACY_ISSUE, LEGACY_HOTSPOT, ADVANCED_RULE; } private final RuleType ruleType; private final String htmlDescription; private final String markdownDescription; private final List<RuleDescriptionSection> ruleDescriptionSections; private final RuleDescriptionSectionGeneratorIdentifier expectedGenerator; private final Set<RuleDescriptionSectionDto> expectedRuleDescriptionSectionsDto; private RuleDescriptionGeneratorTestData(RuleType ruleType, @Nullable String htmlDescription,@Nullable String markdownDescription, List<RuleDescriptionSection> ruleDescriptionSections, RuleDescriptionSectionGeneratorIdentifier expectedGenerator, Set<RuleDescriptionSectionDto> expectedRuleDescriptionSectionsDto) { this.ruleType = ruleType; this.htmlDescription = htmlDescription; this.markdownDescription = markdownDescription; this.ruleDescriptionSections = ruleDescriptionSections; this.expectedGenerator = expectedGenerator; this.expectedRuleDescriptionSectionsDto = expectedRuleDescriptionSectionsDto; } public RuleType getRuleType() { return ruleType; } String getHtmlDescription() { return htmlDescription; } String getMarkdownDescription() { return markdownDescription; } List<RuleDescriptionSection> getRuleDescriptionSections() { return ruleDescriptionSections; } RuleDescriptionSectionGeneratorIdentifier getExpectedGenerator() { return expectedGenerator; } public Set<RuleDescriptionSectionDto> getExpectedRuleDescriptionSectionsDto() { return expectedRuleDescriptionSectionsDto; } static RuleDescriptionGeneratorTestDataBuilder aRuleOfType(RuleType ruleType) { return new RuleDescriptionGeneratorTestDataBuilder(ruleType); } @Override public String toString() { return new StringJoiner(", ") .add(ruleType.name()) .add(htmlDescription == null ? "html present" : "html absent") .add(markdownDescription == null ? "md present" : "md absent") .add(String.valueOf(ruleDescriptionSections.size())) .add("generator=" + expectedGenerator) .toString(); } public static final class RuleDescriptionGeneratorTestDataBuilder { private final RuleType ruleType; private String htmlDescription; private String markdownDescription; private List<RuleDescriptionSection> ruleDescriptionSections = new ArrayList<>(); private Set<RuleDescriptionSectionDto> expectedRuleDescriptionSectionsDto = new HashSet<>(); private RuleDescriptionSectionGeneratorIdentifier expectedGenerator; private RuleDescriptionGeneratorTestDataBuilder(RuleType ruleType) { this.ruleType = ruleType; } RuleDescriptionGeneratorTestDataBuilder html(@Nullable String htmlDescription) { this.htmlDescription = htmlDescription; return this; } RuleDescriptionGeneratorTestDataBuilder md(@Nullable String markdownDescription) { this.markdownDescription = markdownDescription; return this; } RuleDescriptionGeneratorTestDataBuilder addSection(RuleDescriptionSection ruleDescriptionSection) { this.ruleDescriptionSections.add(ruleDescriptionSection); return this; } RuleDescriptionGeneratorTestDataBuilder expectedGenerator(RuleDescriptionSectionGeneratorIdentifier generatorToUse) { this.expectedGenerator = generatorToUse; return this; } RuleDescriptionGeneratorTestDataBuilder addExpectedSection(RuleDescriptionSectionDto sectionDto) { this.expectedRuleDescriptionSectionsDto.add(sectionDto); return this; } RuleDescriptionGeneratorTestData build() { return new RuleDescriptionGeneratorTestData(ruleType, htmlDescription, markdownDescription, ruleDescriptionSections, expectedGenerator, expectedRuleDescriptionSectionsDto); } } }
5,081
36.367647
186
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/rule/RuleDescriptionSectionsGeneratorResolverTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.rule; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.sonar.api.server.rule.RulesDefinition; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class RuleDescriptionSectionsGeneratorResolverTest { private static final String RULE_KEY = "RULE_KEY"; @Mock private RuleDescriptionSectionsGenerator generator1; @Mock private RuleDescriptionSectionsGenerator generator2; @Mock private RulesDefinition.Rule rule; private RuleDescriptionSectionsGeneratorResolver resolver; @Before public void setUp() { resolver = new RuleDescriptionSectionsGeneratorResolver(Set.of(generator1, generator2)); when(rule.key()).thenReturn(RULE_KEY); } @Test public void getRuleDescriptionSectionsGenerator_returnsTheCorrectGenerator() { when(generator2.isGeneratorForRule(rule)).thenReturn(true); assertThat(resolver.getRuleDescriptionSectionsGenerator(rule)).isEqualTo(generator2); } @Test public void getRuleDescriptionSectionsGenerator_whenNoGeneratorFound_throwsWithCorrectMessage() { assertThatIllegalStateException() .isThrownBy(() -> resolver.getRuleDescriptionSectionsGenerator(rule)) .withMessage("No rule description section generator found for rule with key RULE_KEY"); } @Test public void getRuleDescriptionSectionsGenerator_whenMoreThanOneGeneratorFound_throwsWithCorrectMessage() { when(generator1.isGeneratorForRule(rule)).thenReturn(true); when(generator2.isGeneratorForRule(rule)).thenReturn(true); assertThatIllegalStateException() .isThrownBy(() -> resolver.getRuleDescriptionSectionsGenerator(rule)) .withMessage("More than one rule description section generator found for rule with key RULE_KEY"); } }
2,878
36.38961
108
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/rule/RuleDescriptionSectionsGeneratorsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.rule; import com.google.common.collect.ImmutableMap; import java.util.Arrays; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.sonar.api.server.rule.RuleDescriptionSection; import org.sonar.api.server.rule.RuleDescriptionSectionBuilder; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.core.util.UuidFactory; import org.sonar.db.rule.RuleDescriptionSectionDto; import org.sonar.server.rule.RuleDescriptionGeneratorTestData.RuleDescriptionSectionGeneratorIdentifier; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.rules.RuleType.BUG; import static org.sonar.api.rules.RuleType.CODE_SMELL; import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT; import static org.sonar.api.rules.RuleType.VULNERABILITY; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.ROOT_CAUSE_SECTION_KEY; import static org.sonar.server.rule.RuleDescriptionGeneratorTestData.RuleDescriptionSectionGeneratorIdentifier.ADVANCED_RULE; import static org.sonar.server.rule.RuleDescriptionGeneratorTestData.RuleDescriptionSectionGeneratorIdentifier.LEGACY_HOTSPOT; import static org.sonar.server.rule.RuleDescriptionGeneratorTestData.RuleDescriptionSectionGeneratorIdentifier.LEGACY_ISSUE; import static org.sonar.server.rule.RuleDescriptionGeneratorTestData.aRuleOfType; @RunWith(Parameterized.class) public class RuleDescriptionSectionsGeneratorsTest { private static final String KEY_1 = "key"; private static final String KEY_2 = "key_2"; private static final String UUID_1 = "uuid1"; private static final String UUID_2 = "uuid2"; private static final String HTML_CONTENT = "html content"; private static final String MD_CONTENT = "md content balblab"; private static final RuleDescriptionSection SECTION_1 = new RuleDescriptionSectionBuilder().sectionKey(KEY_1).htmlContent(HTML_CONTENT).build(); private static final RuleDescriptionSection SECTION_2 = new RuleDescriptionSectionBuilder().sectionKey(KEY_2).htmlContent(HTML_CONTENT).build(); private static final RuleDescriptionSectionDto DEFAULT_HTML_SECTION_1 = RuleDescriptionSectionDto.builder().uuid(UUID_1).key("default").content(HTML_CONTENT).build(); private static final RuleDescriptionSectionDto DEFAULT_HTML_HOTSPOT_SECTION_1 = RuleDescriptionSectionDto.builder().uuid(UUID_1).key(ROOT_CAUSE_SECTION_KEY).content(HTML_CONTENT).build(); private static final RuleDescriptionSectionDto DEFAULT_MD_HOTSPOT_SECTION_1 = RuleDescriptionSectionDto.builder().uuid(UUID_1).key(ROOT_CAUSE_SECTION_KEY).content(MD_CONTENT).build(); private static final RuleDescriptionSectionDto DEFAULT_MD_SECTION_1 = RuleDescriptionSectionDto.builder().uuid(UUID_1).key("default").content(MD_CONTENT).build(); private static final RuleDescriptionSectionDto HTML_SECTION_1 = RuleDescriptionSectionDto.builder().uuid(UUID_1).key(KEY_1).content(HTML_CONTENT).build(); private static final RuleDescriptionSectionDto HTML_SECTION_2 = RuleDescriptionSectionDto.builder().uuid(UUID_2).key(KEY_2).content(HTML_CONTENT).build(); private static final RuleDescriptionSectionDto LEGACY_HTML_SECTION = RuleDescriptionSectionDto.builder().uuid(UUID_2).key("default").content(HTML_CONTENT).build(); private static final RuleDescriptionSectionDto LEGACY_MD_SECTION = RuleDescriptionSectionDto.builder().uuid(UUID_2).key("default").content(MD_CONTENT).build(); @Parameterized.Parameters(name = "{index} = {0}") public static List<RuleDescriptionGeneratorTestData> testData() { return Arrays.asList( // ISSUES aRuleOfType(BUG).html(null).md(null).expectedGenerator(LEGACY_ISSUE).build(), aRuleOfType(BUG).html(HTML_CONTENT).md(null).expectedGenerator(LEGACY_ISSUE).addExpectedSection(DEFAULT_HTML_SECTION_1).build(), aRuleOfType(BUG).html(null).md(MD_CONTENT).expectedGenerator(LEGACY_ISSUE).addExpectedSection(DEFAULT_MD_SECTION_1).build(), aRuleOfType(BUG).html(HTML_CONTENT).md(MD_CONTENT).expectedGenerator(LEGACY_ISSUE).addExpectedSection(DEFAULT_HTML_SECTION_1).build(), aRuleOfType(CODE_SMELL).html(HTML_CONTENT).md(MD_CONTENT).expectedGenerator(LEGACY_ISSUE).addExpectedSection(DEFAULT_HTML_SECTION_1).build(), aRuleOfType(VULNERABILITY).html(HTML_CONTENT).md(MD_CONTENT).expectedGenerator(LEGACY_ISSUE).addExpectedSection(DEFAULT_HTML_SECTION_1).build(), // HOTSPOT aRuleOfType(SECURITY_HOTSPOT).html(null).md(null).expectedGenerator(LEGACY_HOTSPOT).build(), aRuleOfType(SECURITY_HOTSPOT).html(HTML_CONTENT).md(null).expectedGenerator(LEGACY_HOTSPOT).addExpectedSection(DEFAULT_HTML_HOTSPOT_SECTION_1).addExpectedSection(LEGACY_HTML_SECTION).build(), aRuleOfType(SECURITY_HOTSPOT).html(null).md(MD_CONTENT).expectedGenerator(LEGACY_HOTSPOT).addExpectedSection(DEFAULT_MD_HOTSPOT_SECTION_1).addExpectedSection(LEGACY_MD_SECTION).build(), aRuleOfType(SECURITY_HOTSPOT).html(HTML_CONTENT).md(MD_CONTENT).expectedGenerator(LEGACY_HOTSPOT).addExpectedSection(DEFAULT_HTML_HOTSPOT_SECTION_1).addExpectedSection(LEGACY_HTML_SECTION).build(), // ADVANCED RULES aRuleOfType(BUG).html(null).md(null).addSection(SECTION_1).expectedGenerator(ADVANCED_RULE).addExpectedSection(HTML_SECTION_1).build(), aRuleOfType(BUG).html(HTML_CONTENT).md(null).addSection(SECTION_1).expectedGenerator(ADVANCED_RULE).addExpectedSection(HTML_SECTION_1).addExpectedSection(LEGACY_HTML_SECTION).build(), aRuleOfType(BUG).html(null).md(MD_CONTENT).addSection(SECTION_1).expectedGenerator(ADVANCED_RULE).addExpectedSection(HTML_SECTION_1).addExpectedSection(LEGACY_MD_SECTION).build(), aRuleOfType(BUG).html(HTML_CONTENT).md(MD_CONTENT).addSection(SECTION_1).expectedGenerator(ADVANCED_RULE).addExpectedSection(HTML_SECTION_1).addExpectedSection(LEGACY_HTML_SECTION).build(), aRuleOfType(BUG).html(HTML_CONTENT).md(MD_CONTENT).addSection(SECTION_1).addSection(SECTION_2).expectedGenerator(ADVANCED_RULE) .addExpectedSection(HTML_SECTION_1).addExpectedSection(HTML_SECTION_2).addExpectedSection(LEGACY_HTML_SECTION).build(), aRuleOfType(SECURITY_HOTSPOT).html(null).md(null).addSection(SECTION_1).expectedGenerator(LEGACY_HOTSPOT).build(), aRuleOfType(SECURITY_HOTSPOT).html(HTML_CONTENT).md(null).addSection(SECTION_1).expectedGenerator(LEGACY_HOTSPOT).addExpectedSection(DEFAULT_HTML_HOTSPOT_SECTION_1).addExpectedSection(LEGACY_HTML_SECTION).build(), aRuleOfType(SECURITY_HOTSPOT).html(null).md(MD_CONTENT).addSection(SECTION_1).expectedGenerator(LEGACY_HOTSPOT).addExpectedSection(DEFAULT_MD_HOTSPOT_SECTION_1).addExpectedSection(LEGACY_MD_SECTION).build(), aRuleOfType(SECURITY_HOTSPOT).html(HTML_CONTENT).md(MD_CONTENT).addSection(SECTION_1).expectedGenerator(LEGACY_HOTSPOT).addExpectedSection(DEFAULT_HTML_HOTSPOT_SECTION_1).addExpectedSection(LEGACY_HTML_SECTION).build() ); } private final UuidFactory uuidFactory = mock(UuidFactory.class); private final RulesDefinition.Rule rule = mock(RulesDefinition.Rule.class); private final RuleDescriptionGeneratorTestData testData; private final RuleDescriptionSectionsGenerator legacyHotspotRuleDescriptionSectionsGenerator = new LegacyHotspotRuleDescriptionSectionsGenerator(uuidFactory); private final LegacyIssueRuleDescriptionSectionsGenerator legacyIssueRuleDescriptionSectionsGenerator = new LegacyIssueRuleDescriptionSectionsGenerator(uuidFactory); private final RuleDescriptionSectionsGenerator advancedRuleDescriptionSectionsGenerator = new AdvancedRuleDescriptionSectionsGenerator(uuidFactory, legacyIssueRuleDescriptionSectionsGenerator); Map<RuleDescriptionSectionGeneratorIdentifier, RuleDescriptionSectionsGenerator> idToGenerator = ImmutableMap.<RuleDescriptionSectionGeneratorIdentifier, RuleDescriptionSectionsGenerator>builder() .put(ADVANCED_RULE, advancedRuleDescriptionSectionsGenerator) .put(LEGACY_HOTSPOT, legacyHotspotRuleDescriptionSectionsGenerator) .put(LEGACY_ISSUE, legacyIssueRuleDescriptionSectionsGenerator) .build(); public RuleDescriptionSectionsGeneratorsTest(RuleDescriptionGeneratorTestData testData) { this.testData = testData; } @Before public void before() { when(uuidFactory.create()).thenReturn(UUID_1).thenReturn(UUID_2); when(rule.htmlDescription()).thenReturn(testData.getHtmlDescription()); when(rule.markdownDescription()).thenReturn(testData.getMarkdownDescription()); when(rule.ruleDescriptionSections()).thenReturn(testData.getRuleDescriptionSections()); when(rule.type()).thenReturn(testData.getRuleType()); } @Test public void scenario() { assertThat(advancedRuleDescriptionSectionsGenerator.isGeneratorForRule(rule)).isEqualTo(ADVANCED_RULE.equals(testData.getExpectedGenerator())); assertThat(legacyHotspotRuleDescriptionSectionsGenerator.isGeneratorForRule(rule)).isEqualTo(LEGACY_HOTSPOT.equals(testData.getExpectedGenerator())); assertThat(legacyIssueRuleDescriptionSectionsGenerator.isGeneratorForRule(rule)).isEqualTo(LEGACY_ISSUE.equals(testData.getExpectedGenerator())); generateAndVerifySectionsContent(idToGenerator.get(testData.getExpectedGenerator())); } private void generateAndVerifySectionsContent(RuleDescriptionSectionsGenerator advancedRuleDescriptionSectionsGenerator) { assertThat(advancedRuleDescriptionSectionsGenerator.generateSections(rule)) .usingRecursiveFieldByFieldElementComparator() .containsExactlyInAnyOrderElementsOf(testData.getExpectedRuleDescriptionSectionsDto()); } }
10,560
71.335616
224
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/rule/SingleDeprecatedRuleKeyTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.rule; import com.google.common.collect.ImmutableSet; import java.util.Set; import org.assertj.core.groups.Tuple; import org.junit.Test; import org.sonar.api.rule.RuleKey; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.db.rule.DeprecatedRuleKeyDto; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class SingleDeprecatedRuleKeyTest { @Test public void test_creation_from_DeprecatedRuleKeyDto() { // Creation from DeprecatedRuleKeyDto DeprecatedRuleKeyDto deprecatedRuleKeyDto = new DeprecatedRuleKeyDto() .setOldRuleKey(randomAlphanumeric(50)) .setOldRepositoryKey(randomAlphanumeric(50)) .setRuleUuid(randomAlphanumeric(50)) .setUuid(randomAlphanumeric(40)); SingleDeprecatedRuleKey singleDeprecatedRuleKey = SingleDeprecatedRuleKey.from(deprecatedRuleKeyDto); assertThat(singleDeprecatedRuleKey.getOldRepositoryKey()).isEqualTo(deprecatedRuleKeyDto.getOldRepositoryKey()); assertThat(singleDeprecatedRuleKey.getOldRuleKey()).isEqualTo(deprecatedRuleKeyDto.getOldRuleKey()); assertThat(singleDeprecatedRuleKey.getNewRepositoryKey()).isEqualTo(deprecatedRuleKeyDto.getNewRepositoryKey()); assertThat(singleDeprecatedRuleKey.getNewRuleKey()).isEqualTo(deprecatedRuleKeyDto.getNewRuleKey()); assertThat(singleDeprecatedRuleKey.getUuid()).isEqualTo(deprecatedRuleKeyDto.getUuid()); assertThat(singleDeprecatedRuleKey.getRuleUuid()).isEqualTo(deprecatedRuleKeyDto.getRuleUuid()); assertThat(singleDeprecatedRuleKey.getOldRuleKeyAsRuleKey()) .isEqualTo(RuleKey.of(deprecatedRuleKeyDto.getOldRepositoryKey(), deprecatedRuleKeyDto.getOldRuleKey())); } @Test public void test_creation_from_RulesDefinitionRule() { // Creation from RulesDefinition.Rule ImmutableSet<RuleKey> deprecatedRuleKeys = ImmutableSet.of( RuleKey.of(randomAlphanumeric(50), randomAlphanumeric(50)), RuleKey.of(randomAlphanumeric(50), randomAlphanumeric(50)), RuleKey.of(randomAlphanumeric(50), randomAlphanumeric(50))); RulesDefinition.Repository repository = mock(RulesDefinition.Repository.class); when(repository.key()).thenReturn(randomAlphanumeric(50)); RulesDefinition.Rule rule = mock(RulesDefinition.Rule.class); when(rule.key()).thenReturn(randomAlphanumeric(50)); when(rule.deprecatedRuleKeys()).thenReturn(deprecatedRuleKeys); when(rule.repository()).thenReturn(repository); Set<SingleDeprecatedRuleKey> singleDeprecatedRuleKeys = SingleDeprecatedRuleKey.from(rule); assertThat(singleDeprecatedRuleKeys).hasSize(deprecatedRuleKeys.size()); assertThat(singleDeprecatedRuleKeys) .extracting(SingleDeprecatedRuleKey::getUuid, SingleDeprecatedRuleKey::getOldRepositoryKey, SingleDeprecatedRuleKey::getOldRuleKey, SingleDeprecatedRuleKey::getNewRepositoryKey, SingleDeprecatedRuleKey::getNewRuleKey, SingleDeprecatedRuleKey::getOldRuleKeyAsRuleKey) .containsExactlyInAnyOrder( deprecatedRuleKeys.stream().map( r -> tuple(null, r.repository(), r.rule(), rule.repository().key(), rule.key(), RuleKey.of(r.repository(), r.rule()))) .toList().toArray(new Tuple[deprecatedRuleKeys.size()])); } @Test public void test_equality() { DeprecatedRuleKeyDto deprecatedRuleKeyDto1 = new DeprecatedRuleKeyDto() .setOldRuleKey(randomAlphanumeric(50)) .setOldRepositoryKey(randomAlphanumeric(50)) .setUuid(randomAlphanumeric(40)) .setRuleUuid("some-uuid"); DeprecatedRuleKeyDto deprecatedRuleKeyDto1WithoutUuid = new DeprecatedRuleKeyDto() .setOldRuleKey(deprecatedRuleKeyDto1.getOldRuleKey()) .setOldRepositoryKey(deprecatedRuleKeyDto1.getOldRepositoryKey()); DeprecatedRuleKeyDto deprecatedRuleKeyDto2 = new DeprecatedRuleKeyDto() .setOldRuleKey(randomAlphanumeric(50)) .setOldRepositoryKey(randomAlphanumeric(50)) .setUuid(randomAlphanumeric(40)); SingleDeprecatedRuleKey singleDeprecatedRuleKey1 = SingleDeprecatedRuleKey.from(deprecatedRuleKeyDto1); SingleDeprecatedRuleKey singleDeprecatedRuleKey2 = SingleDeprecatedRuleKey.from(deprecatedRuleKeyDto2); assertThat(singleDeprecatedRuleKey1) .isEqualTo(singleDeprecatedRuleKey1) .isEqualTo(SingleDeprecatedRuleKey.from(deprecatedRuleKeyDto1)) .isEqualTo(SingleDeprecatedRuleKey.from(deprecatedRuleKeyDto1WithoutUuid)); assertThat(singleDeprecatedRuleKey2).isEqualTo(SingleDeprecatedRuleKey.from(deprecatedRuleKeyDto2)); assertThat(singleDeprecatedRuleKey1) .hasSameHashCodeAs(singleDeprecatedRuleKey1) .hasSameHashCodeAs(SingleDeprecatedRuleKey.from(deprecatedRuleKeyDto1)) .hasSameHashCodeAs(SingleDeprecatedRuleKey.from(deprecatedRuleKeyDto1WithoutUuid)); assertThat(singleDeprecatedRuleKey2).hasSameHashCodeAs(SingleDeprecatedRuleKey.from(deprecatedRuleKeyDto2)); assertThat(singleDeprecatedRuleKey1) .isNotNull() .isNotEqualTo("") .isNotEqualTo(null) .isNotEqualTo(singleDeprecatedRuleKey2); assertThat(singleDeprecatedRuleKey2).isNotEqualTo(singleDeprecatedRuleKey1); assertThat(singleDeprecatedRuleKey1.hashCode()).isNotEqualTo(singleDeprecatedRuleKey2.hashCode()); assertThat(singleDeprecatedRuleKey2.hashCode()).isNotEqualTo(singleDeprecatedRuleKey1.hashCode()); } }
6,376
48.434109
142
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/search/BaseDocTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.search; import com.google.common.collect.ImmutableMap; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.sonar.server.es.BaseDoc; import org.sonar.server.es.EsUtils; import org.sonar.server.es.Index; import org.sonar.server.es.IndexType; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; public class BaseDocTest { private final IndexType.IndexMainType someType = IndexType.main(Index.simple("bar"), "donut"); @Test public void getField() { Map<String, Object> fields = new HashMap<>(); fields.put("a_string", "foo"); fields.put("a_int", 42); fields.put("a_null", null); BaseDoc doc = new BaseDoc(someType, fields) { @Override public String getId() { return null; } }; assertThat((String) doc.getNullableField("a_string")).isEqualTo("foo"); assertThat((int) doc.getNullableField("a_int")).isEqualTo(42); assertThat((String) doc.getNullableField("a_null")).isNull(); } @Test public void getField_fails_if_missing_field() { Map<String, Object> fields = Collections.emptyMap(); BaseDoc doc = new BaseDoc(someType, fields) { @Override public String getId() { return null; } }; try { doc.getNullableField("a_string"); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("Field a_string not specified in query options"); } } @Test public void getFieldAsDate() { BaseDoc doc = new BaseDoc(someType, new HashMap<>()) { @Override public String getId() { return null; } }; Date now = new Date(); doc.setField("javaDate", now); assertThat(doc.getFieldAsDate("javaDate")).isEqualToIgnoringMillis(now); doc.setField("stringDate", EsUtils.formatDateTime(now)); assertThat(doc.getFieldAsDate("stringDate")).isEqualToIgnoringMillis(now); } @Test public void getNullableFieldAsDate() { BaseDoc doc = new BaseDoc(someType, new HashMap<>()) { @Override public String getId() { return null; } }; Date now = new Date(); doc.setField("javaDate", now); assertThat(doc.getNullableFieldAsDate("javaDate")).isEqualToIgnoringMillis(now); doc.setField("stringDate", EsUtils.formatDateTime(now)); assertThat(doc.getNullableFieldAsDate("stringDate")).isEqualToIgnoringMillis(now); doc.setField("noValue", null); assertThat(doc.getNullableFieldAsDate("noValue")).isNull(); } @Test public void getFields_fails_with_ISE_if_setParent_has_not_been_called_on_IndexRelationType() { IndexType.IndexRelationType relationType = IndexType.relation(IndexType.main(Index.withRelations("foo"), "bar"), "donut"); BaseDoc doc = new BaseDoc(relationType) { @Override public String getId() { throw new UnsupportedOperationException("getId not implemented"); } }; assertThatThrownBy(() -> doc.getFields()) .isInstanceOf(IllegalStateException.class) .hasMessage("parent must be set on a doc associated to a IndexRelationType (see BaseDoc#setParent(String))"); } @Test public void getFields_contains_join_field_and_indexType_field_when_setParent_has_been_called_on_IndexRelationType() { Index index = Index.withRelations("foo"); IndexType.IndexRelationType relationType = IndexType.relation(IndexType.main(index, "bar"), "donut"); BaseDoc doc = new BaseDoc(relationType) { { setParent("miam"); } @Override public String getId() { throw new UnsupportedOperationException("getId not implemented"); } }; Map<String, Object> fields = doc.getFields(); assertThat((Map) fields.get(index.getJoinField())) .isEqualTo(ImmutableMap.of("name", relationType.getName(), "parent", "miam")); assertThat(fields).containsEntry("indexType", relationType.getName()); } }
4,926
30.583333
126
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/startup/GeneratePluginIndexTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.startup; import java.io.File; import java.io.IOException; import java.util.List; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.core.platform.PluginInfo; import org.sonar.server.platform.ServerFileSystem; import org.sonar.server.plugins.PluginFilesAndMd5.FileAndMd5; import org.sonar.server.plugins.ServerPlugin; import org.sonar.server.plugins.ServerPluginRepository; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.core.plugin.PluginType.BUNDLED; public class GeneratePluginIndexTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); private ServerFileSystem serverFileSystem = mock(ServerFileSystem.class); private ServerPluginRepository serverPluginRepository = mock(ServerPluginRepository.class); private File index; @Before public void createIndexFile() throws IOException { index = temp.newFile(); when(serverFileSystem.getPluginIndex()).thenReturn(index); } @Test public void shouldWriteIndex() throws IOException { ServerPlugin javaPlugin = newInstalledPlugin("java", true); ServerPlugin gitPlugin = newInstalledPlugin("scmgit", false); when(serverPluginRepository.getPlugins()).thenReturn(asList(javaPlugin, gitPlugin)); GeneratePluginIndex underTest = new GeneratePluginIndex(serverFileSystem, serverPluginRepository); underTest.start(); List<String> lines = FileUtils.readLines(index); assertThat(lines).containsExactly( "java,true," + javaPlugin.getJar().getFile().getName() + "|" + javaPlugin.getJar().getMd5(), "scmgit,false," + gitPlugin.getJar().getFile().getName() + "|" + gitPlugin.getJar().getMd5()); underTest.stop(); } @Test public void shouldThrowWhenUnableToWrite() throws IOException { File wrongParent = temp.newFile(); wrongParent.createNewFile(); File wrongIndex = new File(wrongParent, "index.txt"); when(serverFileSystem.getPluginIndex()).thenReturn(wrongIndex); assertThatThrownBy(() -> new GeneratePluginIndex(serverFileSystem, serverPluginRepository).start()) .isInstanceOf(IllegalStateException.class); } private ServerPlugin newInstalledPlugin(String key, boolean supportSonarLint) throws IOException { FileAndMd5 jar = new FileAndMd5(temp.newFile()); PluginInfo pluginInfo = new PluginInfo(key).setJarFile(jar.getFile()).setSonarLintSupported(supportSonarLint); return new ServerPlugin(pluginInfo, BUNDLED, null, jar, null); } }
3,619
38.347826
114
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/test/java/org/sonar/server/startup/LogServerIdTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.startup; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.platform.Server; import org.sonar.api.testfixtures.log.LogTester; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class LogServerIdTest { @Rule public LogTester logTester = new LogTester(); @Test public void log_server_id_at_startup() { Server server = mock(Server.class); when(server.getId()).thenReturn("foo"); LogServerId underTest = new LogServerId(server); underTest.start(); assertThat(logTester.logs(Level.INFO)).contains("Server ID: foo"); // do not fail underTest.stop(); } }
1,602
30.431373
75
java