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-webapi/src/it/java/org/sonar/server/qualityprofile/builtin/BuiltInQProfileInsertImplIT.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.qualityprofile.builtin;
import java.util.Arrays;
import java.util.List;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.PropertyType;
import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
import org.sonar.api.rule.Severity;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.NewBuiltInQualityProfile;
import org.sonar.api.utils.System2;
import org.sonar.core.util.SequenceUuidFactory;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.ActiveRuleKey;
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.QProfileChangeDto;
import org.sonar.db.qualityprofile.QProfileChangeQuery;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.qualityprofile.ActiveRuleChange;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import org.sonar.server.rule.DefaultRuleFinder;
import org.sonar.server.rule.RuleDescriptionFormatter;
import org.sonar.server.rule.ServerRuleFinder;
import org.sonar.server.util.StringTypeValidation;
import org.sonar.server.util.TypeValidations;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class BuiltInQProfileInsertImplIT {
@Rule
public BuiltInQProfileRepositoryRule builtInQProfileRepository = new BuiltInQProfileRepositoryRule();
@Rule
public DbTester db = DbTester.create();
private final System2 system2 = new AlwaysIncreasingSystem2();
private final UuidFactory uuidFactory = new SequenceUuidFactory();
private final TypeValidations typeValidations = new TypeValidations(singletonList(new StringTypeValidation()));
private final DbSession dbSession = db.getSession();
private final DbSession batchDbSession = db.getDbClient().openSession(true);
private final ServerRuleFinder ruleFinder = new DefaultRuleFinder(db.getDbClient(), mock(RuleDescriptionFormatter.class));
private final ActiveRuleIndexer activeRuleIndexer = mock(ActiveRuleIndexer.class);
private final BuiltInQProfileInsertImpl underTest = new BuiltInQProfileInsertImpl(db.getDbClient(), ruleFinder, system2, uuidFactory, typeValidations, activeRuleIndexer);
@After
public void tearDown() {
batchDbSession.close();
}
@Test
public void insert_active_rules_and_changelog() {
RuleDto rule1 = db.rules().insert(r -> r.setLanguage("xoo"));
RuleDto rule2 = db.rules().insert(r -> r.setLanguage("xoo"));
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile("the name", "xoo");
newQp.activateRule(rule1.getRepositoryKey(), rule1.getRuleKey()).overrideSeverity(Severity.CRITICAL);
newQp.activateRule(rule2.getRepositoryKey(), rule2.getRuleKey()).overrideSeverity(Severity.MAJOR);
newQp.done();
BuiltInQProfile builtIn = builtInQProfileRepository.create(context.profile("xoo", "the name"), rule1, rule2);
call(builtIn);
verifyTableSize("rules_profiles", 1);
verifyTableSize("org_qprofiles", 1);
verifyTableSize("active_rules", 2);
verifyTableSize("active_rule_parameters", 0);
verifyTableSize("qprofile_changes", 2);
verifyTableSize("default_qprofiles", 0);
QProfileDto profile = verifyProfileInDb(builtIn);
verifyActiveRuleInDb(profile, rule1, Severity.CRITICAL);
verifyActiveRuleInDb(profile, rule2, Severity.MAJOR);
}
@Test
public void insert_default_qp() {
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
context.createBuiltInQualityProfile("the name", "xoo")
.setDefault(true)
.done();
BuiltInQProfile builtIn = builtInQProfileRepository.create(context.profile("xoo", "the name"));
call(builtIn);
verifyTableSize("rules_profiles", 1);
verifyTableSize("org_qprofiles", 1);
verifyTableSize("active_rules", 0);
verifyTableSize("active_rule_parameters", 0);
verifyTableSize("qprofile_changes", 0);
verifyTableSize("default_qprofiles", 1);
verifyProfileInDb(builtIn);
}
@Test
public void insert_active_rules_with_params() {
RuleDto rule1 = db.rules().insert(r -> r.setLanguage("xoo"));
RuleParamDto param1 = db.rules().insertRuleParam(rule1, p -> p.setType(PropertyType.STRING.name()));
RuleParamDto param2 = db.rules().insertRuleParam(rule1, p -> p.setType(PropertyType.STRING.name()));
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile("the name", "xoo");
newQp.activateRule(rule1.getRepositoryKey(), rule1.getRuleKey()).overrideSeverity(Severity.CRITICAL);
newQp.done();
BuiltInQProfile builtIn = builtInQProfileRepository.create(context.profile("xoo", "the name"), rule1);
call(builtIn);
verifyTableSize("rules_profiles", 1);
verifyTableSize("org_qprofiles", 1);
verifyTableSize("active_rules", 1);
verifyTableSize("active_rule_parameters", 2);
verifyTableSize("qprofile_changes", 1);
QProfileDto profile = verifyProfileInDb(builtIn);
verifyActiveRuleInDb(profile, rule1, Severity.CRITICAL, param1, param2);
}
@Test
public void flag_profile_as_default_if_declared_as_default_by_api() {
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile("the name", "xoo").setDefault(true);
newQp.done();
BuiltInQProfile builtIn = builtInQProfileRepository.create(context.profile("xoo", "the name"));
call(builtIn);
QProfileDto profile = verifyProfileInDb(builtIn);
QProfileDto defaultProfile = db.getDbClient().qualityProfileDao().selectDefaultProfile(dbSession, "xoo");
assertThat(defaultProfile.getKee()).isEqualTo(profile.getKee());
}
@Test
public void existing_default_profile_must_not_be_changed() {
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile("the name", "xoo").setDefault(true);
newQp.done();
BuiltInQProfile builtIn = builtInQProfileRepository.create(context.profile("xoo", "the name"));
QProfileDto currentDefault = db.qualityProfiles().insert(p -> p.setLanguage("xoo"));
db.qualityProfiles().setAsDefault(currentDefault);
call(builtIn);
QProfileDto defaultProfile = db.getDbClient().qualityProfileDao().selectDefaultProfile(dbSession, "xoo");
assertThat(defaultProfile.getKee()).isEqualTo(currentDefault.getKee());
verifyTableSize("rules_profiles", 2);
}
@Test
public void dont_flag_profile_as_default_if_not_declared_as_default_by_api() {
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile("the name", "xoo").setDefault(false);
newQp.done();
BuiltInQProfile builtIn = builtInQProfileRepository.create(context.profile("xoo", "the name"));
call(builtIn);
QProfileDto defaultProfile = db.getDbClient().qualityProfileDao().selectDefaultProfile(dbSession, "xoo");
assertThat(defaultProfile).isNull();
}
// TODO test lot of active_rules, params, orgas
private void verifyActiveRuleInDb(QProfileDto profile, RuleDto rule, String expectedSeverity, RuleParamDto... paramDtos) {
ActiveRuleDto activeRule = db.getDbClient().activeRuleDao().selectByKey(dbSession, ActiveRuleKey.of(profile, rule.getKey())).get();
assertThat(activeRule.getUuid()).isNotNull();
assertThat(activeRule.getInheritance()).isNull();
assertThat(activeRule.doesOverride()).isFalse();
assertThat(activeRule.getRuleUuid()).isEqualTo(rule.getUuid());
assertThat(activeRule.getProfileUuid()).isEqualTo(profile.getRulesProfileUuid());
assertThat(activeRule.getSeverityString()).isEqualTo(expectedSeverity);
assertThat(activeRule.getCreatedAt()).isPositive();
assertThat(activeRule.getUpdatedAt()).isPositive();
List<ActiveRuleParamDto> params = db.getDbClient().activeRuleDao().selectParamsByActiveRuleUuid(dbSession, activeRule.getUuid());
assertThat(params).extracting(ActiveRuleParamDto::getKey).containsOnly(Arrays.stream(paramDtos).map(RuleParamDto::getName).toArray(String[]::new));
QProfileChangeQuery changeQuery = new QProfileChangeQuery(profile.getKee());
QProfileChangeDto change = db.getDbClient().qProfileChangeDao().selectByQuery(dbSession, changeQuery).stream()
.filter(c -> c.getDataAsMap().get("ruleUuid").equals(rule.getUuid()))
.findFirst()
.get();
assertThat(change.getChangeType()).isEqualTo(ActiveRuleChange.Type.ACTIVATED.name());
assertThat(change.getCreatedAt()).isPositive();
assertThat(change.getUuid()).isNotEmpty();
assertThat(change.getUserUuid()).isNull();
assertThat(change.getRulesProfileUuid()).isEqualTo(profile.getRulesProfileUuid());
assertThat(change.getDataAsMap()).containsEntry("severity", expectedSeverity);
}
private QProfileDto verifyProfileInDb(BuiltInQProfile builtIn) {
QProfileDto profileOnOrg1 = db.getDbClient().qualityProfileDao().selectByNameAndLanguage(dbSession, builtIn.getName(), builtIn.getLanguage());
assertThat(profileOnOrg1.getLanguage()).isEqualTo(builtIn.getLanguage());
assertThat(profileOnOrg1.getName()).isEqualTo(builtIn.getName());
assertThat(profileOnOrg1.getParentKee()).isNull();
assertThat(profileOnOrg1.getLastUsed()).isNull();
assertThat(profileOnOrg1.getUserUpdatedAt()).isNull();
assertThat(profileOnOrg1.getRulesUpdatedAt()).isNotEmpty();
assertThat(profileOnOrg1.getKee()).isNotEqualTo(profileOnOrg1.getRulesProfileUuid());
assertThat(profileOnOrg1.getRulesProfileUuid()).isNotNull();
return profileOnOrg1;
}
private void verifyTableSize(String table, int expectedSize) {
assertThat(db.countRowsOfTable(dbSession, table)).as("table " + table).isEqualTo(expectedSize);
}
private void call(BuiltInQProfile builtIn) {
underTest.create(dbSession, builtIn);
dbSession.commit();
batchDbSession.commit();
}
}
| 11,417 | 45.040323 | 172 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/builtin/BuiltInQProfileRepositoryImplIT.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.qualityprofile.builtin;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.qualityprofile.builtin.BuiltInQProfile.ActiveRule;
import org.sonar.server.rule.DefaultRuleFinder;
import org.sonar.server.rule.RuleDescriptionFormatter;
import org.sonar.server.rule.ServerRuleFinder;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.groups.Tuple.tuple;
import static org.mockito.Mockito.mock;
import static org.sonar.db.rule.RuleTesting.EXTERNAL_XOO;
public class BuiltInQProfileRepositoryImplIT {
private static final Language FOO_LANGUAGE = LanguageTesting.newLanguage("foo", "foo", "foo");
private static final String SONAR_WAY_QP_NAME = "Sonar way";
@Rule
public DbTester db = DbTester.create();
private final DbClient dbClient = db.getDbClient();
private final ServerRuleFinder ruleFinder = new DefaultRuleFinder(dbClient, mock(RuleDescriptionFormatter.class));
@Test
public void create_qprofile_with_rule() {
RuleDto rule1 = db.rules().insert();
RuleDto rule2 = db.rules().insert();
db.rules().insert();
DummyProfileDefinition definition = new DummyProfileDefinition("foo", "foo", false, asList(rule1.getKey(), rule2.getKey()));
BuiltInQProfileRepository underTest = new BuiltInQProfileRepositoryImpl(dbClient, ruleFinder, new Languages(FOO_LANGUAGE), definition);
underTest.initialize();
assertThat(underTest.get())
.extracting(BuiltInQProfile::getName)
.containsExactlyInAnyOrder("foo");
assertThat(underTest.get().get(0).getActiveRules())
.extracting(ActiveRule::getRuleUuid, ActiveRule::getRuleKey)
.containsExactlyInAnyOrder(
tuple(rule1.getUuid(), rule1.getKey()),
tuple(rule2.getUuid(), rule2.getKey()));
}
@Test
public void make_single_profile_of_a_language_default_even_if_not_flagged_as_so() {
BuiltInQProfileRepository underTest = new BuiltInQProfileRepositoryImpl(dbClient, ruleFinder, new Languages(FOO_LANGUAGE),
new DummyProfileDefinition("foo", "foo1", false));
underTest.initialize();
assertThat(underTest.get())
.extracting(BuiltInQProfile::getLanguage, BuiltInQProfile::isDefault)
.containsExactly(tuple(FOO_LANGUAGE.getKey(), true));
}
@Test
public void make_single_profile_of_a_language_default_even_if_flagged_as_so() {
BuiltInQProfileRepository underTest = new BuiltInQProfileRepositoryImpl(dbClient, ruleFinder, new Languages(FOO_LANGUAGE),
new DummyProfileDefinition("foo", "foo1", true));
underTest.initialize();
assertThat(underTest.get())
.extracting(BuiltInQProfile::getLanguage, BuiltInQProfile::isDefault)
.containsExactly(tuple(FOO_LANGUAGE.getKey(), true));
}
@Test
public void make_first_profile_of_a_language_default_when_none_flagged_as_so() {
DummyProfileDefinition[] definitions = new DummyProfileDefinition[] {new DummyProfileDefinition("foo", "foo1", false), new DummyProfileDefinition("foo", "foo2", false)};
String firstName = definitions[0].getName();
String secondName = definitions[1].getName();
BuiltInQProfileRepository underTest = new BuiltInQProfileRepositoryImpl(dbClient, ruleFinder, new Languages(FOO_LANGUAGE), definitions);
underTest.initialize();
assertThat(underTest.get())
.extracting(BuiltInQProfile::getName, BuiltInQProfile::isDefault)
.containsExactlyInAnyOrder(tuple(firstName, true), tuple(secondName, false));
}
@Test
public void create_profile_Sonar_Way_as_default_if_none_other_is_defined_default_for_a_given_language() {
BuiltInQProfileRepository underTest = new BuiltInQProfileRepositoryImpl(
dbClient, ruleFinder, new Languages(FOO_LANGUAGE),
new DummyProfileDefinition("foo", "doh", false), new DummyProfileDefinition("foo", "boo", false),
new DummyProfileDefinition("foo", SONAR_WAY_QP_NAME, false), new DummyProfileDefinition("foo", "goo", false));
underTest.initialize();
assertThat(underTest.get())
.filteredOn(b -> FOO_LANGUAGE.getKey().equals(b.getLanguage()))
.filteredOn(BuiltInQProfile::isDefault)
.extracting(BuiltInQProfile::getName)
.containsExactly(SONAR_WAY_QP_NAME);
}
@Test
public void do_not_create_Sonar_Way_as_default_if_other_profile_is_defined_as_default() {
BuiltInQProfileRepository underTest = new BuiltInQProfileRepositoryImpl(
dbClient, ruleFinder, new Languages(FOO_LANGUAGE),
new DummyProfileDefinition("foo", SONAR_WAY_QP_NAME, false), new DummyProfileDefinition("foo", "goo", true));
underTest.initialize();
assertThat(underTest.get())
.filteredOn(b -> FOO_LANGUAGE.getKey().equals(b.getLanguage()))
.filteredOn(BuiltInQProfile::isDefault)
.extracting(BuiltInQProfile::getName)
.containsExactly("goo");
}
@Test
public void match_Sonar_Way_default_with_case_sensitivity() {
String sonarWayInOtherCase = SONAR_WAY_QP_NAME.toUpperCase();
BuiltInQProfileRepository underTest = new BuiltInQProfileRepositoryImpl(
dbClient, ruleFinder, new Languages(FOO_LANGUAGE),
new DummyProfileDefinition("foo", "goo", false), new DummyProfileDefinition("foo", sonarWayInOtherCase, false));
underTest.initialize();
assertThat(underTest.get())
.filteredOn(b -> FOO_LANGUAGE.getKey().equals(b.getLanguage()))
.filteredOn(BuiltInQProfile::isDefault)
.extracting(BuiltInQProfile::getName)
.containsExactly("goo");
}
@Test
public void create_no_BuiltInQProfile_when_all_definitions_apply_to_non_defined_languages() {
BuiltInQProfileRepository underTest = new BuiltInQProfileRepositoryImpl(mock(DbClient.class), ruleFinder, new Languages(),
new DummyProfileDefinition("foo", "P1", false));
underTest.initialize();
assertThat(underTest.get()).isEmpty();
}
@Test
public void create_qprofile_with_deprecated_rule() {
RuleDto rule1 = db.rules().insert();
db.rules().insertDeprecatedKey(d -> d.setRuleUuid(rule1.getUuid()).setOldRepositoryKey("oldRepo").setOldRuleKey("oldKey"));
RuleDto rule2 = db.rules().insert();
DummyProfileDefinition definition = new DummyProfileDefinition("foo", "foo", false,
asList(RuleKey.of("oldRepo", "oldKey"), rule2.getKey()));
BuiltInQProfileRepository underTest = new BuiltInQProfileRepositoryImpl(dbClient, ruleFinder, new Languages(FOO_LANGUAGE), definition);
underTest.initialize();
assertThat(underTest.get())
.extracting(BuiltInQProfile::getName)
.containsExactlyInAnyOrder("foo");
assertThat(underTest.get().get(0).getActiveRules())
.extracting(ActiveRule::getRuleUuid, ActiveRule::getRuleKey)
.containsExactlyInAnyOrder(
tuple(rule1.getUuid(), rule1.getKey()),
tuple(rule2.getUuid(), rule2.getKey()));
}
@Test
public void fail_with_ISE_when_rule_does_not_exist() {
DummyProfileDefinition[] definitions = new DummyProfileDefinition[] {new DummyProfileDefinition("foo", "foo", false, singletonList(EXTERNAL_XOO))};
BuiltInQProfileRepository underTest = new BuiltInQProfileRepositoryImpl(dbClient, ruleFinder, new Languages(FOO_LANGUAGE), definitions);
assertThatThrownBy(underTest::initialize)
.isInstanceOf(IllegalStateException.class)
.hasMessage(String.format("Rule with key '%s' not found", EXTERNAL_XOO));
}
@Test
public void fail_with_ISE_when_two_profiles_with_different_name_are_default_for_the_same_language() {
BuiltInQProfileRepository underTest = new BuiltInQProfileRepositoryImpl(dbClient, ruleFinder, new Languages(FOO_LANGUAGE),
new DummyProfileDefinition("foo", "foo1", true), new DummyProfileDefinition("foo", "foo2", true));
assertThatThrownBy(underTest::initialize)
.isInstanceOf(IllegalStateException.class)
.hasMessage("Several Quality profiles are flagged as default for the language foo: [foo1, foo2]");
}
@Test
public void get_throws_ISE_if_called_before_initialize() {
BuiltInQProfileRepositoryImpl underTest = new BuiltInQProfileRepositoryImpl(mock(DbClient.class), ruleFinder, new Languages());
assertThatThrownBy(underTest::get)
.isInstanceOf(IllegalStateException.class)
.hasMessage("initialize must be called first");
}
@Test
public void initialize_throws_ISE_if_called_twice() {
BuiltInQProfileRepositoryImpl underTest = new BuiltInQProfileRepositoryImpl(mock(DbClient.class), ruleFinder, new Languages());
underTest.initialize();
assertThatThrownBy(underTest::initialize)
.isInstanceOf(IllegalStateException.class)
.hasMessage("initialize must be called only once");
}
@Test
public void initialize_throws_ISE_if_language_has_no_builtin_qp() {
BuiltInQProfileRepository underTest = new BuiltInQProfileRepositoryImpl(mock(DbClient.class), ruleFinder, new Languages(FOO_LANGUAGE));
assertThatThrownBy(underTest::initialize)
.isInstanceOf(IllegalStateException.class)
.hasMessage("The following languages have no built-in quality profiles: foo");
}
private static final class DummyProfileDefinition implements BuiltInQualityProfilesDefinition {
private final String language;
private final String name;
private final boolean defaultProfile;
private final List<RuleKey> activeRuleKeys;
private DummyProfileDefinition(String language, String name, boolean defaultProfile, List<RuleKey> activeRuleKeys) {
this.language = language;
this.name = name;
this.defaultProfile = defaultProfile;
this.activeRuleKeys = activeRuleKeys;
}
private DummyProfileDefinition(String language, String name, boolean defaultProfile) {
this(language, name, defaultProfile, emptyList());
}
@Override
public void define(Context context) {
NewBuiltInQualityProfile builtInQualityProfile = context.createBuiltInQualityProfile(name, language);
activeRuleKeys.forEach(activeRuleKey -> builtInQualityProfile.activateRule(activeRuleKey.repository(), activeRuleKey.rule()));
builtInQualityProfile.setDefault(defaultProfile);
builtInQualityProfile.done();
}
String getName() {
return name;
}
}
}
| 11,574 | 41.244526 | 173 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/builtin/BuiltInQProfileRepositoryRule.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.qualityprofile.builtin;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.junit.rules.ExternalResource;
import org.sonar.api.resources.Language;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition;
import org.sonar.db.rule.RuleDto;
import static com.google.common.base.Preconditions.checkState;
public class BuiltInQProfileRepositoryRule extends ExternalResource implements BuiltInQProfileRepository {
private boolean initializeCalled = false;
private List<BuiltInQProfile> profiles = new ArrayList<>();
@Override
protected void before() {
this.initializeCalled = false;
this.profiles.clear();
}
@Override
public void initialize() {
checkState(!initializeCalled, "initialize must be called only once");
this.initializeCalled = true;
}
@Override
public List<BuiltInQProfile> get() {
checkState(initializeCalled, "initialize must be called first");
return ImmutableList.copyOf(profiles);
}
public boolean isInitialized() {
return initializeCalled;
}
public BuiltInQProfile add(Language language, String profileName) {
return add(language, profileName, false);
}
public BuiltInQProfile add(Language language, String profileName, boolean isDefault) {
return add(language, profileName, isDefault, new BuiltInQProfile.ActiveRule[0]);
}
public BuiltInQProfile add(Language language, String profileName, boolean isDefault, BuiltInQProfile.ActiveRule... rules) {
BuiltInQProfile builtIn = create(language, profileName, isDefault, rules);
profiles.add(builtIn);
return builtIn;
}
public BuiltInQProfile create(Language language, String profileName, boolean isDefault, BuiltInQProfile.ActiveRule... rules) {
BuiltInQProfile.Builder builder = new BuiltInQProfile.Builder()
.setLanguage(language.getKey())
.setName(profileName)
.setDeclaredDefault(isDefault);
Arrays.stream(rules).forEach(builder::addRule);
return builder.build();
}
public BuiltInQProfile create(BuiltInQualityProfilesDefinition.BuiltInQualityProfile api, RuleDto... rules) {
BuiltInQProfile.Builder builder = new BuiltInQProfile.Builder()
.setLanguage(api.language())
.setName(api.name())
.setDeclaredDefault(api.isDefault());
Map<RuleKey, RuleDto> rulesByRuleKey = Arrays.stream(rules)
.collect(Collectors.toMap(RuleDto::getKey, Function.identity()));
api.rules().forEach(rule -> {
RuleKey ruleKey = RuleKey.of(rule.repoKey(), rule.ruleKey());
RuleDto ruleDto = rulesByRuleKey.get(ruleKey);
Preconditions.checkState(ruleDto != null, "Rule '%s' not found", ruleKey);
builder.addRule(new BuiltInQProfile.ActiveRule(ruleDto.getUuid(), rule));
});
return builder
.build();
}
}
| 3,885 | 36.009524 | 128 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/builtin/BuiltInQProfileUpdateImplIT.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.qualityprofile.builtin;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import org.assertj.core.groups.Tuple;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RulePriority;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.NewBuiltInQualityProfile;
import org.sonar.api.utils.System2;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.ActiveRuleKey;
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.OrgActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.RulesProfileDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
import org.sonar.server.qualityprofile.ActiveRuleChange;
import org.sonar.server.qualityprofile.ActiveRuleInheritance;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.util.IntegerTypeValidation;
import org.sonar.server.util.StringTypeValidation;
import org.sonar.server.util.TypeValidations;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.groups.Tuple.tuple;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.sonar.api.rules.RulePriority.BLOCKER;
import static org.sonar.api.rules.RulePriority.CRITICAL;
import static org.sonar.api.rules.RulePriority.MAJOR;
import static org.sonar.api.rules.RulePriority.MINOR;
import static org.sonar.db.qualityprofile.QualityProfileTesting.newRuleProfileDto;
import static org.sonar.server.qualityprofile.ActiveRuleInheritance.INHERITED;
public class BuiltInQProfileUpdateImplIT {
private static final long NOW = 1_000;
private static final long PAST = NOW - 100;
@Rule
public BuiltInQProfileRepositoryRule builtInProfileRepository = new BuiltInQProfileRepositoryRule();
@Rule
public DbTester db = DbTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private System2 system2 = new TestSystem2().setNow(NOW);
private ActiveRuleIndexer activeRuleIndexer = mock(ActiveRuleIndexer.class);
private TypeValidations typeValidations = new TypeValidations(asList(new StringTypeValidation(), new IntegerTypeValidation()));
private QualityProfileChangeEventService qualityProfileChangeEventService = mock(QualityProfileChangeEventService.class);
private RuleActivator ruleActivator = new RuleActivator(system2, db.getDbClient(), typeValidations, userSession);
private BuiltInQProfileUpdateImpl underTest = new BuiltInQProfileUpdateImpl(db.getDbClient(), ruleActivator, activeRuleIndexer,
qualityProfileChangeEventService);
private RulesProfileDto persistedProfile;
@Before
public void setUp() {
persistedProfile = newRuleProfileDto(rp -> rp
.setIsBuiltIn(true)
.setLanguage("xoo")
.setRulesUpdatedAt(null));
db.getDbClient().qualityProfileDao().insert(db.getSession(), persistedProfile);
db.commit();
}
@Test
public void activate_new_rules() {
RuleDto rule1 = db.rules().insert(r -> r.setLanguage("xoo"));
RuleDto rule2 = db.rules().insert(r -> r.setLanguage("xoo"));
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile("Sonar way", "xoo");
newQp.activateRule(rule1.getRepositoryKey(), rule1.getRuleKey()).overrideSeverity(Severity.CRITICAL);
newQp.activateRule(rule2.getRepositoryKey(), rule2.getRuleKey()).overrideSeverity(Severity.MAJOR);
newQp.done();
BuiltInQProfile builtIn = builtInProfileRepository.create(context.profile("xoo", "Sonar way"), rule1, rule2);
List<ActiveRuleChange> changes = underTest.update(db.getSession(), builtIn, persistedProfile);
List<ActiveRuleDto> activeRules = db.getDbClient().activeRuleDao().selectByRuleProfile(db.getSession(), persistedProfile);
assertThat(activeRules).hasSize(2);
assertThatRuleIsNewlyActivated(activeRules, rule1, CRITICAL);
assertThatRuleIsNewlyActivated(activeRules, rule2, MAJOR);
assertThatProfileIsMarkedAsUpdated(persistedProfile);
verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(persistedProfile.getLanguage()));
}
@Test
public void already_activated_rule_is_updated_in_case_of_differences() {
RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo"));
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile("Sonar way", "xoo");
newQp.activateRule(rule.getRepositoryKey(), rule.getRuleKey()).overrideSeverity(Severity.CRITICAL);
newQp.done();
BuiltInQProfile builtIn = builtInProfileRepository.create(context.profile("xoo", "Sonar way"), rule);
activateRuleInDb(persistedProfile, rule, BLOCKER);
List<ActiveRuleChange> changes = underTest.update(db.getSession(), builtIn, persistedProfile);
List<ActiveRuleDto> activeRules = db.getDbClient().activeRuleDao().selectByRuleProfile(db.getSession(), persistedProfile);
assertThat(activeRules).hasSize(1);
assertThatRuleIsUpdated(activeRules, rule, CRITICAL);
assertThatProfileIsMarkedAsUpdated(persistedProfile);
verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(persistedProfile.getLanguage()));
}
@Test
public void already_activated_rule_is_not_touched_if_no_differences() {
RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo"));
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile("Sonar way", "xoo");
newQp.activateRule(rule.getRepositoryKey(), rule.getRuleKey()).overrideSeverity(Severity.CRITICAL);
newQp.done();
BuiltInQProfile builtIn = builtInProfileRepository.create(context.profile("xoo", "Sonar way"), rule);
activateRuleInDb(persistedProfile, rule, CRITICAL);
underTest.update(db.getSession(), builtIn, persistedProfile);
List<ActiveRuleDto> activeRules = db.getDbClient().activeRuleDao().selectByRuleProfile(db.getSession(), persistedProfile);
assertThat(activeRules).hasSize(1);
assertThatRuleIsUntouched(activeRules, rule, CRITICAL);
assertThatProfileIsNotMarkedAsUpdated(persistedProfile);
verifyNoInteractions(qualityProfileChangeEventService);
}
@Test
public void deactivate_rule_that_is_not_in_built_in_definition_anymore() {
RuleDto rule1 = db.rules().insert(r -> r.setLanguage("xoo"));
RuleDto rule2 = db.rules().insert(r -> r.setLanguage("xoo"));
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile("Sonar way", "xoo");
newQp.activateRule(rule2.getRepositoryKey(), rule2.getRuleKey()).overrideSeverity(Severity.MAJOR);
newQp.done();
BuiltInQProfile builtIn = builtInProfileRepository.create(context.profile("xoo", "Sonar way"), rule1, rule2);
// built-in definition contains only rule2
// so rule1 must be deactivated
activateRuleInDb(persistedProfile, rule1, CRITICAL);
List<ActiveRuleChange> changes = underTest.update(db.getSession(), builtIn, persistedProfile);
List<ActiveRuleDto> activeRules = db.getDbClient().activeRuleDao().selectByRuleProfile(db.getSession(), persistedProfile);
assertThat(activeRules).hasSize(1);
assertThatRuleIsDeactivated(activeRules, rule1);
assertThatProfileIsMarkedAsUpdated(persistedProfile);
verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(persistedProfile.getLanguage()));
}
@Test
public void activate_deactivate_and_update_three_rules_at_the_same_time() {
RuleDto rule1 = db.rules().insert(r -> r.setLanguage("xoo"));
RuleDto rule2 = db.rules().insert(r -> r.setLanguage("xoo"));
RuleDto rule3 = db.rules().insert(r -> r.setLanguage("xoo"));
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile("Sonar way", "xoo");
newQp.activateRule(rule1.getRepositoryKey(), rule1.getRuleKey()).overrideSeverity(Severity.CRITICAL);
newQp.activateRule(rule2.getRepositoryKey(), rule2.getRuleKey()).overrideSeverity(Severity.MAJOR);
newQp.done();
BuiltInQProfile builtIn = builtInProfileRepository.create(context.profile("xoo", "Sonar way"), rule1, rule2);
// rule1 must be updated (blocker to critical)
// rule2 must be activated
// rule3 must be deactivated
activateRuleInDb(persistedProfile, rule1, BLOCKER);
activateRuleInDb(persistedProfile, rule3, BLOCKER);
List<ActiveRuleChange> changes = underTest.update(db.getSession(), builtIn, persistedProfile);
List<ActiveRuleDto> activeRules = db.getDbClient().activeRuleDao().selectByRuleProfile(db.getSession(), persistedProfile);
assertThat(activeRules).hasSize(2);
assertThatRuleIsUpdated(activeRules, rule1, CRITICAL);
assertThatRuleIsNewlyActivated(activeRules, rule2, MAJOR);
assertThatRuleIsDeactivated(activeRules, rule3);
assertThatProfileIsMarkedAsUpdated(persistedProfile);
verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(persistedProfile.getLanguage()));
}
// SONAR-10473
@Test
public void activate_rule_on_built_in_profile_resets_severity_to_default_if_not_overridden() {
RuleDto rule = db.rules().insert(r -> r.setSeverity(Severity.MAJOR).setLanguage("xoo"));
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile("Sonar way", "xoo");
newQp.activateRule(rule.getRepositoryKey(), rule.getRuleKey());
newQp.done();
BuiltInQProfile builtIn = builtInProfileRepository.create(context.profile("xoo", "Sonar way"), rule);
underTest.update(db.getSession(), builtIn, persistedProfile);
List<ActiveRuleDto> activeRules = db.getDbClient().activeRuleDao().selectByRuleProfile(db.getSession(), persistedProfile);
assertThatRuleIsNewlyActivated(activeRules, rule, MAJOR);
// emulate an upgrade of analyzer that changes the default severity of the rule
rule.setSeverity(Severity.MINOR);
db.rules().update(rule);
List<ActiveRuleChange> changes = underTest.update(db.getSession(), builtIn, persistedProfile);
activeRules = db.getDbClient().activeRuleDao().selectByRuleProfile(db.getSession(), persistedProfile);
assertThatRuleIsNewlyActivated(activeRules, rule, MINOR);
verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(persistedProfile.getLanguage()));
}
@Test
public void activate_rule_on_built_in_profile_resets_params_to_default_if_not_overridden() {
RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo"));
RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue("10"));
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile("Sonar way", rule.getLanguage());
newQp.activateRule(rule.getRepositoryKey(), rule.getRuleKey());
newQp.done();
BuiltInQProfile builtIn = builtInProfileRepository.create(context.profile(newQp.language(), newQp.name()), rule);
List<ActiveRuleChange> changes = underTest.update(db.getSession(), builtIn, persistedProfile);
List<ActiveRuleDto> activeRules = db.getDbClient().activeRuleDao().selectByRuleProfile(db.getSession(), persistedProfile);
assertThat(activeRules).hasSize(1);
assertThatRuleHasParams(db, activeRules.get(0), tuple("min", "10"));
verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(persistedProfile.getLanguage()));
// emulate an upgrade of analyzer that changes the default value of parameter min
ruleParam.setDefaultValue("20");
db.getDbClient().ruleDao().updateRuleParam(db.getSession(), rule, ruleParam);
changes = underTest.update(db.getSession(), builtIn, persistedProfile);
activeRules = db.getDbClient().activeRuleDao().selectByRuleProfile(db.getSession(), persistedProfile);
assertThat(activeRules).hasSize(1);
assertThatRuleHasParams(db, activeRules.get(0), tuple("min", "20"));
verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(persistedProfile.getLanguage()));
}
@Test
public void propagate_activation_to_descendant_profiles() {
RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo"));
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()).setIsBuiltIn(true));
QProfileDto childProfile = createChildProfile(profile);
QProfileDto grandchildProfile = createChildProfile(childProfile);
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile(profile.getName(), profile.getLanguage());
newQp.activateRule(rule.getRepositoryKey(), rule.getRuleKey());
newQp.done();
BuiltInQProfile builtIn = builtInProfileRepository.create(context.profile(profile.getLanguage(), profile.getName()), rule);
List<ActiveRuleChange> changes = underTest.update(db.getSession(), builtIn, RulesProfileDto.from(profile));
assertThat(changes).hasSize(3);
assertThatRuleIsActivated(profile, rule, changes, rule.getSeverityString(), null, emptyMap());
assertThatRuleIsActivated(childProfile, rule, changes, rule.getSeverityString(), INHERITED, emptyMap());
assertThatRuleIsActivated(grandchildProfile, rule, changes, rule.getSeverityString(), INHERITED, emptyMap());
verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(persistedProfile.getLanguage()));
}
// SONAR-14559
@Test
public void propagate_rule_update_to_descendant_active_rule() {
RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo").setSeverity(Severity.BLOCKER));
QProfileDto parentProfile = db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()).setIsBuiltIn(true));
activateRuleInDb(RulesProfileDto.from(parentProfile), rule, RulePriority.valueOf(Severity.MINOR), null);
QProfileDto childProfile = createChildProfile(parentProfile);
activateRuleInDb(RulesProfileDto.from(childProfile), rule, RulePriority.valueOf(Severity.MINOR), INHERITED);
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile(parentProfile.getName(), parentProfile.getLanguage());
newQp.activateRule(rule.getRepositoryKey(), rule.getRuleKey());
newQp.done();
BuiltInQProfile builtIn = builtInProfileRepository.create(context.profile(parentProfile.getLanguage(), parentProfile.getName()), rule);
List<ActiveRuleChange> changes = underTest.update(db.getSession(), builtIn, RulesProfileDto.from(parentProfile));
assertThat(changes).hasSize(2);
List<ActiveRuleDto> parentActiveRules = db.getDbClient().activeRuleDao().selectByRuleProfile(db.getSession(), RulesProfileDto.from(parentProfile));
assertThatRuleIsUpdated(parentActiveRules, rule, RulePriority.BLOCKER, null);
List<ActiveRuleDto> childActiveRules = db.getDbClient().activeRuleDao().selectByRuleProfile(db.getSession(), RulesProfileDto.from(childProfile));
assertThatRuleIsUpdated(childActiveRules, rule, RulePriority.BLOCKER, INHERITED);
verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(persistedProfile.getLanguage()));
}
@Test
public void propagate_rule_param_update_to_descendant_active_rule_params() {
RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo").setSeverity(Severity.BLOCKER));
RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue("10"));
QProfileDto parentProfile = db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()).setIsBuiltIn(true));
ActiveRuleDto parentActiveRuleDto = activateRuleInDb(RulesProfileDto.from(parentProfile), rule,
RulePriority.valueOf(Severity.MINOR), null);
activateRuleParamInDb(parentActiveRuleDto, ruleParam, "20");
QProfileDto childProfile = createChildProfile(parentProfile);
ActiveRuleDto childActiveRuleDto = activateRuleInDb(RulesProfileDto.from(childProfile), rule,
RulePriority.valueOf(Severity.MINOR), INHERITED);
activateRuleParamInDb(childActiveRuleDto, ruleParam, "20");
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile(parentProfile.getName(), parentProfile.getLanguage());
newQp.activateRule(rule.getRepositoryKey(), rule.getRuleKey());
newQp.done();
BuiltInQProfile builtIn = builtInProfileRepository.create(context.profile(parentProfile.getLanguage(), parentProfile.getName()), rule);
List<ActiveRuleChange> changes = underTest.update(db.getSession(), builtIn, RulesProfileDto.from(parentProfile));
assertThat(changes).hasSize(2);
assertThatRuleHasParams(db, parentActiveRuleDto, tuple("min", "10"));
assertThatRuleHasParams(db, childActiveRuleDto, tuple("min", "10"));
verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(persistedProfile.getLanguage()));
}
@Test
public void do_not_load_descendants_if_no_changes() {
RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo"));
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()).setIsBuiltIn(true));
QProfileDto childProfile = createChildProfile(profile);
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile(profile.getName(), profile.getLanguage());
newQp.activateRule(rule.getRepositoryKey(), rule.getRuleKey());
newQp.done();
// first run
BuiltInQProfile builtIn = builtInProfileRepository.create(context.profile(profile.getLanguage(), profile.getName()), rule);
List<ActiveRuleChange> changes = underTest.update(db.getSession(), builtIn, RulesProfileDto.from(profile));
assertThat(changes).hasSize(2).extracting(ActiveRuleChange::getType).containsOnly(ActiveRuleChange.Type.ACTIVATED);
verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(persistedProfile.getLanguage()));
// second run, without any input changes
RuleActivator ruleActivatorWithoutDescendants = new RuleActivator(system2, db.getDbClient(), typeValidations, userSession) {
@Override
DescendantProfilesSupplier createDescendantProfilesSupplier(DbSession dbSession) {
return (profiles, ruleIds) -> {
throw new IllegalStateException("BOOM - descendants should not be loaded");
};
}
};
changes = new BuiltInQProfileUpdateImpl(db.getDbClient(), ruleActivatorWithoutDescendants, activeRuleIndexer, qualityProfileChangeEventService)
.update(db.getSession(), builtIn, RulesProfileDto.from(profile));
assertThat(changes).isEmpty();
verifyNoMoreInteractions(qualityProfileChangeEventService);
}
@Test
public void propagate_deactivation_to_descendant_profiles() {
RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo"));
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()).setIsBuiltIn(true));
QProfileDto childProfile = createChildProfile(profile);
QProfileDto grandChildProfile = createChildProfile(childProfile);
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile(profile.getName(), profile.getLanguage());
newQp.activateRule(rule.getRepositoryKey(), rule.getRuleKey());
newQp.done();
// first run to activate the rule
BuiltInQProfile builtIn = builtInProfileRepository.create(context.profile(profile.getLanguage(), profile.getName()), rule);
List<ActiveRuleChange> changes = underTest.update(db.getSession(), builtIn, RulesProfileDto.from(profile));
assertThat(changes).hasSize(3).extracting(ActiveRuleChange::getType).containsOnly(ActiveRuleChange.Type.ACTIVATED);
verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(persistedProfile.getLanguage()));
// second run to deactivate the rule
context = new BuiltInQualityProfilesDefinition.Context();
NewBuiltInQualityProfile updatedQp = context.createBuiltInQualityProfile(profile.getName(), profile.getLanguage());
updatedQp.done();
builtIn = builtInProfileRepository.create(context.profile(profile.getLanguage(), profile.getName()), rule);
changes = underTest.update(db.getSession(), builtIn, RulesProfileDto.from(profile));
assertThat(changes).hasSize(3).extracting(ActiveRuleChange::getType).containsOnly(ActiveRuleChange.Type.DEACTIVATED);
verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(persistedProfile.getLanguage()));
assertThatRuleIsDeactivated(profile, rule);
assertThatRuleIsDeactivated(childProfile, rule);
assertThatRuleIsDeactivated(grandChildProfile, rule);
}
private QProfileDto createChildProfile(QProfileDto parent) {
return db.qualityProfiles().insert(p -> p
.setLanguage(parent.getLanguage())
.setParentKee(parent.getKee())
.setName("Child of " + parent.getName()))
.setIsBuiltIn(false);
}
private void assertThatRuleIsActivated(QProfileDto profile, RuleDto rule, @Nullable List<ActiveRuleChange> changes,
String expectedSeverity, @Nullable ActiveRuleInheritance expectedInheritance, Map<String, String> expectedParams) {
OrgActiveRuleDto activeRule = db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile)
.stream()
.filter(ar -> ar.getRuleKey().equals(rule.getKey()))
.findFirst()
.orElseThrow(IllegalStateException::new);
assertThat(activeRule.getSeverityString()).isEqualTo(expectedSeverity);
assertThat(activeRule.getInheritance()).isEqualTo(expectedInheritance != null ? expectedInheritance.name() : null);
List<ActiveRuleParamDto> params = db.getDbClient().activeRuleDao().selectParamsByActiveRuleUuid(db.getSession(), activeRule.getUuid());
assertThat(params).hasSize(expectedParams.size());
if (changes != null) {
ActiveRuleChange change = changes.stream()
.filter(c -> c.getActiveRule().getUuid().equals(activeRule.getUuid()))
.findFirst().orElseThrow(IllegalStateException::new);
assertThat(change.getInheritance()).isEqualTo(expectedInheritance);
assertThat(change.getSeverity()).isEqualTo(expectedSeverity);
assertThat(change.getType()).isEqualTo(ActiveRuleChange.Type.ACTIVATED);
}
}
private static void assertThatRuleHasParams(DbTester db, ActiveRuleDto activeRule, Tuple... expectedParams) {
assertThat(db.getDbClient().activeRuleDao().selectParamsByActiveRuleUuid(db.getSession(), activeRule.getUuid()))
.extracting(ActiveRuleParamDto::getKey, ActiveRuleParamDto::getValue)
.containsExactlyInAnyOrder(expectedParams);
}
private static void assertThatRuleIsNewlyActivated(List<ActiveRuleDto> activeRules, RuleDto rule, RulePriority severity) {
ActiveRuleDto activeRule = findRule(activeRules, rule).get();
assertThat(activeRule.getInheritance()).isNull();
assertThat(activeRule.getSeverityString()).isEqualTo(severity.name());
assertThat(activeRule.getCreatedAt()).isEqualTo(NOW);
assertThat(activeRule.getUpdatedAt()).isEqualTo(NOW);
}
private static void assertThatRuleIsUpdated(List<ActiveRuleDto> activeRules, RuleDto rule, RulePriority severity, @Nullable ActiveRuleInheritance expectedInheritance) {
ActiveRuleDto activeRule = findRule(activeRules, rule).get();
if (expectedInheritance != null) {
assertThat(activeRule.getInheritance()).isEqualTo(expectedInheritance.name());
} else {
assertThat(activeRule.getInheritance()).isNull();
}
assertThat(activeRule.getSeverityString()).isEqualTo(severity.name());
assertThat(activeRule.getCreatedAt()).isEqualTo(PAST);
assertThat(activeRule.getUpdatedAt()).isEqualTo(NOW);
}
private static void assertThatRuleIsUpdated(List<ActiveRuleDto> activeRules, RuleDto rule, RulePriority severity) {
assertThatRuleIsUpdated(activeRules, rule, severity, null);
}
private static void assertThatRuleIsUpdated(ActiveRuleDto activeRules, RuleDto rule, RulePriority severity, @Nullable ActiveRuleInheritance expectedInheritance) {
assertThatRuleIsUpdated(singletonList(activeRules), rule, severity, expectedInheritance);
}
private static void assertThatRuleIsUntouched(List<ActiveRuleDto> activeRules, RuleDto rule, RulePriority severity) {
ActiveRuleDto activeRule = findRule(activeRules, rule).get();
assertThat(activeRule.getInheritance()).isNull();
assertThat(activeRule.getSeverityString()).isEqualTo(severity.name());
assertThat(activeRule.getCreatedAt()).isEqualTo(PAST);
assertThat(activeRule.getUpdatedAt()).isEqualTo(PAST);
}
private void assertThatRuleIsDeactivated(QProfileDto profile, RuleDto rule) {
Collection<ActiveRuleDto> activeRules = db.getDbClient().activeRuleDao().selectByRulesAndRuleProfileUuids(
db.getSession(), singletonList(rule.getUuid()), singletonList(profile.getRulesProfileUuid()));
assertThat(activeRules).isEmpty();
}
private static void assertThatRuleIsDeactivated(List<ActiveRuleDto> activeRules, RuleDto rule) {
assertThat(findRule(activeRules, rule)).isEmpty();
}
private void assertThatProfileIsMarkedAsUpdated(RulesProfileDto dto) {
RulesProfileDto reloaded = db.getDbClient().qualityProfileDao().selectBuiltInRuleProfiles(db.getSession())
.stream()
.filter(p -> p.getUuid().equals(dto.getUuid()))
.findFirst()
.get();
assertThat(reloaded.getRulesUpdatedAt()).isNotEmpty();
}
private void assertThatProfileIsNotMarkedAsUpdated(RulesProfileDto dto) {
RulesProfileDto reloaded = db.getDbClient().qualityProfileDao().selectBuiltInRuleProfiles(db.getSession())
.stream()
.filter(p -> p.getUuid().equals(dto.getUuid()))
.findFirst()
.get();
assertThat(reloaded.getRulesUpdatedAt()).isNull();
}
private static Optional<ActiveRuleDto> findRule(List<ActiveRuleDto> activeRules, RuleDto rule) {
return activeRules.stream()
.filter(ar -> ar.getRuleKey().equals(rule.getKey()))
.findFirst();
}
private ActiveRuleDto activateRuleInDb(RulesProfileDto profile, RuleDto rule, RulePriority severity) {
return activateRuleInDb(profile, rule, severity, null);
}
private ActiveRuleDto activateRuleInDb(RulesProfileDto ruleProfile, RuleDto rule, RulePriority severity, @Nullable ActiveRuleInheritance inheritance) {
ActiveRuleDto dto = new ActiveRuleDto()
.setKey(ActiveRuleKey.of(ruleProfile, RuleKey.of(rule.getRepositoryKey(), rule.getRuleKey())))
.setProfileUuid(ruleProfile.getUuid())
.setSeverity(severity.name())
.setRuleUuid(rule.getUuid())
.setInheritance(inheritance != null ? inheritance.name() : null)
.setCreatedAt(PAST)
.setUpdatedAt(PAST);
db.getDbClient().activeRuleDao().insert(db.getSession(), dto);
db.commit();
return dto;
}
private void activateRuleParamInDb(ActiveRuleDto activeRuleDto, RuleParamDto ruleParamDto, String value) {
ActiveRuleParamDto dto = new ActiveRuleParamDto()
.setActiveRuleUuid(activeRuleDto.getUuid())
.setRulesParameterUuid(ruleParamDto.getUuid())
.setKey(ruleParamDto.getName())
.setValue(value);
db.getDbClient().activeRuleDao().insertParam(db.getSession(), activeRuleDto, dto);
db.commit();
}
}
| 29,974 | 52.718638 | 170 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/builtin/RuleActivatorIT.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.qualityprofile.builtin;
import com.google.common.collect.ImmutableMap;
import java.util.List;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RulePriority;
import org.sonar.api.utils.System2;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.ActiveRuleKey;
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.RulesProfileDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
import org.sonar.server.qualityprofile.ActiveRuleChange;
import org.sonar.server.qualityprofile.ActiveRuleInheritance;
import org.sonar.server.qualityprofile.RuleActivation;
import org.sonar.server.qualityprofile.builtin.DescendantProfilesSupplier.Result;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.util.IntegerTypeValidation;
import org.sonar.server.util.StringTypeValidation;
import org.sonar.server.util.TypeValidations;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.mock;
import static org.sonar.server.qualityprofile.ActiveRuleInheritance.INHERITED;
import static org.sonar.server.qualityprofile.ActiveRuleInheritance.OVERRIDES;
/**
* Class org.sonar.server.qualityprofile.builtin.RuleActivator is mostly covered in
* org.sonar.server.qualityprofile.builtin.BuiltInQProfileUpdateImplTest
*/
public class RuleActivatorIT {
@Rule
public final DbTester db = DbTester.create();
@Rule
public final UserSessionRule userSession = UserSessionRule.standalone();
private static final long NOW = 1_000;
private static final long PAST = NOW - 100;
private final System2 system2 = new TestSystem2().setNow(NOW);
private final TypeValidations typeValidations = new TypeValidations(asList(new StringTypeValidation(), new IntegerTypeValidation()));
private final QualityProfileChangeEventService qualityProfileChangeEventService = mock(QualityProfileChangeEventService.class);
private final RuleActivator underTest = new RuleActivator(system2, db.getDbClient(), typeValidations, userSession);
@Test
public void reset_overridden_active_rule() {
RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo").setSeverity(Severity.BLOCKER));
RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue("10"));
QProfileDto parentProfile = db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()).setIsBuiltIn(true));
ActiveRuleDto parentActiveRuleDto = activateRuleInDb(RulesProfileDto.from(parentProfile), rule,
RulePriority.valueOf(Severity.BLOCKER), null);
ActiveRuleParamDto parentActiveRuleParam = activateRuleParamInDb(parentActiveRuleDto, ruleParam, "10");
QProfileDto childProfile = createChildProfile(parentProfile);
ActiveRuleDto childActiveRuleDto = activateRuleInDb(RulesProfileDto.from(childProfile), rule,
RulePriority.valueOf(Severity.MINOR), OVERRIDES);
ActiveRuleParamDto childActiveRuleParam = activateRuleParamInDb(childActiveRuleDto, ruleParam, "15");
DbSession session = db.getSession();
RuleActivation resetRequest = RuleActivation.createReset(rule.getUuid());
RuleActivationContext context = new RuleActivationContext.Builder()
.setProfiles(asList(parentProfile, childProfile))
.setBaseProfile(RulesProfileDto.from(childProfile))
.setDate(NOW)
.setDescendantProfilesSupplier((profiles, ruleUuids) -> new Result(emptyList(), emptyList(), emptyList()))
.setRules(singletonList(rule))
.setRuleParams(singletonList(ruleParam))
.setActiveRules(asList(parentActiveRuleDto, childActiveRuleDto))
.setActiveRuleParams(asList(parentActiveRuleParam, childActiveRuleParam))
.build();
List<ActiveRuleChange> result = underTest.activate(session, resetRequest, context);
assertThat(result).hasSize(1);
assertThat(result.get(0).getParameters()).containsEntry("min", "10");
assertThat(result.get(0).getSeverity()).isEqualTo(Severity.BLOCKER);
assertThat(result.get(0).getInheritance()).isEqualTo(ActiveRuleInheritance.INHERITED);
}
@Test
public void request_new_severity_and_param_for_child_rule() {
RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo").setSeverity(Severity.BLOCKER));
RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue("10"));
QProfileDto parentProfile = db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()).setIsBuiltIn(true));
ActiveRuleDto parentActiveRuleDto = activateRuleInDb(RulesProfileDto.from(parentProfile), rule,
RulePriority.valueOf(Severity.BLOCKER), null);
ActiveRuleParamDto parentActiveRuleParam = activateRuleParamInDb(parentActiveRuleDto, ruleParam, "10");
QProfileDto childProfile = createChildProfile(parentProfile);
ActiveRuleDto childActiveRuleDto = activateRuleInDb(RulesProfileDto.from(childProfile), rule,
RulePriority.valueOf(Severity.BLOCKER), INHERITED);
ActiveRuleParamDto childActiveRuleParam = activateRuleParamInDb(childActiveRuleDto, ruleParam, "10");
DbSession session = db.getSession();
RuleActivation resetRequest = RuleActivation.create(rule.getUuid(), Severity.MINOR, ImmutableMap.of("min", "15"));
RuleActivationContext context = new RuleActivationContext.Builder()
.setProfiles(asList(parentProfile, childProfile))
.setBaseProfile(RulesProfileDto.from(childProfile))
.setDate(NOW)
.setDescendantProfilesSupplier((profiles, ruleUuids) -> new Result(emptyList(), emptyList(), emptyList()))
.setRules(singletonList(rule))
.setRuleParams(singletonList(ruleParam))
.setActiveRules(asList(parentActiveRuleDto, childActiveRuleDto))
.setActiveRuleParams(asList(parentActiveRuleParam, childActiveRuleParam))
.build();
List<ActiveRuleChange> result = underTest.activate(session, resetRequest, context);
assertThat(result).hasSize(1);
assertThat(result.get(0).getParameters()).containsEntry("min", "15");
assertThat(result.get(0).getSeverity()).isEqualTo(Severity.MINOR);
assertThat(result.get(0).getInheritance()).isEqualTo(OVERRIDES);
}
@Test
public void set_severity_and_param_for_child_rule_when_activating() {
RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo").setSeverity(Severity.BLOCKER));
RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue("10"));
QProfileDto parentProfile = db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()).setIsBuiltIn(true));
QProfileDto childProfile = createChildProfile(parentProfile);
DbSession session = db.getSession();
RuleActivation resetRequest = RuleActivation.create(rule.getUuid());
RuleActivationContext context = new RuleActivationContext.Builder()
.setProfiles(asList(parentProfile, childProfile))
.setBaseProfile(RulesProfileDto.from(childProfile))
.setDate(NOW)
.setDescendantProfilesSupplier((profiles, ruleUuids) -> new Result(emptyList(), emptyList(), emptyList()))
.setRules(singletonList(rule))
.setRuleParams(singletonList(ruleParam))
.setActiveRules(emptyList())
.setActiveRuleParams(emptyList())
.build();
List<ActiveRuleChange> result = underTest.activate(session, resetRequest, context);
assertThat(result).hasSize(1);
assertThat(result.get(0).getParameters()).containsEntry("min", "10");
assertThat(result.get(0).getSeverity()).isEqualTo(Severity.BLOCKER);
assertThat(result.get(0).getInheritance()).isNull();
}
@Test
public void fail_if_rule_language_doesnt_match_qp() {
RuleDto rule = db.rules().insert(r -> r.setLanguage("xoo")
.setRepositoryKey("repo")
.setRuleKey("rule")
.setSeverity(Severity.BLOCKER));
QProfileDto qp = db.qualityProfiles().insert(p -> p.setLanguage("xoo2").setKee("qp").setIsBuiltIn(true));
DbSession session = db.getSession();
RuleActivation resetRequest = RuleActivation.create(rule.getUuid());
RuleActivationContext context = new RuleActivationContext.Builder()
.setProfiles(singletonList(qp))
.setBaseProfile(RulesProfileDto.from(qp))
.setDate(NOW)
.setDescendantProfilesSupplier((profiles, ruleUuids) -> new Result(emptyList(), emptyList(), emptyList()))
.setRules(singletonList(rule))
.setRuleParams(emptyList())
.setActiveRules(emptyList())
.setActiveRuleParams(emptyList())
.build();
assertThrows("xoo rule repo:rule cannot be activated on xoo2 profile qp", BadRequestException.class,
() -> underTest.activate(session, resetRequest, context));
}
private ActiveRuleDto activateRuleInDb(RulesProfileDto ruleProfile, RuleDto rule, RulePriority severity, @Nullable ActiveRuleInheritance inheritance) {
ActiveRuleDto dto = new ActiveRuleDto()
.setKey(ActiveRuleKey.of(ruleProfile, RuleKey.of(rule.getRepositoryKey(), rule.getRuleKey())))
.setProfileUuid(ruleProfile.getUuid())
.setSeverity(severity.name())
.setRuleUuid(rule.getUuid())
.setInheritance(inheritance != null ? inheritance.name() : null)
.setCreatedAt(PAST)
.setUpdatedAt(PAST);
db.getDbClient().activeRuleDao().insert(db.getSession(), dto);
db.commit();
return dto;
}
private ActiveRuleParamDto activateRuleParamInDb(ActiveRuleDto activeRuleDto, RuleParamDto ruleParamDto, String value) {
ActiveRuleParamDto dto = new ActiveRuleParamDto()
.setActiveRuleUuid(activeRuleDto.getUuid())
.setRulesParameterUuid(ruleParamDto.getUuid())
.setKey(ruleParamDto.getName())
.setValue(value);
db.getDbClient().activeRuleDao().insertParam(db.getSession(), activeRuleDto, dto);
db.commit();
return dto;
}
private QProfileDto createChildProfile(QProfileDto parent) {
return db.qualityProfiles().insert(p -> p
.setLanguage(parent.getLanguage())
.setParentKee(parent.getKee())
.setName("Child of " + parent.getName()))
.setIsBuiltIn(false);
}
}
| 11,530 | 46.64876 | 153 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ActivateRuleActionIT.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.qualityprofile.ws;
import java.net.HttpURLConnection;
import java.util.Collection;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.MockitoAnnotations;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.Severity;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.qualityprofile.QProfileRules;
import org.sonar.server.qualityprofile.RuleActivation;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
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.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.UUID_SIZE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_KEY;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_RULE;
public class ActivateRuleActionIT {
@Rule
public DbTester db = DbTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final ArgumentCaptor<Collection<RuleActivation>> ruleActivationCaptor = ArgumentCaptor.forClass(Collection.class);
private final DbClient dbClient = db.getDbClient();
private final QProfileRules qProfileRules = mock(QProfileRules.class);
private final QProfileWsSupport wsSupport = new QProfileWsSupport(dbClient, userSession);
private final WsActionTester ws = new WsActionTester(new ActivateRuleAction(dbClient, qProfileRules, userSession, wsSupport));
@Before
public void before() {
MockitoAnnotations.initMocks(this);
}
@Test
public void define_activate_rule_action() {
WebService.Action definition = ws.getDef();
assertThat(definition).isNotNull();
assertThat(definition.isPost()).isTrue();
assertThat(definition.params()).extracting(WebService.Param::key).containsExactlyInAnyOrder("severity", "key", "reset", "rule", "params");
}
@Test
public void fail_if_not_logged_in() {
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_RULE, RuleTesting.newRule().getKey().toString())
.setParam(PARAM_KEY, randomAlphanumeric(UUID_SIZE));
assertThatThrownBy(() -> request.execute())
.isInstanceOf(UnauthorizedException.class);
}
@Test
public void fail_if_not_global_quality_profile_administrator() {
userSession.logIn(db.users().insertUser());
QProfileDto qualityProfile = db.qualityProfiles().insert();
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_RULE, RuleTesting.newRule().getKey().toString())
.setParam(PARAM_KEY, qualityProfile.getKee());
assertThatThrownBy(() -> request.execute())
.isInstanceOf(ForbiddenException.class);
}
@Test
public void fail_activate_if_built_in_profile() {
userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
QProfileDto qualityProfile = db.qualityProfiles().insert(profile -> profile.setIsBuiltIn(true).setName("Xoo profile").setLanguage("xoo"));
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_RULE, RuleTesting.newRule().getKey().toString())
.setParam(PARAM_KEY, qualityProfile.getKee());
assertThatThrownBy(() -> request.execute())
.isInstanceOf(BadRequestException.class)
.hasMessage("Operation forbidden for built-in Quality Profile 'Xoo profile' with language 'xoo'");
}
@Test
public void fail_activate_external_rule() {
userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
QProfileDto qualityProfile = db.qualityProfiles().insert();
RuleDto rule = db.rules().insert(r -> r.setIsExternal(true));
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_RULE, rule.getKey().toString())
.setParam(PARAM_KEY, qualityProfile.getKee());
assertThatThrownBy(() -> request.execute())
.isInstanceOf(BadRequestException.class)
.hasMessage(String.format("Operation forbidden for rule '%s' imported from an external rule engine.", rule.getKey()));
}
@Test
public void activate_rule() {
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
QProfileDto qualityProfile = db.qualityProfiles().insert();
RuleDto rule = db.rules().insert(RuleTesting.randomRuleKey());
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_RULE, rule.getKey().toString())
.setParam(PARAM_KEY, qualityProfile.getKee())
.setParam("severity", "BLOCKER")
.setParam("params", "key1=v1;key2=v2")
.setParam("reset", "false");
TestResponse response = request.execute();
assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
verify(qProfileRules).activateAndCommit(any(DbSession.class), any(QProfileDto.class), ruleActivationCaptor.capture());
Collection<RuleActivation> activations = ruleActivationCaptor.getValue();
assertThat(activations).hasSize(1);
RuleActivation activation = activations.iterator().next();
assertThat(activation.getRuleUuid()).isEqualTo(rule.getUuid());
assertThat(activation.getSeverity()).isEqualTo(Severity.BLOCKER);
assertThat(activation.isReset()).isFalse();
}
@Test
public void as_qprofile_editor() {
UserDto user = db.users().insertUser();
QProfileDto qualityProfile = db.qualityProfiles().insert();
db.qualityProfiles().addUserPermission(qualityProfile, user);
userSession.logIn(user);
RuleKey ruleKey = RuleTesting.randomRuleKey();
db.rules().insert(ruleKey);
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_RULE, ruleKey.toString())
.setParam(PARAM_KEY, qualityProfile.getKee())
.setParam("severity", "BLOCKER")
.setParam("params", "key1=v1;key2=v2")
.setParam("reset", "false")
.execute();
verify(qProfileRules).activateAndCommit(any(DbSession.class), any(QProfileDto.class), anyCollection());
}
}
| 7,804 | 39.863874 | 142 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ActivateRulesActionIT.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.qualityprofile.ws;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.qualityprofile.QProfileRules;
import org.sonar.server.rule.ws.RuleQueryFactory;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
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.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.UUID_SIZE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_TARGET_KEY;
public class ActivateRulesActionIT {
@Rule
public DbTester db = DbTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private DbClient dbClient = db.getDbClient();
private final QProfileWsSupport wsSupport = new QProfileWsSupport(dbClient, userSession);
private RuleQueryFactory ruleQueryFactory = mock(RuleQueryFactory.class, Mockito.RETURNS_MOCKS);
private QProfileRules qProfileRules = mock(QProfileRules.class, Mockito.RETURNS_DEEP_STUBS);
private WsActionTester ws = new WsActionTester(new ActivateRulesAction(ruleQueryFactory, userSession, qProfileRules, wsSupport, dbClient));
@Test
public void define_bulk_activate_rule_action() {
WebService.Action definition = ws.getDef();
assertThat(definition).isNotNull();
assertThat(definition.isPost()).isTrue();
assertThat(definition.params()).extracting(WebService.Param::key).containsExactlyInAnyOrder(
"types",
"template_key",
"languages",
"is_template",
"inheritance",
"qprofile",
"compareToProfile",
"targetSeverity",
"tags",
"asc",
"q",
"active_severities",
"s",
"repositories",
"targetKey",
"statuses",
"rule_key",
"available_since",
"activation",
"severities",
"cwe",
"owaspTop10",
"owaspTop10-2021",
"sansTop25",
"sonarsourceSecurity");
}
@Test
public void as_global_qprofile_admin() {
userSession.logIn(db.users().insertUser()).addPermission(ADMINISTER_QUALITY_PROFILES);
QProfileDto qualityProfile = db.qualityProfiles().insert();
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TARGET_KEY, qualityProfile.getKee())
.execute();
verify(qProfileRules).bulkActivateAndCommit(any(), any(), any(), any());
}
@Test
public void as_qprofile_editor() {
UserDto user = db.users().insertUser();
GroupDto group = db.users().insertGroup();
QProfileDto qualityProfile = db.qualityProfiles().insert();
db.qualityProfiles().addGroupPermission(qualityProfile, group);
userSession.logIn(user).setGroups(group);
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TARGET_KEY, qualityProfile.getKee())
.execute();
verify(qProfileRules).bulkActivateAndCommit(any(), any(), any(), any());
}
@Test
public void fail_if_not_logged_in() {
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TARGET_KEY, randomAlphanumeric(UUID_SIZE));
assertThatThrownBy(() -> request.execute())
.isInstanceOf(UnauthorizedException.class);
}
@Test
public void fail_if_built_in_profile() {
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
QProfileDto qualityProfile = db.qualityProfiles().insert(p -> p.setIsBuiltIn(true));
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TARGET_KEY, qualityProfile.getKee());
assertThatThrownBy(() -> request.execute())
.isInstanceOf(BadRequestException.class);
}
@Test
public void fail_if_not_enough_permission() {
userSession.logIn(db.users().insertUser());
QProfileDto qualityProfile = db.qualityProfiles().insert();
assertThatThrownBy(() -> {
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TARGET_KEY, qualityProfile.getKee())
.execute();
})
.isInstanceOf(ForbiddenException.class);
}
}
| 5,659 | 33.938272 | 141 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/AddGroupActionIT.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.qualityprofile.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.WebService;
import org.sonar.core.util.UuidFactory;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.DbTester;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_GROUP;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE;
public class AddGroupActionIT {
private static final String XOO = "xoo";
private static final Languages LANGUAGES = LanguageTesting.newLanguages(XOO);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create();
private final QProfileWsSupport wsSupport = new QProfileWsSupport(db.getDbClient(), userSession);
private final UuidFactory uuidFactory = UuidFactoryFast.getInstance();
private final WsActionTester ws = new WsActionTester(new AddGroupAction(db.getDbClient(), uuidFactory, wsSupport, LANGUAGES));
@Test
public void test_definition() {
WebService.Action def = ws.getDef();
assertThat(def.key()).isEqualTo("add_group");
assertThat(def.isPost()).isTrue();
assertThat(def.isInternal()).isTrue();
assertThat(def.params()).extracting(WebService.Param::key).containsExactlyInAnyOrder("qualityProfile", "language", "group");
}
@Test
public void add_group() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group = db.users().insertGroup();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
TestResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, group.getName())
.execute();
assertThat(response.getStatus()).isEqualTo(204);
assertThat(db.getDbClient().qProfileEditGroupsDao().exists(db.getSession(), profile, group)).isTrue();
}
@Test
public void does_nothing_when_group_can_already_edit_profile() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group = db.users().insertGroup();
db.qualityProfiles().addGroupPermission(profile, group);
assertThat(db.getDbClient().qProfileEditGroupsDao().exists(db.getSession(), profile, group)).isTrue();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, group.getName())
.execute();
assertThat(db.getDbClient().qProfileEditGroupsDao().exists(db.getSession(), profile, group)).isTrue();
}
@Test
public void qp_administers_can_add_group() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group = db.users().insertGroup();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, group.getName())
.execute();
assertThat(db.getDbClient().qProfileEditGroupsDao().exists(db.getSession(), profile, group)).isTrue();
}
@Test
public void can_add_group_with_user_edit_permission() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group = db.users().insertGroup();
UserDto userAllowedToEditProfile = db.users().insertUser();
db.qualityProfiles().addUserPermission(profile, userAllowedToEditProfile);
userSession.logIn(userAllowedToEditProfile);
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, group.getName())
.execute();
assertThat(db.getDbClient().qProfileEditGroupsDao().exists(db.getSession(), profile, group)).isTrue();
}
@Test
public void can_add_group_with_group_edit_permission() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group = db.users().insertGroup();
UserDto userAllowedToEditProfile = db.users().insertUser();
db.qualityProfiles().addGroupPermission(profile, group);
userSession.logIn(userAllowedToEditProfile).setGroups(group);
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, group.getName())
.execute();
assertThat(db.getDbClient().qProfileEditGroupsDao().exists(db.getSession(), profile, group)).isTrue();
}
@Test
public void uses_global_permission() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group = db.users().insertGroup();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, group.getName())
.execute();
assertThat(db.getDbClient().qProfileEditGroupsDao().exists(db.getSession(), profile, group)).isTrue();
}
@Test
public void fail_when_group_does_not_exist() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, "unknown")
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage("No group with name 'unknown'");
}
@Test
public void fail_when_qprofile_does_not_exist() {
GroupDto group = db.users().insertGroup();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, "unknown")
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, group.getName())
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist");
}
@Test
public void fail_when_wrong_language() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage("unknown"));
UserDto user = db.users().insertUser();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, user.getLogin())
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage(format("Quality Profile for language 'xoo' and name '%s' does not exist", profile.getName()));
}
@Test
public void fail_when_qp_is_built_in() {
UserDto user = db.users().insertUser();
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO).setIsBuiltIn(true));
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, user.getLogin())
.execute();
})
.isInstanceOf(BadRequestException.class)
.hasMessage(String.format("Operation forbidden for built-in Quality Profile '%s' with language 'xoo'", profile.getName()));
}
@Test
public void fail_when_not_enough_permission() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user = db.users().insertUser();
userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, user.getLogin())
.execute();
})
.isInstanceOf(ForbiddenException.class);
}
}
| 9,889 | 38.40239 | 129 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/AddProjectActionIT.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.qualityprofile.ws;
import java.net.HttpURLConnection;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.component.TestComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
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.verify;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
public class AddProjectActionIT {
private static final String LANGUAGE_1 = "xoo";
private static final String LANGUAGE_2 = "foo";
@Rule
public DbTester db = DbTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final DbClient dbClient = db.getDbClient();
private final Languages languages = LanguageTesting.newLanguages(LANGUAGE_1, LANGUAGE_2);
private final QProfileWsSupport wsSupport = new QProfileWsSupport(dbClient, userSession);
private QualityProfileChangeEventService qualityProfileChangeEventService = mock(QualityProfileChangeEventService.class);
private final AddProjectAction underTest = new AddProjectAction(dbClient, userSession, languages, TestComponentFinder.from(db), wsSupport, qualityProfileChangeEventService);
private final WsActionTester tester = new WsActionTester(underTest);
@Test
public void definition() {
WebService.Action definition = tester.getDef();
assertThat(definition.since()).isEqualTo("5.2");
assertThat(definition.isPost()).isTrue();
// parameters
assertThat(definition.params()).extracting(WebService.Param::key)
.containsExactlyInAnyOrder("qualityProfile", "project", "language");
WebService.Param project = definition.param("project");
assertThat(project.isRequired()).isTrue();
WebService.Param languageParam = definition.param("language");
assertThat(languageParam.possibleValues()).containsOnly(LANGUAGE_1, LANGUAGE_2);
assertThat(languageParam.exampleValue()).isNull();
}
@Test
public void add_project_on_profile() {
logInAsProfileAdmin();
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
QProfileDto profile = db.qualityProfiles().insert(qp -> qp.setLanguage("xoo"));
TestResponse response = call(project, profile);
assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
assertProjectIsAssociatedToProfile(project, profile);
verify(qualityProfileChangeEventService).publishRuleActivationToSonarLintClients(project, profile, null);
}
@Test
public void as_qprofile_editor_and_global_admin() {
UserDto user = db.users().insertUser();
QProfileDto qualityProfile = db.qualityProfiles().insert(qp -> qp.setLanguage(LANGUAGE_1));
db.qualityProfiles().addUserPermission(qualityProfile, user);
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
userSession.logIn(user).addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
call(project, qualityProfile);
assertProjectIsAssociatedToProfile(project, qualityProfile);
verify(qualityProfileChangeEventService).publishRuleActivationToSonarLintClients(project, qualityProfile, null);
}
@Test
public void change_association() {
logInAsProfileAdmin();
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
// two profiles on same language
QProfileDto profile1 = db.qualityProfiles().insert(p -> p.setLanguage(LANGUAGE_1));
QProfileDto profile2 = db.qualityProfiles().insert(p -> p.setLanguage(LANGUAGE_1));
db.qualityProfiles().associateWithProject(project, profile1);
call(project, profile2);
assertProjectIsNotAssociatedToProfile(project, profile1);
assertProjectIsAssociatedToProfile(project, profile2);
verify(qualityProfileChangeEventService).publishRuleActivationToSonarLintClients(project, profile2, profile1);
}
@Test
public void changing_association_does_not_change_other_language_associations() {
logInAsProfileAdmin();
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
QProfileDto profile1Language1 = db.qualityProfiles().insert(p -> p.setLanguage(LANGUAGE_1));
QProfileDto profile2Language2 = db.qualityProfiles().insert(p -> p.setLanguage(LANGUAGE_2));
QProfileDto profile3Language1 = db.qualityProfiles().insert(p -> p.setLanguage(LANGUAGE_1));
db.qualityProfiles().associateWithProject(project, profile1Language1, profile2Language2);
call(project, profile3Language1);
assertProjectIsAssociatedToProfile(project, profile3Language1);
assertProjectIsAssociatedToProfile(project, profile2Language2);
verify(qualityProfileChangeEventService).publishRuleActivationToSonarLintClients(project, profile3Language1, profile1Language1);
}
@Test
public void project_administrator_can_change_profile() {
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
QProfileDto profile = db.qualityProfiles().insert(qp -> qp.setLanguage("xoo"));
userSession.logIn(db.users().insertUser()).addProjectPermission(UserRole.ADMIN, project);
call(project, profile);
assertProjectIsAssociatedToProfile(project, profile);
verify(qualityProfileChangeEventService).publishRuleActivationToSonarLintClients(project, profile, null);
}
@Test
public void throw_ForbiddenException_if_not_project_nor_global_administrator() {
userSession.logIn(db.users().insertUser());
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
QProfileDto profile = db.qualityProfiles().insert(qp -> qp.setLanguage("xoo"));
assertThatThrownBy(() -> call(project, profile))
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void throw_UnauthorizedException_if_not_logged_in() {
userSession.anonymous();
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
QProfileDto profile = db.qualityProfiles().insert();
assertThatThrownBy(() -> call(project, profile))
.isInstanceOf(UnauthorizedException.class)
.hasMessage("Authentication is required");
}
@Test
public void throw_NotFoundException_if_project_does_not_exist() {
logInAsProfileAdmin();
QProfileDto profile = db.qualityProfiles().insert();
assertThatThrownBy(() -> {
tester.newRequest()
.setParam("project", "unknown")
.setParam("profileKey", profile.getKee())
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Project 'unknown' not found");
}
@Test
public void throw_NotFoundException_if_profile_does_not_exist() {
logInAsProfileAdmin();
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
assertThatThrownBy(() -> {
tester.newRequest()
.setParam("project", project.getKey())
.setParam("language", "xoo")
.setParam("qualityProfile", "unknown")
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist");
}
private void assertProjectIsAssociatedToProfile(ProjectDto project, QProfileDto profile) {
QProfileDto loaded = dbClient.qualityProfileDao().selectAssociatedToProjectAndLanguage(db.getSession(), project, profile.getLanguage());
assertThat(loaded.getKee()).isEqualTo(profile.getKee());
}
private void assertProjectIsNotAssociatedToProfile(ProjectDto project, QProfileDto profile) {
QProfileDto loaded = dbClient.qualityProfileDao().selectAssociatedToProjectAndLanguage(db.getSession(), project, profile.getLanguage());
assertThat(loaded == null || !loaded.getKee().equals(profile.getKee())).isTrue();
}
private void logInAsProfileAdmin() {
userSession.logIn(db.users().insertUser()).addPermission(ADMINISTER_QUALITY_PROFILES);
}
private TestResponse call(ProjectDto project, QProfileDto qualityProfile) {
TestRequest request = tester.newRequest()
.setParam("project", project.getKey())
.setParam("language", qualityProfile.getLanguage())
.setParam("qualityProfile", qualityProfile.getName());
return request.execute();
}
}
| 9,995 | 42.086207 | 175 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/AddUserActionIT.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.qualityprofile.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.WebService;
import org.sonar.core.util.UuidFactory;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.DbTester;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LOGIN;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE;
public class AddUserActionIT {
private static final String XOO = "xoo";
private static final Languages LANGUAGES = LanguageTesting.newLanguages(XOO);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create();
private final QProfileWsSupport wsSupport = new QProfileWsSupport(db.getDbClient(), userSession);
private final UuidFactory uuidFactory = UuidFactoryFast.getInstance();
private final WsActionTester ws = new WsActionTester(new AddUserAction(db.getDbClient(), uuidFactory, wsSupport, LANGUAGES));
@Test
public void test_definition() {
WebService.Action def = ws.getDef();
assertThat(def.key()).isEqualTo("add_user");
assertThat(def.isPost()).isTrue();
assertThat(def.isInternal()).isTrue();
assertThat(def.params()).extracting(WebService.Param::key).containsExactlyInAnyOrder("qualityProfile", "language", "login");
}
@Test
public void add_user() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user = db.users().insertUser();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
TestResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
assertThat(response.getStatus()).isEqualTo(204);
assertThat(db.getDbClient().qProfileEditUsersDao().exists(db.getSession(), profile, user)).isTrue();
}
@Test
public void does_nothing_when_user_can_already_edit_profile() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user = db.users().insertUser();
db.qualityProfiles().addUserPermission(profile, user);
assertThat(db.getDbClient().qProfileEditUsersDao().exists(db.getSession(), profile, user)).isTrue();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
assertThat(db.getDbClient().qProfileEditUsersDao().exists(db.getSession(), profile, user)).isTrue();
}
@Test
public void qp_administers_can_add_user() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user = db.users().insertUser();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
assertThat(db.getDbClient().qProfileEditUsersDao().exists(db.getSession(), profile, user)).isTrue();
}
@Test
public void qp_editors_can_add_user() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user = db.users().insertUser();
UserDto userAllowedToEditProfile = db.users().insertUser();
db.qualityProfiles().addUserPermission(profile, userAllowedToEditProfile);
userSession.logIn(userAllowedToEditProfile);
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
assertThat(db.getDbClient().qProfileEditUsersDao().exists(db.getSession(), profile, user)).isTrue();
}
@Test
public void fail_when_user_does_not_exist() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_LOGIN, "unknown")
.execute())
.isInstanceOf(NotFoundException.class)
.hasMessageContaining("User with login 'unknown' is not found");
}
@Test
public void fail_when_qprofile_does_not_exist() {
UserDto user = db.users().insertUser();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, "unknown")
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist");
}
@Test
public void fail_when_wrong_language() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage("unknown"));
UserDto user = db.users().insertUser();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage(format("Quality Profile for language 'xoo' and name '%s' does not exist", profile.getName()));
}
@Test
public void fail_when_qp_is_built_in() {
UserDto user = db.users().insertUser();
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO).setIsBuiltIn(true));
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
})
.isInstanceOf(BadRequestException.class)
.hasMessage(String.format("Operation forbidden for built-in Quality Profile '%s' with language 'xoo'", profile.getName()));
}
@Test
public void fail_when_not_enough_permission() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user = db.users().insertUser();
userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
})
.isInstanceOf(ForbiddenException.class);
}
}
| 8,568 | 38.855814 | 129 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/BackupActionIT.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.qualityprofile.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.qualityprofile.QProfileBackuper;
import org.sonar.server.qualityprofile.QProfileBackuperImpl;
import org.sonar.server.qualityprofile.QProfileParser;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class BackupActionIT {
private static final String A_LANGUAGE = "xoo";
@Rule
public DbTester db = DbTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final QProfileBackuper backuper = new QProfileBackuperImpl(db.getDbClient(), null, null, null, new QProfileParser());
private final QProfileWsSupport wsSupport = new QProfileWsSupport(db.getDbClient(), userSession);
private final Languages languages = LanguageTesting.newLanguages(A_LANGUAGE);
private final WsActionTester tester = new WsActionTester(new BackupAction(db.getDbClient(), backuper, wsSupport, languages));
@Test
public void returns_backup_of_profile_with_specified_key() {
QProfileDto profile = db.qualityProfiles().insert(qp -> qp.setLanguage("xoo"));
TestResponse response = tester.newRequest()
.setParam("language", profile.getLanguage())
.setParam("qualityProfile", profile.getName())
.execute();
assertThat(response.getMediaType()).isEqualTo("application/xml");
assertThat(response.getInput()).isXmlEqualTo(xmlForProfileWithoutRules(profile));
assertThat(response.getHeader("Content-Disposition")).isEqualTo("attachment; filename=" + profile.getKee() + ".xml");
}
@Test
public void returns_backup_of_profile_with_specified_name() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(A_LANGUAGE));
TestResponse response = tester.newRequest()
.setParam("language", profile.getLanguage())
.setParam("qualityProfile", profile.getName())
.execute();
assertThat(response.getInput()).isXmlEqualTo(xmlForProfileWithoutRules(profile));
}
@Test
public void throws_IAE_if_profile_reference_is_not_set() {
TestRequest request = tester.newRequest();
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void test_definition() {
WebService.Action definition = tester.getDef();
assertThat(definition.key()).isEqualTo("backup");
assertThat(definition.responseExampleAsString()).isNotEmpty();
assertThat(definition.isInternal()).isFalse();
assertThat(definition.isPost()).isFalse();
// parameters
assertThat(definition.params()).extracting(Param::key).containsExactlyInAnyOrder("qualityProfile", "language");
Param language = definition.param("language");
assertThat(language.deprecatedSince()).isNullOrEmpty();
}
private static String xmlForProfileWithoutRules(QProfileDto profile) {
return "<?xml version='1.0' encoding='UTF-8'?>" +
"<profile>" +
" <name>" + profile.getName() + "</name>" +
" <language>" + profile.getLanguage() + "</language>" +
" <rules/>" +
"</profile>";
}
}
| 4,434 | 38.598214 | 127 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ChangeParentActionIT.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.qualityprofile.ws;
import java.util.Collections;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.System2;
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.OrgActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.QualityProfileTesting;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsClient;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
import org.sonar.server.qualityprofile.QProfileTreeImpl;
import org.sonar.server.qualityprofile.builtin.RuleActivator;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import org.sonar.server.rule.index.RuleIndex;
import org.sonar.server.rule.index.RuleIndexer;
import org.sonar.server.rule.index.RuleQuery;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.util.TypeValidations;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters;
import static java.util.Arrays.asList;
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.mockito.Mockito.mock;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_PARENT_QUALITY_PROFILE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE;
public class ChangeParentActionIT {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public EsTester es = EsTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private DbClient dbClient;
private DbSession dbSession;
private RuleIndex ruleIndex;
private RuleIndexer ruleIndexer;
private ActiveRuleIndexer activeRuleIndexer;
private WsActionTester ws;
private Language language = LanguageTesting.newLanguage(randomAlphanumeric(20));
private String ruleRepository = randomAlphanumeric(5);
private QProfileTreeImpl qProfileTree;
@Before
public void setUp() {
dbClient = db.getDbClient();
dbSession = db.getSession();
EsClient esClient = es.client();
ruleIndex = new RuleIndex(esClient, System2.INSTANCE);
ruleIndexer = new RuleIndexer(esClient, dbClient);
activeRuleIndexer = new ActiveRuleIndexer(dbClient, esClient);
TypeValidations typeValidations = new TypeValidations(Collections.emptyList());
RuleActivator ruleActivator = new RuleActivator(System2.INSTANCE, dbClient, typeValidations, userSession);
qProfileTree = new QProfileTreeImpl(dbClient, ruleActivator, System2.INSTANCE, activeRuleIndexer, mock(QualityProfileChangeEventService.class));
ChangeParentAction underTest = new ChangeParentAction(
dbClient,
qProfileTree,
new Languages(),
new QProfileWsSupport(
dbClient,
userSession),
userSession);
ws = new WsActionTester(underTest);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
}
@Test
public void definition() {
WebService.Action definition = ws.getDef();
assertThat(definition.isPost()).isTrue();
assertThat(definition.params()).extracting(Param::key).containsExactlyInAnyOrder(
"qualityProfile", "language", "parentQualityProfile");
}
@Test
public void change_parent_with_no_parent_before() {
QProfileDto parent1 = createProfile();
QProfileDto child = createProfile();
RuleDto rule1 = createRule();
createActiveRule(rule1, parent1);
ruleIndexer.commitAndIndex(dbSession, rule1.getUuid());
activeRuleIndexer.indexAll();
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, child.getKee())).isEmpty();
// Set parent
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_LANGUAGE, child.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, child.getName())
.setParam(PARAM_PARENT_QUALITY_PROFILE, parent1.getName())
.execute();
// Check rule 1 enabled
List<OrgActiveRuleDto> activeRules1 = dbClient.activeRuleDao().selectByProfile(dbSession, child);
assertThat(activeRules1).hasSize(1);
assertThat(activeRules1.get(0).getKey().getRuleKey().rule()).isEqualTo(rule1.getRuleKey());
assertThat(ruleIndex.search(new RuleQuery().setActivation(true).setQProfile(child), new SearchOptions()).getUuids()).hasSize(1);
}
@Test
public void replace_existing_parent() {
QProfileDto parent1 = createProfile();
QProfileDto parent2 = createProfile();
QProfileDto child = createProfile();
RuleDto rule1 = createRule();
RuleDto rule2 = createRule();
createActiveRule(rule1, parent1);
createActiveRule(rule2, parent2);
ruleIndexer.commitAndIndex(dbSession, asList(rule1.getUuid(), rule2.getUuid()));
activeRuleIndexer.indexAll();
// Set parent 1
qProfileTree.setParentAndCommit(dbSession, child, parent1);
// Set parent 2 through WS
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_LANGUAGE, child.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, child.getName())
.setParam(PARAM_PARENT_QUALITY_PROFILE, parent2.getName())
.execute();
// Check rule 2 enabled
List<OrgActiveRuleDto> activeRules2 = dbClient.activeRuleDao().selectByProfile(dbSession, child);
assertThat(activeRules2).hasSize(1);
assertThat(activeRules2.get(0).getKey().getRuleKey().rule()).isEqualTo(rule2.getRuleKey());
assertThat(ruleIndex.search(new RuleQuery().setActivation(true).setQProfile(child), new SearchOptions()).getUuids()).hasSize(1);
}
@Test
public void remove_parent() {
QProfileDto parent = createProfile();
QProfileDto child = createProfile();
RuleDto rule1 = createRule();
createActiveRule(rule1, parent);
ruleIndexer.commitAndIndex(dbSession, rule1.getUuid());
activeRuleIndexer.indexAll();
// Set parent
qProfileTree.setParentAndCommit(dbSession, child, parent);
// Remove parent through WS
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_LANGUAGE, child.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, child.getName())
.execute();
// Check no rule enabled
assertThat(dbClient.activeRuleDao().selectByProfile(dbSession, child)).isEmpty();
assertThat(ruleIndex.search(new RuleQuery().setActivation(true).setQProfile(child), new SearchOptions()).getUuids()).isEmpty();
}
@Test
public void change_parent_with_names() {
QProfileDto parent1 = createProfile();
QProfileDto parent2 = createProfile();
QProfileDto child = createProfile();
RuleDto rule1 = createRule();
RuleDto rule2 = createRule();
createActiveRule(rule1, parent1);
createActiveRule(rule2, parent2);
ruleIndexer.commitAndIndex(dbSession, rule1.getUuid());
activeRuleIndexer.indexAll();
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, child.getKee())).isEmpty();
// 1. Set parent 1
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_LANGUAGE, child.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, child.getName())
.setParam(PARAM_PARENT_QUALITY_PROFILE, parent1.getName())
.execute();
// 1. check rule 1 enabled
List<OrgActiveRuleDto> activeRules1 = dbClient.activeRuleDao().selectByProfile(dbSession, child);
assertThat(activeRules1).hasSize(1);
assertThat(activeRules1.get(0).getKey().getRuleKey().rule()).isEqualTo(rule1.getRuleKey());
assertThat(ruleIndex.search(new RuleQuery().setActivation(true).setQProfile(child), new SearchOptions()).getUuids()).hasSize(1);
// 2. Set parent 2
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_LANGUAGE, child.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, child.getName())
.setParam(QualityProfileWsParameters.PARAM_PARENT_QUALITY_PROFILE, parent2.getName())
.execute();
// 2. check rule 2 enabled
List<OrgActiveRuleDto> activeRules2 = dbClient.activeRuleDao().selectByProfile(dbSession, child);
assertThat(activeRules2).hasSize(1);
assertThat(activeRules2.get(0).getKey().getRuleKey().rule()).isEqualTo(rule2.getRuleKey());
// 3. Remove parent
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_LANGUAGE, child.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, child.getName())
.setParam(QualityProfileWsParameters.PARAM_PARENT_QUALITY_PROFILE, "")
.execute();
// 3. check no rule enabled
List<OrgActiveRuleDto> activeRules = dbClient.activeRuleDao().selectByProfile(dbSession, child);
assertThat(activeRules).isEmpty();
assertThat(ruleIndex.search(new RuleQuery().setActivation(true).setQProfile(child), new SearchOptions()).getUuids()).isEmpty();
}
@Test
public void remove_parent_with_empty_key() {
QProfileDto parent = createProfile();
QProfileDto child = createProfile();
RuleDto rule1 = createRule();
createActiveRule(rule1, parent);
ruleIndexer.commitAndIndex(dbSession, rule1.getUuid());
activeRuleIndexer.indexAll();
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, child.getKee())).isEmpty();
// Set parent
qProfileTree.setParentAndCommit(dbSession, child, parent);
// Remove parent
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_LANGUAGE, child.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, child.getName())
.setParam(PARAM_PARENT_QUALITY_PROFILE, "")
.execute();
// Check no rule enabled
assertThat(dbClient.activeRuleDao().selectByProfile(dbSession, child)).isEmpty();
assertThat(ruleIndex.search(new RuleQuery().setActivation(true).setQProfile(child), new SearchOptions()).getUuids()).isEmpty();
}
@Test
public void as_qprofile_editor() {
QProfileDto parent1 = createProfile();
QProfileDto parent2 = createProfile();
QProfileDto child = createProfile();
RuleDto rule1 = createRule();
RuleDto rule2 = createRule();
createActiveRule(rule1, parent1);
createActiveRule(rule2, parent2);
ruleIndexer.commitAndIndex(dbSession, asList(rule1.getUuid(), rule2.getUuid()));
activeRuleIndexer.indexAll();
// Set parent 1
qProfileTree.setParentAndCommit(dbSession, child, parent1);
UserDto user = db.users().insertUser();
db.qualityProfiles().addUserPermission(child, user);
userSession.logIn(user);
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_LANGUAGE, child.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, child.getName())
.setParam(PARAM_PARENT_QUALITY_PROFILE, parent2.getName())
.execute();
List<OrgActiveRuleDto> activeRules2 = dbClient.activeRuleDao().selectByProfile(dbSession, child);
assertThat(activeRules2).hasSize(1);
assertThat(activeRules2.get(0).getKey().getRuleKey().rule()).isEqualTo(rule2.getRuleKey());
assertThat(ruleIndex.search(new RuleQuery().setActivation(true).setQProfile(child), new SearchOptions()).getUuids()).hasSize(1);
}
@Test
public void fail_if_built_in_profile() {
QProfileDto child = db.qualityProfiles().insert(p -> p
.setLanguage(language.getKey())
.setIsBuiltIn(true));
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, child.getKee())).isEmpty();
assertThat(ruleIndex.search(new RuleQuery().setActivation(true).setQProfile(child), new SearchOptions()).getUuids()).isEmpty();
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_LANGUAGE, child.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, child.getName())
.setParam(PARAM_PARENT_QUALITY_PROFILE, "palap");
assertThatThrownBy(request::execute)
.isInstanceOf(BadRequestException.class);
}
@Test
public void fail_if_missing_permission() {
userSession.logIn(db.users().insertUser());
QProfileDto child = createProfile();
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_LANGUAGE, child.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, child.getName());
assertThatThrownBy(request::execute)
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
private QProfileDto createProfile() {
QProfileDto profile = QualityProfileTesting.newQualityProfileDto()
.setLanguage(language.getKey());
dbClient.qualityProfileDao().insert(dbSession, profile);
dbSession.commit();
return profile;
}
private RuleDto createRule() {
RuleDto rule = RuleTesting.newRule(RuleKey.of(ruleRepository, randomAlphanumeric(5)))
.setLanguage(language.getKey())
.setSeverity(Severity.BLOCKER)
.setStatus(RuleStatus.READY);
dbClient.ruleDao().insert(dbSession, rule);
dbSession.commit();
return rule;
}
private ActiveRuleDto createActiveRule(RuleDto rule, QProfileDto profile) {
ActiveRuleDto activeRule = ActiveRuleDto.createFor(profile, rule)
.setSeverity(rule.getSeverityString());
dbClient.activeRuleDao().insert(dbSession, activeRule);
dbSession.commit();
return activeRule;
}
}
| 14,999 | 37.659794 | 148 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ChangelogActionIT.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.qualityprofile.ws;
import com.google.common.collect.ImmutableMap;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.resources.Languages;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.DateUtils;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.QProfileChangeDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.qualityprofile.ActiveRuleChange;
import org.sonar.server.qualityprofile.ActiveRuleInheritance;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.test.JsonAssert.assertJson;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_SINCE;
public class ChangelogActionIT {
private static final String DATE = "2011-04-25T01:15:42+0100";
private final TestSystem2 system2 = new TestSystem2().setNow(DateUtils.parseDateTime(DATE).getTime());
@Rule
public DbTester db = DbTester.create(system2);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final QProfileWsSupport wsSupport = new QProfileWsSupport(db.getDbClient(), userSession);
private final WsActionTester ws = new WsActionTester(new ChangelogAction(wsSupport, new Languages(), db.getDbClient()));
@Test
public void return_change_with_all_fields() {
QProfileDto profile = db.qualityProfiles().insert();
UserDto user = db.users().insertUser();
RuleDto rule = db.rules().insert(RuleKey.of("java", "S001"));
insertChange(profile, ActiveRuleChange.Type.ACTIVATED, user, ImmutableMap.of(
"ruleUuid", rule.getUuid(),
"severity", "MINOR",
"inheritance", ActiveRuleInheritance.INHERITED.name(),
"param_foo", "foo_value",
"param_bar", "bar_value"));
String response = ws.newRequest()
.setParam(PARAM_LANGUAGE, profile.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.execute()
.getInput();
assertJson(response).isSimilarTo("{\n" +
" \"total\": 1,\n" +
" \"p\": 1,\n" +
" \"ps\": 50,\n" +
" \"paging\": {\n" +
" \"pageIndex\": 1,\n" +
" \"pageSize\": 50,\n" +
" \"total\": 1\n" +
" }," +
" \"events\": [\n" +
" {\n" +
" \"date\": \"" + DATE + "\",\n" +
" \"authorLogin\": \"" + user.getLogin() + "\",\n" +
" \"authorName\": \"" + user.getName() + "\",\n" +
" \"action\": \"ACTIVATED\",\n" +
" \"ruleKey\": \"" + rule.getKey() + "\",\n" +
" \"ruleName\": \"" + rule.getName() + "\",\n" +
" \"params\": {\n" +
" \"severity\": \"MINOR\",\n" +
" \"bar\": \"bar_value\",\n" +
" \"foo\": \"foo_value\"\n" +
" }\n" +
" }\n" +
" ]\n" +
"}");
}
@Test
public void find_changelog_by_profile_key() {
QProfileDto profile = db.qualityProfiles().insert();
RuleDto rule = db.rules().insert();
UserDto user = db.users().insertUser();
insertChange(profile, ActiveRuleChange.Type.ACTIVATED, user,
ImmutableMap.of(
"ruleUuid", rule.getUuid(),
"severity", "MINOR"));
String response = ws.newRequest()
.setParam(PARAM_LANGUAGE, profile.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.execute()
.getInput();
assertJson(response).isSimilarTo("{\n" +
" \"events\": [\n" +
" {\n" +
" \"date\": \"" + DATE + "\",\n" +
" \"authorLogin\": \"" + user.getLogin() + "\",\n" +
" \"action\": \"ACTIVATED\",\n" +
" \"ruleKey\": \"" + rule.getKey() + "\",\n" +
" \"ruleName\": \"" + rule.getName() + "\",\n" +
" \"params\": {\n" +
" \"severity\": \"MINOR\"\n" +
" }\n" +
" }\n" +
" ]\n" +
"}");
}
@Test
public void find_changelog_by_language_and_name() {
QProfileDto qualityProfile = db.qualityProfiles().insert();
RuleDto rule = db.rules().insert();
UserDto user = db.users().insertUser();
insertChange(qualityProfile, ActiveRuleChange.Type.ACTIVATED, user,
ImmutableMap.of(
"ruleUuid", rule.getUuid(),
"severity", "MINOR"));
String response = ws.newRequest()
.setParam(PARAM_LANGUAGE, qualityProfile.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, qualityProfile.getName())
.execute()
.getInput();
assertJson(response).isSimilarTo("{\n" +
" \"events\": [\n" +
" {\n" +
" \"date\": \"" + DATE + "\",\n" +
" \"authorLogin\": \"" + user.getLogin() + "\",\n" +
" \"action\": \"ACTIVATED\",\n" +
" \"ruleKey\": \"" + rule.getKey() + "\",\n" +
" \"ruleName\": \"" + rule.getName() + "\",\n" +
" \"params\": {\n" +
" \"severity\": \"MINOR\"\n" +
" }\n" +
" }\n" +
" ]\n" +
"}");
}
@Test
public void changelog_empty() {
QProfileDto qualityProfile = db.qualityProfiles().insert();
String response = ws.newRequest()
.setParam(PARAM_LANGUAGE, qualityProfile.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, qualityProfile.getName())
.execute()
.getInput();
assertJson(response).isSimilarTo("{\"total\":0,\"p\":1,\"ps\":50,\"paging\":{\"pageIndex\":1,\"pageSize\":50,\"total\":0},\"events\":[]}");
}
@Test
public void changelog_filter_by_since() {
QProfileDto qualityProfile = db.qualityProfiles().insert();
system2.setNow(DateUtils.parseDateTime("2011-04-25T01:15:42+0100").getTime());
RuleDto rule = db.rules().insert();
UserDto user = db.users().insertUser();
insertChange(qualityProfile, ActiveRuleChange.Type.ACTIVATED, user,
ImmutableMap.of(
"ruleUuid", rule.getUuid(),
"severity", "MINOR"));
assertJson(ws.newRequest()
.setParam(PARAM_LANGUAGE, qualityProfile.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, qualityProfile.getName())
.setParam(PARAM_SINCE, "2011-04-25T01:15:42+0100")
.execute()
.getInput()).isSimilarTo("{\n" +
" \"events\": [\n" +
" {\n" +
" \"date\": \"2011-04-25T01:15:42+0100\",\n" +
" \"authorLogin\": \"" + user.getLogin() + "\",\n" +
" \"action\": \"ACTIVATED\",\n" +
" \"ruleKey\": \"" + rule.getKey() + "\",\n" +
" \"ruleName\": \"" + rule.getName() + "\",\n" +
" }\n" +
" ]\n" +
"}");
assertJson(ws.newRequest()
.setParam(PARAM_LANGUAGE, qualityProfile.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, qualityProfile.getName())
.setParam(PARAM_SINCE, "2011-04-25T01:15:43+0100")
.execute()
.getInput()).isSimilarTo("{\n" +
" \"events\": []\n" +
"}");
}
@Test
public void sort_changelog_events_in_reverse_chronological_order() {
QProfileDto profile = db.qualityProfiles().insert();
system2.setNow(DateUtils.parseDateTime("2011-04-25T01:15:42+0100").getTime());
RuleDto rule1 = db.rules().insert();
insertChange(profile, ActiveRuleChange.Type.ACTIVATED, null,
ImmutableMap.of(
"ruleUuid", rule1.getUuid(),
"severity", "MINOR"));
system2.setNow(DateUtils.parseDateTime("2011-04-25T01:15:43+0100").getTime());
UserDto user = db.users().insertUser();
RuleDto rule2 = db.rules().insert();
insertChange(profile, ActiveRuleChange.Type.DEACTIVATED, user,
ImmutableMap.of("ruleUuid", rule2.getUuid()));
String response = ws.newRequest()
.setParam(PARAM_LANGUAGE, profile.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.execute()
.getInput();
assertJson(response).isSimilarTo("{\n" +
"\"events\": [\n" +
" {\n" +
" \"date\": \"2011-04-25T02:15:43+0200\",\n" +
" \"action\": \"DEACTIVATED\",\n" +
" \"authorLogin\": \"" + user.getLogin() + "\",\n" +
" \"ruleKey\": \"" + rule2.getKey() + "\",\n" +
" \"ruleName\": \"" + rule2.getName() + "\",\n" +
" \"params\": {}\n" +
" },\n" +
" {\n" +
" \"date\": \"2011-04-25T02:15:42+0200\",\n" +
" \"action\": \"ACTIVATED\",\n" +
" \"ruleKey\": \"" + rule1.getKey() + "\",\n" +
" \"ruleName\": \"" + rule1.getName() + "\",\n" +
" \"params\": {\n" +
" \"severity\": \"MINOR\"\n" +
" }\n" +
" }\n" +
" ]" +
"}");
}
@Test
public void changelog_on_no_more_existing_rule() {
QProfileDto qualityProfile = db.qualityProfiles().insert();
UserDto user = db.users().insertUser();
insertChange(qualityProfile, ActiveRuleChange.Type.ACTIVATED, user,
ImmutableMap.of("ruleUuid", "123"));
String response = ws.newRequest()
.setParam(PARAM_LANGUAGE, qualityProfile.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, qualityProfile.getName())
.execute()
.getInput();
assertJson(response).isSimilarTo("{\n" +
" \"events\": [\n" +
" {\n" +
" \"date\": \"" + DATE + "\",\n" +
" \"action\": \"ACTIVATED\",\n" +
" \"params\": {}\n" +
" }\n" +
" ]\n" +
"}");
assertThat(response).doesNotContain("ruleKey", "ruleName");
}
@Test
public void changelog_on_no_more_existing_user() {
QProfileDto qualityProfile = db.qualityProfiles().insert();
RuleDto rule = db.rules().insert();
insertChange(c -> c.setRulesProfileUuid(qualityProfile.getRulesProfileUuid())
.setUserUuid("UNKNOWN")
.setChangeType(ActiveRuleChange.Type.ACTIVATED.name())
.setData(ImmutableMap.of("ruleUuid", rule.getUuid())));
String response = ws.newRequest()
.setParam(PARAM_LANGUAGE, qualityProfile.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, qualityProfile.getName())
.execute()
.getInput();
assertJson(response).isSimilarTo("{\n" +
" \"events\": [\n" +
" {\n" +
" \"date\": \"" + DATE + "\",\n" +
" \"ruleKey\": \"" + rule.getKey() + "\",\n" +
" \"ruleName\": \"" + rule.getName() + "\",\n" +
" \"action\": \"ACTIVATED\",\n" +
" \"params\": {}\n" +
" }\n" +
" ]\n" +
"}");
assertThat(response).doesNotContain("authorLogin", "authorName");
}
@Test
public void changelog_example() {
QProfileDto profile = db.qualityProfiles().insert();
String profileUuid = profile.getRulesProfileUuid();
system2.setNow(DateUtils.parseDateTime("2015-02-23T17:58:39+0100").getTime());
RuleDto rule1 = db.rules().insert(RuleKey.of("java", "S2438"), r -> r.setName("\"Threads\" should not be used where \"Runnables\" are expected"));
UserDto user1 = db.users().insertUser(u -> u.setLogin("anakin.skywalker").setName("Anakin Skywalker"));
insertChange(c -> c.setRulesProfileUuid(profileUuid)
.setUserUuid(user1.getUuid())
.setChangeType(ActiveRuleChange.Type.ACTIVATED.name())
.setData(ImmutableMap.of("severity", "CRITICAL", "ruleUuid", rule1.getUuid())));
system2.setNow(DateUtils.parseDateTime("2015-02-23T17:58:18+0100").getTime());
RuleDto rule2 = db.rules().insert(RuleKey.of("java", "S2162"), r -> r.setName("\"equals\" methods should be symmetric and work for subclasses"));
UserDto user2 = db.users().insertUser(u -> u.setLogin("padme.amidala").setName("Padme Amidala"));
insertChange(c -> c.setRulesProfileUuid(profileUuid)
.setUserUuid(user2.getUuid())
.setChangeType(ActiveRuleChange.Type.DEACTIVATED.name())
.setData(ImmutableMap.of("ruleUuid", rule2.getUuid())));
system2.setNow(DateUtils.parseDateTime("2014-09-12T15:20:46+0200").getTime());
RuleDto rule3 = db.rules().insert(RuleKey.of("java", "S00101"), r -> r.setName("Class names should comply with a naming convention"));
UserDto user3 = db.users().insertUser(u -> u.setLogin("obiwan.kenobi").setName("Obiwan Kenobi"));
insertChange(c -> c.setRulesProfileUuid(profileUuid)
.setUserUuid(user3.getUuid())
.setChangeType(ActiveRuleChange.Type.ACTIVATED.name())
.setData(ImmutableMap.of("severity", "MAJOR", "param_format", "^[A-Z][a-zA-Z0-9]*$", "ruleUuid", rule3.getUuid())));
ws.newRequest()
.setMethod("GET")
.setParam(PARAM_LANGUAGE, profile.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam("ps", "10")
.execute()
.assertJson(this.getClass(), "changelog_example.json");
}
@Test
public void definition() {
WebService.Action definition = ws.getDef();
assertThat(definition.isPost()).isFalse();
assertThat(definition.responseExampleAsString()).isNotEmpty();
assertThat(definition.params()).extracting(WebService.Param::key)
.containsExactlyInAnyOrder("qualityProfile", "language", "since", "to", "p", "ps");
WebService.Param profileName = definition.param("qualityProfile");
assertThat(profileName.deprecatedSince()).isNullOrEmpty();
WebService.Param language = definition.param("language");
assertThat(language.deprecatedSince()).isNullOrEmpty();
}
private QProfileChangeDto insertChange(QProfileDto profile, ActiveRuleChange.Type type, @Nullable UserDto user, @Nullable Map<String, Object> data) {
return insertChange(c -> c.setRulesProfileUuid(profile.getRulesProfileUuid())
.setUserUuid(user == null ? null : user.getUuid())
.setChangeType(type.name())
.setData(data));
}
@SafeVarargs
private final QProfileChangeDto insertChange(Consumer<QProfileChangeDto>... consumers) {
QProfileChangeDto dto = new QProfileChangeDto();
Arrays.stream(consumers).forEach(c -> c.accept(dto));
db.getDbClient().qProfileChangeDao().insert(db.getSession(), dto);
db.commit();
return dto;
}
}
| 15,327 | 38.403599 | 151 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/CompareActionIT.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.qualityprofile.ws;
import org.apache.commons.lang.StringUtils;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Languages;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import org.sonar.api.server.rule.RuleParamType;
import org.sonar.api.server.ws.WebService;
import org.sonar.core.util.Uuids;
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.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.QProfileDto;
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.language.LanguageTesting;
import org.sonar.server.qualityprofile.QProfileComparison;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsActionTester;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class CompareActionIT {
@Rule
public DbTester db = DbTester.create();
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private DbClient dbClient = db.getDbClient();
private DbSession session = db.getSession();
private WsActionTester ws = new WsActionTester(
new CompareAction(db.getDbClient(), new QProfileComparison(db.getDbClient()), new Languages(LanguageTesting.newLanguage("xoo", "Xoo"))));
@Test
public void compare_nominal() {
createRepository("blah", "xoo", "Blah");
RuleDto rule1 = createRule("xoo", "rule1");
RuleDto rule2 = createRule("xoo", "rule2");
RuleDto rule3 = createRule("xoo", "rule3");
RuleDto rule4 = createRuleWithParam("xoo", "rule4");
RuleDto rule5 = createRule("xoo", "rule5");
/*
* Profile 1:
* - rule 1 active (on both profiles) => "same"
* - rule 2 active (only in this profile) => "inLeft"
* - rule 4 active with different parameters => "modified"
* - rule 5 active with different severity => "modified"
*/
QProfileDto profile1 = createProfile("xoo", "Profile 1", "xoo-profile-1-01234");
createActiveRule(rule1, profile1);
createActiveRule(rule2, profile1);
createActiveRuleWithParam(rule4, profile1, "polop");
createActiveRuleWithSeverity(rule5, profile1, Severity.MINOR);
session.commit();
/*
* Profile 1:
* - rule 1 active (on both profiles) => "same"
* - rule 3 active (only in this profile) => "inRight"
* - rule 4 active with different parameters => "modified"
*/
QProfileDto profile2 = createProfile("xoo", "Profile 2", "xoo-profile-2-12345");
createActiveRule(rule1, profile2);
createActiveRule(rule3, profile2);
createActiveRuleWithParam(rule4, profile2, "palap");
createActiveRuleWithSeverity(rule5, profile2, Severity.MAJOR);
session.commit();
ws.newRequest()
.setParam("leftKey", profile1.getKee())
.setParam("rightKey", profile2.getKee())
.execute().assertJson(this.getClass(), "compare_nominal.json");
}
@Test
public void compare_param_on_left() {
RuleDto rule1 = createRuleWithParam("xoo", "rule1");
createRepository("blah", "xoo", "Blah");
QProfileDto profile1 = createProfile("xoo", "Profile 1", "xoo-profile-1-01234");
createActiveRuleWithParam(rule1, profile1, "polop");
QProfileDto profile2 = createProfile("xoo", "Profile 2", "xoo-profile-2-12345");
createActiveRule(rule1, profile2);
session.commit();
ws.newRequest()
.setParam("leftKey", profile1.getKee())
.setParam("rightKey", profile2.getKee())
.execute().assertJson(this.getClass(), "compare_param_on_left.json");
}
@Test
public void compare_param_on_right() {
RuleDto rule1 = createRuleWithParam("xoo", "rule1");
createRepository("blah", "xoo", "Blah");
QProfileDto profile1 = createProfile("xoo", "Profile 1", "xoo-profile-1-01234");
createActiveRule(rule1, profile1);
QProfileDto profile2 = createProfile("xoo", "Profile 2", "xoo-profile-2-12345");
createActiveRuleWithParam(rule1, profile2, "polop");
session.commit();
ws.newRequest()
.setParam("leftKey", profile1.getKee())
.setParam("rightKey", profile2.getKee())
.execute().assertJson(this.getClass(), "compare_param_on_right.json");
}
@Test
public void fail_on_missing_left_param() {
assertThatThrownBy(() -> {
ws.newRequest()
.setParam("rightKey", "polop")
.execute();
})
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void fail_on_missing_right_param() {
assertThatThrownBy(() -> {
ws.newRequest()
.setParam("leftKey", "polop")
.execute();
})
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void fail_on_left_profile_not_found() {
createProfile("xoo", "Right", "xoo-right-12345");
assertThatThrownBy(() -> {
ws.newRequest()
.setParam("leftKey", "polop")
.setParam("rightKey", "xoo-right-12345")
.execute();
})
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void fail_on_right_profile_not_found() {
createProfile("xoo", "Left", "xoo-left-12345");
assertThatThrownBy(() -> {
ws.newRequest()
.setParam("leftKey", "xoo-left-12345")
.setParam("rightKey", "polop")
.execute();
})
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void definition() {
WebService.Action definition = ws.getDef();
assertThat(definition).isNotNull();
assertThat(definition.isPost()).isFalse();
assertThat(definition.isInternal()).isTrue();
assertThat(definition.params()).hasSize(2).extracting("key").containsOnly(
"leftKey", "rightKey");
assertThat(definition.responseExampleAsString()).isNotEmpty();
}
private QProfileDto createProfile(String lang, String name, String key) {
return db.qualityProfiles().insert(p -> p.setKee(key).setName(name).setLanguage(lang));
}
private RuleDto createRule(String lang, String id) {
RuleDto rule = createFor(RuleKey.of("blah", id))
.setUuid(Uuids.createFast())
.setName(StringUtils.capitalize(id))
.setLanguage(lang)
.setSeverity(Severity.BLOCKER)
.setScope(Scope.MAIN)
.setStatus(RuleStatus.READY);
RuleDto ruleDto = rule;
dbClient.ruleDao().insert(session, ruleDto);
return ruleDto;
}
private static RuleDto createFor(RuleKey key) {
return new RuleDto()
.setRepositoryKey(key.repository())
.setRuleKey(key.rule());
}
private RuleDto createRuleWithParam(String lang, String id) {
RuleDto rule = createRule(lang, id);
RuleParamDto param = RuleParamDto.createFor(rule)
.setName("param_" + id)
.setType(RuleParamType.STRING.toString());
dbClient.ruleDao().insertRuleParam(session, rule, param);
return rule;
}
private ActiveRuleDto createActiveRule(RuleDto rule, QProfileDto profile) {
ActiveRuleDto activeRule = ActiveRuleDto.createFor(profile, rule)
.setSeverity(rule.getSeverityString());
dbClient.activeRuleDao().insert(session, activeRule);
return activeRule;
}
private ActiveRuleDto createActiveRuleWithParam(RuleDto rule, QProfileDto profile, String value) {
ActiveRuleDto activeRule = createActiveRule(rule, profile);
RuleParamDto paramDto = dbClient.ruleDao().selectRuleParamsByRuleKey(session, rule.getKey()).get(0);
ActiveRuleParamDto activeRuleParam = ActiveRuleParamDto.createFor(paramDto).setValue(value);
dbClient.activeRuleDao().insertParam(session, activeRule, activeRuleParam);
return activeRule;
}
private ActiveRuleDto createActiveRuleWithSeverity(RuleDto rule, QProfileDto profile, String severity) {
ActiveRuleDto activeRule = ActiveRuleDto.createFor(profile, rule)
.setSeverity(severity);
dbClient.activeRuleDao().insert(session, activeRule);
return activeRule;
}
private void createRepository(String repositoryKey, String repositoryLanguage, String repositoryName) {
RuleRepositoryDto dto = new RuleRepositoryDto(repositoryKey, repositoryLanguage, repositoryName);
dbClient.ruleRepositoryDao().insert(session, singletonList(dto));
session.commit();
}
}
| 9,401 | 35.44186 | 141 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/CopyActionIT.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.qualityprofile.ws;
import java.io.Reader;
import java.io.Writer;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.JUnitTempFolder;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.core.util.SequenceUuidFactory;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.qualityprofile.QProfileBackuper;
import org.sonar.server.qualityprofile.QProfileCopier;
import org.sonar.server.qualityprofile.QProfileFactory;
import org.sonar.server.qualityprofile.QProfileFactoryImpl;
import org.sonar.server.qualityprofile.QProfileRestoreSummary;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
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.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
import static org.sonar.test.JsonAssert.assertJson;
public class CopyActionIT {
private static final String A_LANGUAGE = "lang1";
@Rule
public DbTester db = DbTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public JUnitTempFolder tempDir = new JUnitTempFolder();
private final ActiveRuleIndexer activeRuleIndexer = mock(ActiveRuleIndexer.class);
private final TestBackuper backuper = new TestBackuper();
private final QProfileFactory profileFactory = new QProfileFactoryImpl(db.getDbClient(), new SequenceUuidFactory(), System2.INSTANCE, activeRuleIndexer);
private final QProfileCopier profileCopier = new QProfileCopier(db.getDbClient(), profileFactory, backuper);
private final Languages languages = LanguageTesting.newLanguages(A_LANGUAGE);
private final QProfileWsSupport wsSupport = new QProfileWsSupport(db.getDbClient(), userSession);
private final CopyAction underTest = new CopyAction(db.getDbClient(), profileCopier, languages, userSession, wsSupport);
private final WsActionTester tester = new WsActionTester(underTest);
@Test
public void test_definition() {
WebService.Action definition = tester.getDef();
assertThat(definition.key()).isEqualTo("copy");
assertThat(definition.isInternal()).isFalse();
assertThat(definition.responseExampleAsString()).isNotEmpty();
assertThat(definition.since()).isEqualTo("5.2");
assertThat(definition.isPost()).isTrue();
assertThat(definition.params()).extracting(WebService.Param::key).containsOnly("fromKey", "toName");
assertThat(definition.param("fromKey").isRequired()).isTrue();
assertThat(definition.param("toName").isRequired()).isTrue();
}
@Test
public void example() {
logInAsQProfileAdministrator();
QProfileDto parent = db.qualityProfiles().insert(p -> p.setKee("AU-TpxcA-iU5OvuD2FL2"));
QProfileDto profile = db.qualityProfiles().insert(p -> p.setKee("old")
.setLanguage("Java")
.setParentKee(parent.getKee()));
String profileUuid = profile.getRulesProfileUuid();
String response = tester.newRequest()
.setMethod("POST")
.setParam("fromKey", profile.getKee())
.setParam("toName", "My New Profile")
.execute()
.getInput();
assertJson(response).ignoreFields("key").isSimilarTo(getClass().getResource("copy-example.json"));
}
@Test
public void create_profile_with_specified_name_and_copy_rules_from_source_profile() {
logInAsQProfileAdministrator();
QProfileDto sourceProfile = db.qualityProfiles().insert(p -> p.setLanguage(A_LANGUAGE));
TestResponse response = tester.newRequest()
.setMethod("POST")
.setParam("fromKey", sourceProfile.getKee())
.setParam("toName", "target-name")
.execute();
String generatedUuid = "1";
assertJson(response.getInput()).isSimilarTo("{" +
" \"key\": \"" + generatedUuid + "\"," +
" \"name\": \"target-name\"," +
" \"language\": \"lang1\"," +
" \"languageName\": \"Lang1\"," +
" \"isDefault\": false," +
" \"isInherited\": false" +
"}");
QProfileDto loadedProfile = db.getDbClient().qualityProfileDao().selectByNameAndLanguage(db.getSession(), "target-name", sourceProfile.getLanguage());
assertThat(loadedProfile.getKee()).isEqualTo(generatedUuid);
assertThat(loadedProfile.getParentKee()).isNull();
assertThat(backuper.copiedProfile.getKee()).isEqualTo(sourceProfile.getKee());
assertThat(backuper.toProfile.getLanguage()).isEqualTo(sourceProfile.getLanguage());
assertThat(backuper.toProfile.getName()).isEqualTo("target-name");
assertThat(backuper.toProfile.getKee()).isEqualTo(generatedUuid);
assertThat(backuper.toProfile.getParentKee()).isNull();
}
@Test
public void copy_rules_on_existing_profile() {
logInAsQProfileAdministrator();
QProfileDto sourceProfile = db.qualityProfiles().insert(p -> p.setLanguage(A_LANGUAGE));
QProfileDto targetProfile = db.qualityProfiles().insert(p -> p.setLanguage(A_LANGUAGE));
TestResponse response = tester.newRequest()
.setMethod("POST")
.setParam("fromKey", sourceProfile.getKee())
.setParam("toName", targetProfile.getName())
.execute();
assertJson(response.getInput()).isSimilarTo("{" +
" \"key\": \"" + targetProfile.getKee() + "\"," +
" \"name\": \"" + targetProfile.getName() + "\"," +
" \"language\": \"lang1\"," +
" \"languageName\": \"Lang1\"," +
" \"isDefault\": false," +
" \"isInherited\": false" +
"}");
QProfileDto loadedProfile = db.getDbClient().qualityProfileDao().selectByUuid(db.getSession(), targetProfile.getKee());
assertThat(loadedProfile).isNotNull();
assertThat(backuper.copiedProfile.getKee()).isEqualTo(sourceProfile.getKee());
assertThat(backuper.toProfile.getKee()).isEqualTo(targetProfile.getKee());
}
@Test
public void create_profile_with_same_parent_as_source_profile() {
logInAsQProfileAdministrator();
QProfileDto parentProfile = db.qualityProfiles().insert(p -> p.setLanguage(A_LANGUAGE));
QProfileDto sourceProfile = db.qualityProfiles().insert(p -> p.setLanguage(A_LANGUAGE).setParentKee(parentProfile.getKee()));
TestResponse response = tester.newRequest()
.setMethod("POST")
.setParam("fromKey", sourceProfile.getKee())
.setParam("toName", "target-name")
.execute();
String generatedUuid = "1";
assertJson(response.getInput()).isSimilarTo("{" +
" \"key\": \"" + generatedUuid + "\"," +
" \"name\": \"target-name\"," +
" \"language\": \"lang1\"," +
" \"languageName\": \"Lang1\"," +
" \"isDefault\": false," +
" \"isInherited\": true" +
"}");
QProfileDto loadedProfile = db.getDbClient().qualityProfileDao().selectByNameAndLanguage(db.getSession(), "target-name", sourceProfile.getLanguage());
assertThat(loadedProfile.getKee()).isEqualTo(generatedUuid);
assertThat(loadedProfile.getParentKee()).isEqualTo(parentProfile.getKee());
assertThat(backuper.copiedProfile.getKee()).isEqualTo(sourceProfile.getKee());
assertThat(backuper.toProfile.getLanguage()).isEqualTo(sourceProfile.getLanguage());
assertThat(backuper.toProfile.getName()).isEqualTo("target-name");
assertThat(backuper.toProfile.getKee()).isEqualTo(generatedUuid);
assertThat(backuper.toProfile.getParentKee()).isEqualTo(parentProfile.getKee());
}
@Test
public void throw_UnauthorizedException_if_not_logged_in() {
userSession.anonymous();
assertThatThrownBy(() -> {
tester.newRequest()
.setMethod("POST")
.setParam("fromKey", "foo")
.setParam("toName", "bar")
.execute();
})
.isInstanceOf(UnauthorizedException.class)
.hasMessage("Authentication is required");
}
@Test
public void throw_ForbiddenException_if_not_profile_global_administrator() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(A_LANGUAGE));
userSession.logIn().addPermission(GlobalPermission.SCAN);
assertThatThrownBy(() -> {
tester.newRequest()
.setMethod("POST")
.setParam("fromKey", profile.getKee())
.setParam("toName", "bar")
.execute();
})
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void throw_ForbiddenException_if_not_profile_administrator() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(A_LANGUAGE));
userSession.logIn().addPermission(GlobalPermission.SCAN);
assertThatThrownBy(() -> {
tester.newRequest()
.setMethod("POST")
.setParam("fromKey", profile.getKee())
.setParam("toName", "bar")
.execute();
})
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void fail_if_parameter_fromKey_is_missing() {
logInAsQProfileAdministrator();
assertThatThrownBy(() -> {
tester.newRequest()
.setParam("toName", "bar")
.execute();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The 'fromKey' parameter is missing");
}
@Test
public void fail_if_parameter_toName_is_missing() {
logInAsQProfileAdministrator();
assertThatThrownBy(() -> {
tester.newRequest()
.setParam("fromKey", "foo")
.execute();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The 'toName' parameter is missing");
}
private void logInAsQProfileAdministrator() {
userSession
.logIn()
.addPermission(ADMINISTER_QUALITY_PROFILES);
}
private static class TestBackuper implements QProfileBackuper {
private QProfileDto copiedProfile;
private QProfileDto toProfile;
@Override
public void backup(DbSession dbSession, QProfileDto profile, Writer backupWriter) {
throw new UnsupportedOperationException();
}
@Override
public QProfileRestoreSummary restore(DbSession dbSession, Reader backup, @Nullable String overriddenProfileName) {
throw new UnsupportedOperationException();
}
@Override
public QProfileRestoreSummary restore(DbSession dbSession, Reader backup, QProfileDto profile) {
throw new UnsupportedOperationException();
}
@Override
public QProfileRestoreSummary copy(DbSession dbSession, QProfileDto from, QProfileDto to) {
this.copiedProfile = from;
this.toProfile = to;
return null;
}
}
}
| 11,859 | 37.75817 | 155 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/CreateActionIT.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.qualityprofile.ws;
import com.google.common.collect.ImmutableMap;
import java.io.Reader;
import java.util.Collections;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.profiles.ProfileImporter;
import org.sonar.api.profiles.RulesProfile;
import org.sonar.api.rules.RulePriority;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.ValidationMessages;
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.QProfileDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
import org.sonar.server.qualityprofile.QProfileExporters;
import org.sonar.server.qualityprofile.QProfileFactoryImpl;
import org.sonar.server.qualityprofile.QProfileRules;
import org.sonar.server.qualityprofile.QProfileRulesImpl;
import org.sonar.server.qualityprofile.builtin.RuleActivator;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import org.sonar.server.rule.index.RuleIndex;
import org.sonar.server.rule.index.RuleIndexer;
import org.sonar.server.rule.index.RuleQuery;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import org.sonar.test.JsonAssert;
import org.sonarqube.ws.MediaTypes;
import org.sonarqube.ws.Qualityprofiles.CreateWsResponse;
import org.sonarqube.ws.Qualityprofiles.CreateWsResponse.QualityProfile;
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.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
import static org.sonar.db.permission.GlobalPermission.SCAN;
import static org.sonar.server.language.LanguageTesting.newLanguages;
public class CreateActionIT {
private static final String XOO_LANGUAGE = "xoo";
private static final RuleDto RULE = RuleTesting.newXooX1()
.setSeverity("MINOR")
.setLanguage(XOO_LANGUAGE);
@Rule
public DbTester db = DbTester.create();
@Rule
public EsTester es = EsTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private DbClient dbClient = db.getDbClient();
private DbSession dbSession = db.getSession();
private RuleIndex ruleIndex = new RuleIndex(es.client(), System2.INSTANCE);
private RuleIndexer ruleIndexer = new RuleIndexer(es.client(), dbClient);
private ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(dbClient, es.client());
private ProfileImporter[] profileImporters = createImporters();
private QualityProfileChangeEventService qualityProfileChangeEventService = mock(QualityProfileChangeEventService.class);
private RuleActivator ruleActivator = new RuleActivator(System2.INSTANCE, dbClient, null, userSession);
private QProfileRules qProfileRules = new QProfileRulesImpl(dbClient, ruleActivator, ruleIndex, activeRuleIndexer, qualityProfileChangeEventService);
private QProfileExporters qProfileExporters = new QProfileExporters(dbClient, null, qProfileRules, profileImporters);
private CreateAction underTest = new CreateAction(dbClient, new QProfileFactoryImpl(dbClient, UuidFactoryFast.getInstance(), System2.INSTANCE, activeRuleIndexer),
qProfileExporters, newLanguages(XOO_LANGUAGE), userSession, activeRuleIndexer, profileImporters);
private WsActionTester ws = new WsActionTester(underTest);
@Test
public void definition() {
WebService.Action definition = ws.getDef();
assertThat(definition.responseExampleAsString()).isNotEmpty();
assertThat(definition.isPost()).isTrue();
assertThat(definition.params()).extracting(Param::key)
.containsExactlyInAnyOrder("language", "name", "backup_with_messages", "backup_with_errors", "backup_xoo_lint");
}
@Test
public void create_profile() {
logInAsQProfileAdministrator();
CreateWsResponse response = executeRequest("New Profile", XOO_LANGUAGE);
QProfileDto dto = dbClient.qualityProfileDao().selectByNameAndLanguage(dbSession, "New Profile", XOO_LANGUAGE);
assertThat(dto.getKee()).isNotNull();
assertThat(dto.getLanguage()).isEqualTo(XOO_LANGUAGE);
assertThat(dto.getName()).isEqualTo("New Profile");
QualityProfile profile = response.getProfile();
assertThat(profile.getKey()).isEqualTo(dto.getKee());
assertThat(profile.getName()).isEqualTo("New Profile");
assertThat(profile.getLanguage()).isEqualTo(XOO_LANGUAGE);
assertThat(profile.getIsInherited()).isFalse();
assertThat(profile.getIsDefault()).isFalse();
assertThat(profile.hasInfos()).isFalse();
assertThat(profile.hasWarnings()).isFalse();
}
@Test
public void create_profile_from_backup_xml() {
logInAsQProfileAdministrator();
insertRule(RULE);
executeRequest("New Profile", XOO_LANGUAGE, ImmutableMap.of("xoo_lint", "<xml/>"));
QProfileDto dto = dbClient.qualityProfileDao().selectByNameAndLanguage(dbSession, "New Profile", XOO_LANGUAGE);
assertThat(dto.getKee()).isNotNull();
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, dto.getKee())).hasSize(1);
assertThat(ruleIndex.searchAll(new RuleQuery().setQProfile(dto).setActivation(true))).toIterable().hasSize(1);
}
@Test
public void create_profile_with_messages() {
logInAsQProfileAdministrator();
CreateWsResponse response = executeRequest("Profile with messages", XOO_LANGUAGE, ImmutableMap.of("with_messages", "<xml/>"));
QualityProfile profile = response.getProfile();
assertThat(profile.getInfos().getInfosList()).containsOnly("an info");
assertThat(profile.getWarnings().getWarningsList()).containsOnly("a warning");
}
@Test
public void fail_if_unsufficient_privileges() {
userSession
.logIn()
.addPermission(SCAN);
assertThatThrownBy(() -> {
executeRequest(ws.newRequest()
.setParam("name", "some Name")
.setParam("language", XOO_LANGUAGE));
})
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void fail_if_import_generate_error() {
logInAsQProfileAdministrator();
assertThatThrownBy(() -> {
executeRequest("Profile with errors", XOO_LANGUAGE, ImmutableMap.of("with_errors", "<xml/>"));
})
.isInstanceOf(BadRequestException.class);
}
@Test
public void test_json() {
logInAsQProfileAdministrator();
TestResponse response = ws.newRequest()
.setMethod("POST")
.setMediaType(MediaTypes.JSON)
.setParam("language", XOO_LANGUAGE)
.setParam("name", "Yeehaw!")
.execute();
JsonAssert.assertJson(response.getInput()).isSimilarTo(getClass().getResource("CreateActionIT/test_json.json"));
assertThat(response.getMediaType()).isEqualTo(MediaTypes.JSON);
}
private void insertRule(RuleDto ruleDto) {
dbClient.ruleDao().insert(dbSession, ruleDto);
dbSession.commit();
ruleIndexer.commitAndIndex(dbSession, ruleDto.getUuid());
}
private CreateWsResponse executeRequest(String name, String language) {
return executeRequest(name, language, Collections.emptyMap());
}
private CreateWsResponse executeRequest(String name, String language, Map<String, String> xmls) {
TestRequest request = ws.newRequest()
.setParam("name", name)
.setParam("language", language);
for (Map.Entry<String, String> entry : xmls.entrySet()) {
request.setParam("backup_" + entry.getKey(), entry.getValue());
}
return executeRequest(request);
}
private CreateWsResponse executeRequest(TestRequest request) {
return request.executeProtobuf(CreateWsResponse.class);
}
private ProfileImporter[] createImporters() {
class DefaultProfileImporter extends ProfileImporter {
private DefaultProfileImporter() {
super("xoo_lint", "Xoo Lint");
setSupportedLanguages(XOO_LANGUAGE);
}
@Override
public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
RulesProfile rulesProfile = RulesProfile.create();
rulesProfile.activateRule(org.sonar.api.rules.Rule.create(RULE.getRepositoryKey(), RULE.getRuleKey()), RulePriority.BLOCKER);
return rulesProfile;
}
}
class ProfileImporterGeneratingMessages extends ProfileImporter {
private ProfileImporterGeneratingMessages() {
super("with_messages", "With messages");
setSupportedLanguages(XOO_LANGUAGE);
}
@Override
public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
RulesProfile rulesProfile = RulesProfile.create();
messages.addWarningText("a warning");
messages.addInfoText("an info");
return rulesProfile;
}
}
class ProfileImporterGeneratingErrors extends ProfileImporter {
private ProfileImporterGeneratingErrors() {
super("with_errors", "With errors");
setSupportedLanguages(XOO_LANGUAGE);
}
@Override
public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
RulesProfile rulesProfile = RulesProfile.create();
messages.addErrorText("error!");
return rulesProfile;
}
}
return new ProfileImporter[] {
new DefaultProfileImporter(), new ProfileImporterGeneratingMessages(), new ProfileImporterGeneratingErrors()
};
}
private void logInAsQProfileAdministrator() {
userSession
.logIn()
.addPermission(ADMINISTER_QUALITY_PROFILES);
}
}
| 10,825 | 38.367273 | 164 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/DeactivateRuleActionIT.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.qualityprofile.ws;
import java.net.HttpURLConnection;
import java.util.Collection;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.MockitoAnnotations;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.qualityprofile.QProfileRules;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
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.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.UUID_SIZE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_KEY;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_RULE;
public class DeactivateRuleActionIT {
@Rule
public DbTester db = DbTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final ArgumentCaptor<Collection<String>> ruleUuidsCaptor = ArgumentCaptor.forClass(Collection.class);
private final DbClient dbClient = db.getDbClient();
private final QProfileRules qProfileRules = mock(QProfileRules.class);
private final QProfileWsSupport wsSupport = new QProfileWsSupport(dbClient, userSession);
private final DeactivateRuleAction underTest = new DeactivateRuleAction(dbClient, qProfileRules, userSession, wsSupport);
private final WsActionTester ws = new WsActionTester(underTest);
@Before
public void before() {
MockitoAnnotations.initMocks(this);
}
@Test
public void definition() {
WebService.Action definition = ws.getDef();
assertThat(definition).isNotNull();
assertThat(definition.isPost()).isTrue();
assertThat(definition.params()).extracting(WebService.Param::key).containsExactlyInAnyOrder("key", "rule");
}
@Test
public void deactivate_rule() {
userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
QProfileDto qualityProfile = db.qualityProfiles().insert();
RuleDto rule = db.rules().insert(RuleTesting.randomRuleKey());
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_RULE, rule.getKey().toString())
.setParam(PARAM_KEY, qualityProfile.getKee());
TestResponse response = request.execute();
assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
ArgumentCaptor<QProfileDto> qProfileDtoCaptor = ArgumentCaptor.forClass(QProfileDto.class);
verify(qProfileRules).deactivateAndCommit(any(DbSession.class), qProfileDtoCaptor.capture(), ruleUuidsCaptor.capture());
assertThat(ruleUuidsCaptor.getValue()).containsExactly(rule.getUuid());
assertThat(qProfileDtoCaptor.getValue().getKee()).isEqualTo(qualityProfile.getKee());
}
@Test
public void as_qprofile_editor() {
UserDto user = db.users().insertUser();
QProfileDto qualityProfile = db.qualityProfiles().insert();
db.qualityProfiles().addUserPermission(qualityProfile, user);
userSession.logIn(user);
RuleKey ruleKey = RuleTesting.randomRuleKey();
db.rules().insert(ruleKey);
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_RULE, ruleKey.toString())
.setParam(PARAM_KEY, qualityProfile.getKee())
.execute();
verify(qProfileRules).deactivateAndCommit(any(DbSession.class), any(QProfileDto.class), anyCollection());
}
@Test
public void fail_if_not_logged_in() {
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_RULE, RuleTesting.newRule().getKey().toString())
.setParam(PARAM_KEY, randomAlphanumeric(UUID_SIZE));
assertThatThrownBy(request::execute)
.isInstanceOf(UnauthorizedException.class);
}
@Test
public void fail_activate_external_rule() {
userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
QProfileDto qualityProfile = db.qualityProfiles().insert();
RuleDto rule = db.rules().insert(r -> r.setIsExternal(true));
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_RULE, rule.getKey().toString())
.setParam(PARAM_KEY, qualityProfile.getKee());
assertThatThrownBy(() -> request.execute())
.isInstanceOf(BadRequestException.class)
.hasMessage(String.format("Operation forbidden for rule '%s' imported from an external rule engine.", rule.getKey()));
}
@Test
public void fail_deactivate_if_built_in_profile() {
RuleDto rule = db.rules().insert();
userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
QProfileDto qualityProfile = db.qualityProfiles().insert(profile -> profile.setIsBuiltIn(true));
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_RULE, rule.getKey().toString())
.setParam(PARAM_KEY, qualityProfile.getKee());
assertThatThrownBy(request::execute)
.isInstanceOf(BadRequestException.class);
}
}
| 6,731 | 40.300613 | 124 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/DeactivateRulesActionIT.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.qualityprofile.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.qualityprofile.QProfileRules;
import org.sonar.server.rule.ws.RuleQueryFactory;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
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.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
import static org.sonar.db.permission.GlobalPermission.SCAN;
import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.UUID_SIZE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_TARGET_KEY;
public class DeactivateRulesActionIT {
@Rule
public DbTester db = DbTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private DbClient dbClient = db.getDbClient();
private QProfileRules qProfileRules = mock(QProfileRules.class, RETURNS_DEEP_STUBS);
private final QProfileWsSupport wsSupport = new QProfileWsSupport(dbClient, userSession);
private RuleQueryFactory ruleQueryFactory = mock(RuleQueryFactory.class, RETURNS_DEEP_STUBS);
private DeactivateRulesAction underTest = new DeactivateRulesAction(ruleQueryFactory, userSession, qProfileRules, wsSupport, dbClient);
private WsActionTester ws = new WsActionTester(underTest);
@Test
public void definition() {
WebService.Action definition = ws.getDef();
assertThat(definition).isNotNull();
assertThat(definition.isPost()).isTrue();
assertThat(definition.params()).extracting(WebService.Param::key).containsExactlyInAnyOrder(
"types",
"template_key",
"languages",
"is_template",
"inheritance",
"qprofile",
"compareToProfile",
"tags",
"asc",
"q",
"active_severities",
"s",
"repositories",
"targetKey",
"statuses",
"rule_key",
"available_since",
"activation",
"severities",
"cwe",
"owaspTop10",
"owaspTop10-2021",
"sansTop25",
"sonarsourceSecurity");
}
@Test
public void as_global_admin() {
UserDto user = db.users().insertUser();
QProfileDto qualityProfile = db.qualityProfiles().insert();
userSession.logIn(user).addPermission(ADMINISTER_QUALITY_PROFILES);
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TARGET_KEY, qualityProfile.getKee())
.execute();
verify(qProfileRules).bulkDeactivateAndCommit(any(), any(), any());
}
@Test
public void as_qprofile_editor() {
UserDto user = db.users().insertUser();
GroupDto group = db.users().insertGroup();
QProfileDto qualityProfile = db.qualityProfiles().insert();
db.qualityProfiles().addGroupPermission(qualityProfile, group);
userSession.logIn(user).setGroups(group);
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TARGET_KEY, qualityProfile.getKee())
.execute();
verify(qProfileRules).bulkDeactivateAndCommit(any(), any(), any());
}
@Test
public void fail_if_not_logged_in() {
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TARGET_KEY, randomAlphanumeric(UUID_SIZE));
assertThatThrownBy(request::execute)
.isInstanceOf(UnauthorizedException.class);
}
@Test
public void fail_if_built_in_profile() {
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
QProfileDto qualityProfile = db.qualityProfiles().insert(p -> p.setIsBuiltIn(true));
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TARGET_KEY, qualityProfile.getKee());
assertThatThrownBy(request::execute)
.isInstanceOf(BadRequestException.class);
}
@Test
public void fail_if_not_quality_profile_administrator() {
userSession.logIn(db.users().insertUser()).addPermission(SCAN);
QProfileDto qualityProfile = db.qualityProfiles().insert();
TestRequest request = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TARGET_KEY, qualityProfile.getKee());
assertThatThrownBy(request::execute)
.isInstanceOf(ForbiddenException.class);
}
}
| 5,771 | 34.850932 | 137 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/DeleteActionIT.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.qualityprofile.ws;
import java.net.HttpURLConnection;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.System2;
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.permission.GlobalPermission;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.qualityprofile.QProfileFactoryImpl;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
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.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_KEY;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE;
public class DeleteActionIT {
private static final String A_LANGUAGE = "xoo";
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final DbClient dbClient = db.getDbClient();
private final DbSession dbSession = db.getSession();
private final ActiveRuleIndexer activeRuleIndexer = mock(ActiveRuleIndexer.class);
private final DeleteAction underTest = new DeleteAction(
new Languages(LanguageTesting.newLanguage(A_LANGUAGE)),
new QProfileFactoryImpl(dbClient, UuidFactoryFast.getInstance(), System2.INSTANCE, activeRuleIndexer), dbClient, userSession,
new QProfileWsSupport(dbClient, userSession));
private final WsActionTester ws = new WsActionTester(underTest);
@Test
public void delete_profile_by_language_and_name() {
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
QProfileDto profile1 = createProfile();
QProfileDto profile2 = createProfile();
db.qualityProfiles().associateWithProject(project, profile1);
logInAsQProfileAdministrator();
TestResponse response = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_LANGUAGE, profile1.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, profile1.getName())
.execute();
assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
verifyProfileDoesNotExist(profile1);
verifyProfileExists(profile2);
}
@Test
public void as_qprofile_editor_and_global_admin() {
QProfileDto profile = createProfile();
UserDto user = db.users().insertUser();
db.qualityProfiles().addUserPermission(profile, user);
userSession.logIn(user).addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
TestResponse response = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_LANGUAGE, profile.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.execute();
assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
verifyProfileDoesNotExist(profile);
}
@Test
public void fail_if_built_in_profile() {
QProfileDto profile1 = db.qualityProfiles().insert(p -> p.setIsBuiltIn(true).setLanguage(A_LANGUAGE));
logInAsQProfileAdministrator();
assertThatThrownBy(() -> {
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_LANGUAGE, profile1.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, profile1.getName())
.execute();
})
.isInstanceOf(BadRequestException.class);
}
@Test
public void fail_if_not_profile_administrator() {
QProfileDto qprofile = createProfile();
userSession.logIn(db.users().insertUser());
assertThatThrownBy(() -> {
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_LANGUAGE, qprofile.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, qprofile.getName())
.execute();
})
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void fail_if_not_logged_in() {
QProfileDto profile = createProfile();
assertThatThrownBy(() -> {
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_KEY, profile.getKee())
.execute();
})
.isInstanceOf(UnauthorizedException.class);
}
@Test
public void fail_if_missing_parameters() {
userSession.logIn();
assertThatThrownBy(() -> {
ws.newRequest()
.setMethod("POST")
.execute();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The 'language' parameter is missing");
}
@Test
public void fail_if_missing_language_parameter() {
QProfileDto profile = createProfile();
logInAsQProfileAdministrator();
assertThatThrownBy(() -> {
ws.newRequest()
.setMethod("POST")
.setParam("profileName", profile.getName())
.execute();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The 'language' parameter is missing");
}
@Test
public void fail_if_missing_name_parameter() {
QProfileDto profile = createProfile();
logInAsQProfileAdministrator();
assertThatThrownBy(() -> {
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_LANGUAGE, profile.getLanguage())
.execute();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The 'qualityProfile' parameter is missing");
}
@Test
public void fail_if_profile_does_not_exist() {
userSession.logIn();
assertThatThrownBy(() -> {
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_QUALITY_PROFILE, "does_not_exist")
.setParam(PARAM_LANGUAGE, "xoo")
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Quality Profile for language 'xoo' and name 'does_not_exist' does not exist");
}
@Test
public void fail_if_deleting_default_profile() {
QProfileDto profile = createProfile();
db.qualityProfiles().setAsDefault(profile);
logInAsQProfileAdministrator();
assertThatThrownBy(() -> {
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_LANGUAGE, profile.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.execute();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Profile '" + profile.getName() + "' cannot be deleted because it is marked as default");
}
@Test
public void fail_if_a_descendant_is_marked_as_default() {
QProfileDto parentProfile = createProfile();
QProfileDto childProfile = db.qualityProfiles().insert(p -> p.setLanguage(A_LANGUAGE).setParentKee(parentProfile.getKee()));
db.qualityProfiles().setAsDefault(childProfile);
logInAsQProfileAdministrator();
assertThatThrownBy(() -> {
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_LANGUAGE, parentProfile.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, parentProfile.getName())
.execute();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Profile '" + parentProfile.getName() + "' cannot be deleted because its descendant named '" + childProfile.getName() +
"' is marked as default");
}
@Test
public void definition() {
WebService.Action definition = ws.getDef();
assertThat(definition.isPost()).isTrue();
assertThat(definition.params()).extracting(Param::key).containsExactlyInAnyOrder("language", "qualityProfile");
}
private void logInAsQProfileAdministrator() {
userSession
.logIn(db.users().insertUser())
.addPermission(ADMINISTER_QUALITY_PROFILES);
}
private void verifyProfileDoesNotExist(QProfileDto profile) {
assertThat(dbClient.qualityProfileDao().selectByUuid(dbSession, profile.getKee())).isNull();
assertThat(dbClient.qualityProfileDao().selectSelectedProjects(dbSession, profile, null)).isEmpty();
}
private void verifyProfileExists(QProfileDto profile) {
assertThat(dbClient.qualityProfileDao().selectByUuid(dbSession, profile.getKee())).isNotNull();
}
private QProfileDto createProfile() {
return db.qualityProfiles().insert(p -> p.setLanguage(A_LANGUAGE));
}
}
| 9,801 | 34.258993 | 137 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ExportActionIT.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.qualityprofile.ws;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.profiles.ProfileExporter;
import org.sonar.api.profiles.RulesProfile;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.qualityprofile.QProfileBackuper;
import org.sonar.server.qualityprofile.QProfileExporters;
import org.sonar.server.qualityprofile.QProfileRestoreSummary;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsActionTester;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ExportActionIT {
private static final String XOO_LANGUAGE = "xoo";
private static final String JAVA_LANGUAGE = "java";
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final DbClient dbClient = db.getDbClient();
private final QProfileBackuper backuper = new TestBackuper();
@Test
public void export_profile() {
QProfileDto profile = createProfile(false);
WsActionTester tester = newWsActionTester(newExporter("polop"), newExporter("palap"));
String result = tester.newRequest()
.setParam("language", profile.getLanguage())
.setParam("qualityProfile", profile.getName())
.setParam("exporterKey", "polop").execute()
.getInput();
assertThat(result).isEqualTo("Profile " + profile.getLanguage() + "/" + profile.getName() + " exported by polop");
}
@Test
public void export_default_profile() {
QProfileDto nonDefaultProfile = createProfile(false);
QProfileDto defaultProfile = createProfile(true);
WsActionTester tester = newWsActionTester(newExporter("polop"), newExporter("palap"));
String result = tester.newRequest()
.setParam("language", XOO_LANGUAGE)
.setParam("exporterKey", "polop")
.execute()
.getInput();
assertThat(result).isEqualTo("Profile " + defaultProfile.getLanguage() + "/" + defaultProfile.getName() + " exported by polop");
}
@Test
public void return_backup_when_exporter_is_not_specified() {
QProfileDto profile = createProfile(false);
String result = newWsActionTester(newExporter("polop")).newRequest()
.setParam("language", profile.getLanguage())
.setParam("qualityProfile", profile.getName())
.execute()
.getInput();
assertThat(result).isEqualTo("Backup of " + profile.getLanguage() + "/" + profile.getKee());
}
@Test
public void throw_NotFoundException_if_profile_with_specified_name_does_not_exist() {
assertThatThrownBy(() -> {
newWsActionTester().newRequest()
.setParam("language", XOO_LANGUAGE)
.setParam("exporterKey", "polop").execute();
})
.isInstanceOf(NotFoundException.class);
}
@Test
public void throw_IAE_if_export_with_specified_key_does_not_exist() {
QProfileDto profile = createProfile(true);
assertThatThrownBy(() -> {
newWsActionTester(newExporter("polop"), newExporter("palap")).newRequest()
.setParam("language", XOO_LANGUAGE)
.setParam("exporterKey", "unknown").execute();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Value of parameter 'exporterKey' (unknown) must be one of: [polop, palap]");
}
@Test
public void definition_without_exporters() {
WebService.Action definition = newWsActionTester().getDef();
assertThat(definition.isPost()).isFalse();
assertThat(definition.isInternal()).isFalse();
assertThat(definition.params()).extracting(WebService.Param::key).containsExactlyInAnyOrder("language", "qualityProfile");
WebService.Param name = definition.param("qualityProfile");
assertThat(name.deprecatedSince()).isNullOrEmpty();
WebService.Param language = definition.param("language");
assertThat(language.deprecatedSince()).isNullOrEmpty();
}
@Test
public void definition_with_exporters() {
WebService.Action definition = newWsActionTester(newExporter("polop"), newExporter("palap")).getDef();
assertThat(definition.isPost()).isFalse();
assertThat(definition.isInternal()).isFalse();
assertThat(definition.params()).extracting("key").containsExactlyInAnyOrder("language", "qualityProfile", "exporterKey");
WebService.Param exportersParam = definition.param("exporterKey");
assertThat(exportersParam.possibleValues()).containsOnly("polop", "palap");
assertThat(exportersParam.isInternal()).isFalse();
}
private QProfileDto createProfile(boolean isDefault) {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO_LANGUAGE));
if (isDefault) {
db.qualityProfiles().setAsDefault(profile);
}
return profile;
}
private WsActionTester newWsActionTester(ProfileExporter... profileExporters) {
QProfileExporters exporters = new QProfileExporters(dbClient, null, null, profileExporters, null);
return new WsActionTester(new ExportAction(dbClient, backuper, exporters, LanguageTesting.newLanguages(XOO_LANGUAGE, JAVA_LANGUAGE)));
}
private static ProfileExporter newExporter(String key) {
return new ProfileExporter(key, StringUtils.capitalize(key)) {
@Override
public String getMimeType() {
return "text/plain+" + key;
}
@Override
public void exportProfile(RulesProfile profile, Writer writer) {
try {
writer.write(format("Profile %s/%s exported by %s", profile.getLanguage(), profile.getName(), key));
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
};
}
private static class TestBackuper implements QProfileBackuper {
@Override
public void backup(DbSession dbSession, QProfileDto profile, Writer backupWriter) {
try {
backupWriter.write(format("Backup of %s/%s", profile.getLanguage(), profile.getKee()));
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public QProfileRestoreSummary restore(DbSession dbSession, Reader backup, @Nullable String overriddenProfileName) {
throw new UnsupportedOperationException();
}
@Override
public QProfileRestoreSummary restore(DbSession dbSession, Reader backup, QProfileDto profile) {
throw new UnsupportedOperationException();
}
@Override
public QProfileRestoreSummary copy(DbSession dbSession, QProfileDto from, QProfileDto to) {
throw new UnsupportedOperationException();
}
}
}
| 7,870 | 36.127358 | 138 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/InheritanceActionIT.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.qualityprofile.ws;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Languages;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.System2;
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.QProfileDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.server.es.EsClient;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
import org.sonar.server.qualityprofile.QProfileRules;
import org.sonar.server.qualityprofile.QProfileRulesImpl;
import org.sonar.server.qualityprofile.QProfileTree;
import org.sonar.server.qualityprofile.QProfileTreeImpl;
import org.sonar.server.qualityprofile.RuleActivation;
import org.sonar.server.qualityprofile.builtin.RuleActivator;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import org.sonar.server.rule.index.RuleIndex;
import org.sonar.server.rule.index.RuleIndexer;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.util.TypeValidations;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Qualityprofiles.InheritanceWsResponse;
import static java.util.Arrays.asList;
import static java.util.Collections.singleton;
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.sonar.test.JsonAssert.assertJson;
import static org.sonarqube.ws.MediaTypes.PROTOBUF;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE;
public class InheritanceActionIT {
@Rule
public DbTester db = DbTester.create();
@Rule
public EsTester es = EsTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private DbClient dbClient = db.getDbClient();
private DbSession dbSession = db.getSession();
private EsClient esClient = es.client();
private RuleIndexer ruleIndexer = new RuleIndexer(esClient, dbClient);
private ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(dbClient, esClient);
private RuleIndex ruleIndex = new RuleIndex(esClient, System2.INSTANCE);
private QualityProfileChangeEventService qualityProfileChangeEventService = mock(QualityProfileChangeEventService.class);
private RuleActivator ruleActivator = new RuleActivator(System2.INSTANCE, dbClient, new TypeValidations(new ArrayList<>()), userSession);
private QProfileRules qProfileRules = new QProfileRulesImpl(dbClient, ruleActivator, ruleIndex, activeRuleIndexer, qualityProfileChangeEventService);
private QProfileTree qProfileTree = new QProfileTreeImpl(dbClient, ruleActivator, System2.INSTANCE, activeRuleIndexer, mock(QualityProfileChangeEventService.class));
private WsActionTester ws = new WsActionTester(new InheritanceAction(
dbClient,
new QProfileWsSupport(dbClient, userSession),
new Languages()));
@Test
public void inheritance_nominal() {
RuleDto rule1 = createRule("xoo", "rule1");
RuleDto rule2 = createRule("xoo", "rule2");
RuleDto rule3 = createRule("xoo", "rule3");
/*
* sonar way (2) <- companyWide (2) <- buWide (2, 1 overriding) <- (forProject1 (2), forProject2 (2))
*/
QProfileDto sonarway = db.qualityProfiles().insert(p -> p.setKee("xoo-sonar-way").setLanguage("xoo").setName("Sonar way").setIsBuiltIn(true));
createActiveRule(rule1, sonarway);
createActiveRule(rule2, sonarway);
dbSession.commit();
activeRuleIndexer.indexAll();
QProfileDto companyWide = createProfile("xoo", "My Company Profile", "xoo-my-company-profile-12345");
setParent(sonarway, companyWide);
QProfileDto buWide = createProfile("xoo", "My BU Profile", "xoo-my-bu-profile-23456");
setParent(companyWide, buWide);
overrideActiveRuleSeverity(rule1, buWide, Severity.CRITICAL);
QProfileDto forProject1 = createProfile("xoo", "For Project One", "xoo-for-project-one-34567");
setParent(buWide, forProject1);
createActiveRule(rule3, forProject1);
dbSession.commit();
activeRuleIndexer.indexAll();
QProfileDto forProject2 = createProfile("xoo", "For Project Two", "xoo-for-project-two-45678");
setParent(buWide, forProject2);
overrideActiveRuleSeverity(rule2, forProject2, Severity.CRITICAL);
String response = ws.newRequest()
.setParam(PARAM_LANGUAGE, buWide.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, buWide.getName())
.execute()
.getInput();
assertJson(response).isSimilarTo(getClass().getResource("InheritanceActionIT/inheritance-buWide.json"));
}
@Test
public void inheritance_parent_child() throws Exception {
RuleDto rule1 = db.rules().insert();
RuleDto rule2 = db.rules().insert();
RuleDto rule3 = db.rules().insert();
ruleIndexer.commitAndIndex(db.getSession(), asList(rule1.getUuid(), rule2.getUuid(), rule3.getUuid()));
QProfileDto parent = db.qualityProfiles().insert();
db.qualityProfiles().activateRule(parent, rule1);
db.qualityProfiles().activateRule(parent, rule2);
long parentRules = 2;
QProfileDto child = db.qualityProfiles().insert(q -> q.setParentKee(parent.getKee()));
db.qualityProfiles().activateRule(child, rule3);
long childRules = 1;
activeRuleIndexer.indexAll();
InputStream response = ws.newRequest()
.setMediaType(PROTOBUF)
.setParam(PARAM_LANGUAGE, child.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, child.getName())
.execute()
.getInputStream();
InheritanceWsResponse result = InheritanceWsResponse.parseFrom(response);
assertThat(result.getProfile().getKey()).isEqualTo(child.getKee());
assertThat(result.getProfile().getActiveRuleCount()).isEqualTo(childRules);
assertThat(result.getAncestorsList()).extracting(InheritanceWsResponse.QualityProfile::getKey).containsExactly(parent.getKee());
assertThat(result.getAncestorsList()).extracting(InheritanceWsResponse.QualityProfile::getActiveRuleCount).containsExactly(parentRules);
}
@Test
public void inheritance_ignores_removed_rules() throws Exception {
RuleDto rule = db.rules().insert(r -> r.setStatus(RuleStatus.REMOVED));
ruleIndexer.commitAndIndex(db.getSession(), rule.getUuid());
QProfileDto profile = db.qualityProfiles().insert();
db.qualityProfiles().activateRule(profile, rule);
long activeRules = 0;
activeRuleIndexer.indexAll();
InputStream response = ws.newRequest()
.setMediaType(PROTOBUF)
.setParam(PARAM_LANGUAGE, profile.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.execute()
.getInputStream();
InheritanceWsResponse result = InheritanceWsResponse.parseFrom(response);
assertThat(result.getProfile().getKey()).isEqualTo(profile.getKee());
assertThat(result.getProfile().getActiveRuleCount()).isEqualTo(activeRules);
}
@Test
public void inheritance_no_family() {
// Simple profile, no parent, no child
QProfileDto remi = createProfile("xoo", "Nobodys Boy", "xoo-nobody-s-boy-01234");
String response = ws.newRequest()
.setParam(PARAM_LANGUAGE, remi.getLanguage())
.setParam(PARAM_QUALITY_PROFILE, remi.getName())
.execute()
.getInput();
assertJson(response).isSimilarTo(getClass().getResource("InheritanceActionIT/inheritance-simple.json"));
}
@Test
public void fail_if_not_found() {
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_LANGUAGE, "xoo")
.setParam(PARAM_QUALITY_PROFILE, "asd")
.execute();
})
.isInstanceOf(NotFoundException.class);
}
@Test
public void definition() {
WebService.Action definition = ws.getDef();
assertThat(definition.key()).isEqualTo("inheritance");
assertThat(definition.params()).extracting(Param::key).containsExactlyInAnyOrder("language", "qualityProfile");
}
private QProfileDto createProfile(String lang, String name, String key) {
return db.qualityProfiles().insert(qp -> qp.setKee(key).setName(name).setLanguage(lang));
}
private void setParent(QProfileDto profile, QProfileDto parent) {
qProfileTree.setParentAndCommit(dbSession, parent, profile);
}
private RuleDto createRule(String lang, String id) {
long now = new Date().getTime();
RuleDto rule = RuleTesting.newRule(RuleKey.of("blah", id))
.setLanguage(lang)
.setSeverity(Severity.BLOCKER)
.setStatus(RuleStatus.READY)
.setUpdatedAt(now)
.setCreatedAt(now);
dbClient.ruleDao().insert(dbSession, rule);
ruleIndexer.commitAndIndex(dbSession, rule.getUuid());
return rule;
}
private ActiveRuleDto createActiveRule(RuleDto rule, QProfileDto profile) {
long now = new Date().getTime();
ActiveRuleDto activeRule = ActiveRuleDto.createFor(profile, rule)
.setSeverity(rule.getSeverityString())
.setUpdatedAt(now)
.setCreatedAt(now);
dbClient.activeRuleDao().insert(dbSession, activeRule);
return activeRule;
}
private void overrideActiveRuleSeverity(RuleDto rule, QProfileDto profile, String severity) {
qProfileRules.activateAndCommit(dbSession, profile, singleton(RuleActivation.create(rule.getUuid(), severity, null)));
}
}
| 10,668 | 39.721374 | 167 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ProjectsActionIT.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.qualityprofile.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.server.ws.WebService.Param.PAGE;
import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
import static org.sonar.api.web.UserRole.USER;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_KEY;
public class ProjectsActionIT {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final WsActionTester ws = new WsActionTester(new ProjectsAction(db.getDbClient(), userSession));
@Test
public void list_authorized_projects_only() {
ProjectDto project1 = db.components().insertPrivateProject().getProjectDto();
ProjectDto project2 = db.components().insertPrivateProject().getProjectDto();
QProfileDto qualityProfile = db.qualityProfiles().insert();
associateProjectsWithProfile(qualityProfile, project1, project2);
// user only sees project1
UserDto user = db.users().insertUser();
db.users().insertProjectPermissionOnUser(user, USER, project1);
userSession.logIn(user);
ws.newRequest()
.setParam(PARAM_KEY, qualityProfile.getKee())
.setParam("selected", "selected")
.execute()
.assertJson("{\"results\":\n" +
" [\n" +
" {\n" +
" \"key\": \"" + project1.getKey() + "\",\n" +
" \"name\": \"" + project1.getName() + "\",\n" +
" \"selected\": true\n" +
" }\n" +
" ]}");
}
@Test
public void paginate() {
ProjectDto project1 = db.components().insertPublicProject(p -> p.setName("Project One")).getProjectDto();
ProjectDto project2 = db.components().insertPublicProject(p -> p.setName("Project Two")).getProjectDto();
ProjectDto project3 = db.components().insertPublicProject(p -> p.setName("Project Three")).getProjectDto();
ProjectDto project4 = db.components().insertPublicProject(p -> p.setName("Project Four")).getProjectDto();
QProfileDto qualityProfile = db.qualityProfiles().insert();
associateProjectsWithProfile(qualityProfile, project1, project2, project3, project4);
ws.newRequest()
.setParam(PARAM_KEY, qualityProfile.getKee())
.setParam("selected", "selected")
.setParam(PAGE_SIZE, "2")
.execute()
.assertJson("{\n" +
" \"results\":\n" +
" [\n" +
" {\n" +
" \"key\": \"" + project4.getKey() + "\",\n" +
" \"selected\": true\n" +
" },\n" +
" {\n" +
" \"key\": \"" + project1.getKey() + "\",\n" +
" \"selected\": true\n" +
" }\n" +
" ]\n" +
"}\n");
ws.newRequest()
.setParam(PARAM_KEY, qualityProfile.getKee())
.setParam("selected", "selected")
.setParam(PAGE_SIZE, "2")
.setParam(PAGE, "2")
.execute()
.assertJson("{\n" +
" \"results\":\n" +
" [\n" +
" {\n" +
" \"key\": \"" + project3.getKey() + "\",\n" +
" \"selected\": true\n" +
" },\n" +
" {\n" +
" \"key\": \"" + project2.getKey() + "\",\n" +
" \"selected\": true\n" +
" }\n" +
" ]\n" +
"}\n");
ws.newRequest()
.setParam(PARAM_KEY, qualityProfile.getKee())
.setParam("selected", "selected")
.setParam(PAGE_SIZE, "2")
.setParam(PAGE, "3")
.execute()
.assertJson("{\"results\":[]}");
ws.newRequest()
.setParam(PARAM_KEY, qualityProfile.getKee())
.setParam("selected", "selected")
.setParam(PAGE_SIZE, "2")
.setParam(PAGE, "4")
.execute()
.assertJson("{\"results\":[]}");
ws.newRequest()
.setParam(PARAM_KEY, qualityProfile.getKee())
.setParam("selected", "selected")
.setParam(PAGE_SIZE, "3")
.setParam(PAGE, "1")
.execute()
.assertJson("{\n" +
" \"results\":\n" +
" [\n" +
" {\n" +
" \"key\": \"" + project4.getKey() + "\",\n" +
" \"selected\": true\n" +
" },\n" +
" {\n" +
" \"key\": \"" + project1.getKey() + "\",\n" +
" \"selected\": true\n" +
" },\n" +
" {\n" +
" \"key\": \"" + project3.getKey() + "\",\n" +
" \"selected\": true\n" +
" }\n" +
" ]\n" +
"}\n");
ws.newRequest()
.setParam(PARAM_KEY, qualityProfile.getKee())
.setParam("selected", "selected")
.setParam(PAGE_SIZE, "3")
.setParam(PAGE, "2")
.execute()
.assertJson("{\n" +
" \"results\":\n" +
" [\n" +
" {\n" +
" \"key\": \"" + project2.getKey() + "\",\n" +
" \"selected\": true\n" +
" }\n" +
" ]\n" +
"}\n");
ws.newRequest()
.setParam(PARAM_KEY, qualityProfile.getKee())
.setParam("selected", "selected")
.setParam(PAGE_SIZE, "3")
.setParam(PAGE, "3")
.execute()
.assertJson("{\"results\":[]}");
}
@Test
public void show_unselected() {
ProjectDto project1 = db.components().insertPublicProject().getProjectDto();
ProjectDto project2 = db.components().insertPublicProject().getProjectDto();
QProfileDto qualityProfile = db.qualityProfiles().insert();
associateProjectsWithProfile(qualityProfile, project1);
ws.newRequest()
.setParam(PARAM_KEY, qualityProfile.getKee())
.setParam("selected", "deselected")
.execute()
.assertJson("{ \"results\":\n" +
" [\n" +
" {\n" +
" \"key\": \"" + project2.getKey() + "\",\n" +
" \"selected\": false\n" +
" }\n" +
" ]}");
}
@Test
public void show_all() {
ProjectDto project1 = db.components().insertPublicProject().getProjectDto();
ProjectDto project2 = db.components().insertPublicProject().getProjectDto();
ProjectDto project3 = db.components().insertPublicProject().getProjectDto();
ProjectDto project4 = db.components().insertPublicProject().getProjectDto();
QProfileDto qualityProfile1 = db.qualityProfiles().insert();
associateProjectsWithProfile(qualityProfile1, project1, project2);
QProfileDto qualityProfile2 = db.qualityProfiles().insert();
// project3 is associated with P2, must appear as not associated with xooP1
associateProjectsWithProfile(qualityProfile2, project3);
ws.newRequest()
.setParam(PARAM_KEY, qualityProfile1.getKee())
.setParam("selected", "all")
.execute()
.assertJson("{\n" +
" \"results\": [\n" +
" {\n" +
" \"key\": \"" + project1.getKey() + "\",\n" +
" \"selected\": true\n" +
" },\n" +
" {\n" +
" \"key\": \"" + project2.getKey() + "\",\n" +
" \"selected\": true\n" +
" },\n" +
" {\n" +
" \"key\": \"" + project3.getKey() + "\",\n" +
" \"selected\": false\n" +
" },\n" +
" {\n" +
" \"key\": \"" + project4.getKey() + "\",\n" +
" \"selected\": false\n" +
" }\n" +
" ]}\n");
}
@Test
public void filter_on_name_and_key() {
ProjectDto project1 = db.components().insertPublicProject(p -> p.setName("Project One")).getProjectDto();
ProjectDto project2 = db.components().insertPublicProject(p -> p.setName("Project Two")).getProjectDto();
ProjectDto project3 = db.components().insertPublicProject(p -> p.setName("Project Three")).getProjectDto();
db.components().insertPublicProject(p -> p.setName("Project Four")).getProjectDto();
ProjectDto project5 = db.components().insertPublicProject(p -> p.setKey("Project the fifth")).getProjectDto();
QProfileDto qualityProfile = db.qualityProfiles().insert();
associateProjectsWithProfile(qualityProfile, project1, project2);
ws.newRequest()
.setParam(PARAM_KEY, qualityProfile.getKee())
.setParam("selected", "all")
.setParam(TEXT_QUERY, "project t")
.execute()
.assertJson("{\n" +
" \"results\":\n" +
" [\n" +
" {\n" +
" \"key\": \"" + project3.getKey() + "\",\n" +
" \"name\": \"" + project3.getName() + "\",\n" +
" \"selected\": false\n" +
" },\n" +
" {\n" +
" \"key\": \"" + project2.getKey() + "\",\n" +
" \"name\": \"" + project2.getName() + "\",\n" +
" \"selected\": true\n" +
" },\n" +
" {\n" +
" \"key\": \"" + project5.getKey() + "\",\n" +
" \"name\": \"" + project5.getName() + "\",\n" +
" \"selected\": false\n" +
" }\n" +
" ]}\n");
}
@Test
public void return_deprecated_uuid_field() {
ProjectDto project = db.components().insertPublicProject().getProjectDto();
QProfileDto qualityProfile = db.qualityProfiles().insert();
associateProjectsWithProfile(qualityProfile, project);
ws.newRequest()
.setParam(PARAM_KEY, qualityProfile.getKee())
.setParam("selected", "all")
.execute()
.assertJson("{\"results\":\n" +
" [\n" +
" {\n" +
" \"key\": \"" + project.getKey() + "\",\n" +
" }\n" +
" ]}");
}
@Test
public void fail_on_nonexistent_profile() {
TestRequest testRequest = ws.newRequest().setParam(PARAM_KEY, "unknown");
assertThatThrownBy(testRequest::execute).isInstanceOf(NotFoundException.class);
}
@Test
public void definition() {
WebService.Action definition = ws.getDef();
assertThat(definition.key()).isEqualTo("projects");
assertThat(definition.responseExampleAsString()).isNotEmpty();
assertThat(definition.params()).extracting(Param::key).containsExactlyInAnyOrder("key", "p", "ps", "q", "selected");
Param profile = definition.param("key");
assertThat(profile).isNotNull();
assertThat(profile.deprecatedKey()).isNullOrEmpty();
assertThat(definition.param("p")).isNotNull();
assertThat(definition.param("ps")).isNotNull();
assertThat(definition.param("q")).isNotNull();
}
private void associateProjectsWithProfile(QProfileDto profile, ProjectDto... projects) {
for (ProjectDto project : projects) {
db.getDbClient().qualityProfileDao().insertProjectProfileAssociation(db.getSession(), project, profile);
}
db.commit();
}
}
| 12,086 | 36.076687 | 120 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/QProfileWsSupportIT.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.qualityprofile.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.QualityProfileTesting;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.tester.UserSessionRule;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class QProfileWsSupportIT {
@Rule
public DbTester db = DbTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final QProfileWsSupport underTest = new QProfileWsSupport(db.getDbClient(), userSession);
@Test
public void getProfile_returns_the_profile_specified_by_key() {
QProfileDto profile = db.qualityProfiles().insert();
QProfileDto loaded = underTest.getProfile(db.getSession(), QProfileReference.fromKey(profile.getKee()));
assertThat(loaded.getKee()).isEqualTo(profile.getKee());
assertThat(loaded.getLanguage()).isEqualTo(profile.getLanguage());
assertThat(loaded.getName()).isEqualTo(profile.getName());
}
@Test
public void getProfile_throws_NotFoundException_if_specified_key_does_not_exist() {
assertThatThrownBy(() -> underTest.getProfile(db.getSession(), QProfileReference.fromKey("missing")))
.isInstanceOf(NotFoundException.class)
.hasMessage("Quality Profile with key 'missing' does not exist");
}
@Test
public void getProfile_returns_the_profile_specified_by_name() {
QProfileDto profile = QualityProfileTesting.newQualityProfileDto();
db.qualityProfiles().insert(profile);
QProfileDto loaded = underTest.getProfile(db.getSession(), QProfileReference.fromName(profile.getLanguage(), profile.getName()));
assertThat(loaded.getKee()).isEqualTo(profile.getKee());
assertThat(loaded.getLanguage()).isEqualTo(profile.getLanguage());
assertThat(loaded.getName()).isEqualTo(profile.getName());
}
@Test
public void getProfile_throws_NotFoundException_if_specified_name_does_not_exist() {
QProfileDto profile = QualityProfileTesting.newQualityProfileDto();
db.qualityProfiles().insert(profile);
assertThatThrownBy(() -> underTest.getProfile(db.getSession(), QProfileReference.fromName("java", "missing")))
.isInstanceOf(NotFoundException.class)
.hasMessage("Quality Profile for language 'java' and name 'missing' does not exist");
}
@Test
public void getRule_throws_BadRequest_if_rule_is_external() {
RuleDto rule = db.rules().insert(r -> r.setIsExternal(true));
assertThatThrownBy(() -> underTest.getRule(db.getSession(), rule.getKey()))
.isInstanceOf(BadRequestException.class)
.hasMessage(format("Operation forbidden for rule '%s' imported from an external rule engine.", rule.getKey()));
}
}
| 3,838 | 39.840426 | 133 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/QProfilesWsMediumIT.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.qualityprofile.ws;
import com.google.common.collect.ImmutableSet;
import java.util.Collections;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.ActiveRuleKey;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.QualityProfileTesting;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
import org.sonar.server.qualityprofile.QProfileRules;
import org.sonar.server.qualityprofile.QProfileRulesImpl;
import org.sonar.server.qualityprofile.builtin.RuleActivator;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import org.sonar.server.rule.index.RuleIndex;
import org.sonar.server.rule.index.RuleIndexer;
import org.sonar.server.rule.index.RuleQuery;
import org.sonar.server.rule.ws.RuleQueryFactory;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.util.TypeValidations;
import org.sonar.server.ws.WsActionTester;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_LANGUAGES;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_QPROFILE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_KEY;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_RESET;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_RULE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_SEVERITY;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_TARGET_KEY;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_TARGET_SEVERITY;
public class QProfilesWsMediumIT {
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone().logIn();
@Rule
public EsTester es = EsTester.create();
@Rule
public DbTester dbTester = DbTester.create();
private final DbClient dbClient = dbTester.getDbClient();
private final DbSession dbSession = dbTester.getSession();
private final RuleIndex ruleIndex = new RuleIndex(es.client(), System2.INSTANCE);
private final RuleIndexer ruleIndexer = new RuleIndexer(es.client(), dbClient);
private final ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(dbClient, es.client());
private final TypeValidations typeValidations = new TypeValidations(emptyList());
private final QualityProfileChangeEventService qualityProfileChangeEventService = mock(QualityProfileChangeEventService.class);
private final RuleActivator ruleActivator = new RuleActivator(System2.INSTANCE, dbClient, typeValidations, userSessionRule);
private final QProfileRules qProfileRules = new QProfileRulesImpl(dbClient, ruleActivator, ruleIndex, activeRuleIndexer, qualityProfileChangeEventService);
private final QProfileWsSupport qProfileWsSupport = new QProfileWsSupport(dbClient, userSessionRule);
private final RuleQueryFactory ruleQueryFactory = new RuleQueryFactory(dbClient);
private final WsActionTester wsDeactivateRule = new WsActionTester(new DeactivateRuleAction(dbClient, qProfileRules, userSessionRule, qProfileWsSupport));
private final WsActionTester wsDeactivateRules = new WsActionTester(new DeactivateRulesAction(ruleQueryFactory, userSessionRule, qProfileRules, qProfileWsSupport, dbClient));
private final WsActionTester wsActivateRule = new WsActionTester(new ActivateRuleAction(dbClient, qProfileRules, userSessionRule, qProfileWsSupport));
private final WsActionTester wsActivateRules = new WsActionTester(new ActivateRulesAction(ruleQueryFactory, userSessionRule, qProfileRules, qProfileWsSupport, dbClient));
@Before
public void before(){
userSessionRule.logIn().setSystemAdministrator();
userSessionRule.addPermission(GlobalPermission.ADMINISTER);
userSessionRule.addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
}
@Test
public void deactivate_rule() {
QProfileDto profile = createProfile("java");
RuleDto rule = createRule(profile.getLanguage(), "toto");
createActiveRule(rule, profile);
ruleIndexer.commitAndIndex(dbSession, rule.getUuid());
activeRuleIndexer.indexAll();
// 0. Assert No Active Rule for profile
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee())).hasSize(1);
// 1. Deactivate Rule
wsDeactivateRule.newRequest().setMethod("POST")
.setParam(PARAM_KEY, profile.getKee())
.setParam(PARAM_RULE, rule.getKey().toString())
.execute();
dbSession.clearCache();
// 2. Assert ActiveRule in DAO
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee())).isEmpty();
}
@Test
public void bulk_deactivate_rule() {
QProfileDto profile = createProfile("java");
RuleDto rule0 = createRule(profile.getLanguage(), "toto1");
RuleDto rule1 = createRule(profile.getLanguage(), "toto2");
RuleDto rule2 = createRule(profile.getLanguage(), "toto3");
RuleDto rule3 = createRule(profile.getLanguage(), "toto4");
createActiveRule(rule0, profile);
createActiveRule(rule2, profile);
createActiveRule(rule3, profile);
createActiveRule(rule1, profile);
dbSession.commit();
activeRuleIndexer.indexAll();
// 0. Assert No Active Rule for profile
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee())).hasSize(4);
// 1. Deactivate Rule
wsDeactivateRules.newRequest().setMethod("POST")
.setParam(PARAM_TARGET_KEY, profile.getKee())
.execute();
dbSession.clearCache();
// 2. Assert ActiveRule in DAO
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee())).isEmpty();
}
@Test
public void bulk_deactivate_rule_not_all() {
QProfileDto profile = createProfile("java");
QProfileDto php = createProfile("php");
RuleDto rule0 = createRule(profile.getLanguage(), "toto1");
RuleDto rule1 = createRule(profile.getLanguage(), "toto2");
createActiveRule(rule0, profile);
createActiveRule(rule1, profile);
createActiveRule(rule0, php);
createActiveRule(rule1, php);
dbSession.commit();
activeRuleIndexer.indexAll();
// 0. Assert No Active Rule for profile
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee())).hasSize(2);
// 1. Deactivate Rule
wsDeactivateRules.newRequest().setMethod("POST")
.setParam(PARAM_TARGET_KEY, profile.getKee())
.execute();
dbSession.clearCache();
// 2. Assert ActiveRule in DAO
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee())).isEmpty();
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, php.getKee())).hasSize(2);
}
@Test
public void bulk_deactivate_rule_by_profile() {
QProfileDto profile = createProfile("java");
RuleDto rule0 = createRule(profile.getLanguage(), "hello");
RuleDto rule1 = createRule(profile.getLanguage(), "world");
createActiveRule(rule0, profile);
createActiveRule(rule1, profile);
dbSession.commit();
activeRuleIndexer.indexAll();
// 0. Assert No Active Rule for profile
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee())).hasSize(2);
// 1. Deactivate Rule
wsDeactivateRules.newRequest().setMethod("POST")
.setParam(PARAM_TARGET_KEY, profile.getKee())
.setParam(Param.TEXT_QUERY, "hello")
.execute();
dbSession.clearCache();
// 2. Assert ActiveRule in DAO
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee())).hasSize(1);
}
@Test
public void activate_rule() {
QProfileDto profile = createProfile("java");
RuleDto rule = createRule(profile.getLanguage(), "toto");
ruleIndexer.commitAndIndex(dbSession, rule.getUuid());
// 0. Assert No Active Rule for profile
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee())).isEmpty();
// 1. Activate Rule
wsActivateRule.newRequest().setMethod("POST")
.setParam(PARAM_KEY, profile.getKee())
.setParam(PARAM_RULE, rule.getKey().toString())
.execute();
dbSession.clearCache();
// 2. Assert ActiveRule in DAO
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee())).hasSize(1);
}
@Test
public void activate_rule_diff_languages() {
QProfileDto profile = createProfile("java");
RuleDto rule = createRule("php", "toto");
ruleIndexer.commitAndIndex(dbSession, rule.getUuid());
// 0. Assert No Active Rule for profile
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee())).isEmpty();
try {
// 1. Activate Rule
wsActivateRule.newRequest().setMethod("POST")
.setParam(PARAM_KEY, profile.getKee())
.setParam(PARAM_RULE, rule.getKey().toString())
.execute();
dbSession.clearCache();
fail();
} catch (BadRequestException e) {
assertThat(e.getMessage()).isEqualTo("php rule blah:toto cannot be activated on java profile Pjava");
}
}
@Test
public void activate_rule_override_severity() {
QProfileDto profile = createProfile("java");
RuleDto rule = createRule(profile.getLanguage(), "toto");
ruleIndexer.commitAndIndex(dbSession, rule.getUuid());
// 0. Assert No Active Rule for profile
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee())).isEmpty();
// 1. Activate Rule
wsActivateRule.newRequest().setMethod("POST")
.setParam(PARAM_KEY, profile.getKee())
.setParam(PARAM_RULE, rule.getKey().toString())
.setParam(PARAM_SEVERITY, "MINOR")
.execute();
dbSession.clearCache();
// 2. Assert ActiveRule in DAO
ActiveRuleKey activeRuleKey = ActiveRuleKey.of(profile, rule.getKey());
Optional<ActiveRuleDto> activeRuleDto = dbClient.activeRuleDao().selectByKey(dbSession, activeRuleKey);
assertThat(activeRuleDto).isPresent();
assertThat(activeRuleDto.get().getSeverityString()).isEqualTo(Severity.MINOR);
}
@Test
public void bulk_activate_rule() {
QProfileDto profile = createProfile("java");
createRule(profile.getLanguage(), "toto");
createRule(profile.getLanguage(), "tata");
createRule(profile.getLanguage(), "hello");
createRule(profile.getLanguage(), "world");
dbSession.commit();
// 0. Assert No Active Rule for profile
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee())).isEmpty();
// 1. Activate Rule
wsActivateRules.newRequest().setMethod("POST")
.setParam(PARAM_TARGET_KEY, profile.getKee())
.setParam(PARAM_LANGUAGES, "java")
.execute()
.assertJson(getClass(), "bulk_activate_rule.json");
dbSession.clearCache();
// 2. Assert ActiveRule in DAO
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee())).hasSize(4);
}
@Test
public void bulk_activate_rule_not_all() {
QProfileDto java = createProfile("java");
QProfileDto php = createProfile("php");
createRule(java.getLanguage(), "toto");
createRule(java.getLanguage(), "tata");
createRule(php.getLanguage(), "hello");
createRule(php.getLanguage(), "world");
dbSession.commit();
// 0. Assert No Active Rule for profile
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, php.getKee())).isEmpty();
// 1. Activate Rule
wsActivateRules.newRequest().setMethod("POST")
.setParam(PARAM_TARGET_KEY, php.getKee())
.setParam(PARAM_LANGUAGES, "php")
.execute()
.assertJson(getClass(), "bulk_activate_rule_not_all.json");
dbSession.clearCache();
// 2. Assert ActiveRule in DAO
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, php.getKee())).hasSize(2);
}
@Test
public void bulk_activate_rule_by_query() {
QProfileDto profile = createProfile("java");
createRule(profile.getLanguage(), "toto");
createRule(profile.getLanguage(), "tata");
createRule(profile.getLanguage(), "hello");
createRule(profile.getLanguage(), "world");
dbSession.commit();
// 0. Assert No Active Rule for profile
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee())).isEmpty();
// 1. Activate Rule with query returning 0 hits
wsActivateRules.newRequest().setMethod("POST")
.setParam(PARAM_TARGET_KEY, profile.getKee())
.setParam(Param.TEXT_QUERY, "php")
.execute();
dbSession.clearCache();
// 2. Assert ActiveRule in DAO
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee())).isEmpty();
// 1. Activate Rule with query returning 1 hits
wsActivateRules.newRequest().setMethod("POST")
.setParam(PARAM_TARGET_KEY, profile.getKee())
.setParam(Param.TEXT_QUERY, "world")
.execute();
dbSession.commit();
// 2. Assert ActiveRule in DAO
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee())).hasSize(1);
}
@Test
public void bulk_activate_rule_by_query_with_severity() {
QProfileDto profile = createProfile("java");
RuleDto rule0 = createRule(profile.getLanguage(), "toto");
RuleDto rule1 = createRule(profile.getLanguage(), "tata");
dbSession.commit();
// 0. Assert No Active Rule for profile
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, profile.getKee())).isEmpty();
// 2. Assert ActiveRule with BLOCKER severity
assertThat(ruleIndex.search(
new RuleQuery().setSeverities(ImmutableSet.of("BLOCKER")),
new SearchOptions()).getUuids()).hasSize(2);
// 1. Activate Rule with query returning 2 hits
wsActivateRules.newRequest().setMethod("POST")
.setParam(PARAM_TARGET_KEY, profile.getKee())
.setParam(PARAM_TARGET_SEVERITY, "MINOR")
.execute();
dbSession.commit();
// 2. Assert ActiveRule with MINOR severity
assertThat(dbClient.activeRuleDao().selectByOrgRuleUuid(dbSession, rule0.getUuid()).get(0).getSeverityString()).isEqualTo("MINOR");
assertThat(ruleIndex.searchAll(new RuleQuery()
.setQProfile(profile)
.setKey(rule0.getKey().toString())
.setActiveSeverities(Collections.singleton("MINOR"))
.setActivation(true))).toIterable().hasSize(1);
}
@Test
public void does_not_return_warnings_when_bulk_activate_on_profile_and_rules_exist_on_another_language_than_profile() {
QProfileDto javaProfile = createProfile("java");
createRule(javaProfile.getLanguage(), "toto");
createRule(javaProfile.getLanguage(), "tata");
QProfileDto phpProfile = createProfile("php");
createRule(phpProfile.getLanguage(), "hello");
createRule(phpProfile.getLanguage(), "world");
dbSession.commit();
// 1. Activate Rule
wsActivateRules.newRequest().setMethod("POST")
.setParam(PARAM_TARGET_KEY, javaProfile.getKee())
.setParam(PARAM_QPROFILE, javaProfile.getKee())
.setParam("activation", "false")
.execute()
.assertJson(getClass(), "does_not_return_warnings_when_bulk_activate_on_profile_and_rules_exist_on_another_language_than_profile.json");
dbSession.clearCache();
// 2. Assert ActiveRule in DAO
assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, javaProfile.getKee())).hasSize(2);
}
@Test
public void reset() {
QProfileDto profile = QualityProfileTesting.newQualityProfileDto().setLanguage("java");
QProfileDto childProfile = QualityProfileTesting.newQualityProfileDto().setParentKee(profile.getKee()).setLanguage("java");
dbClient.qualityProfileDao().insert(dbSession, profile, childProfile);
RuleDto rule = createRule(profile.getLanguage(), "rule");
ActiveRuleDto active1 = ActiveRuleDto.createFor(profile, rule)
.setSeverity(rule.getSeverityString());
ActiveRuleDto active2 = ActiveRuleDto.createFor(childProfile, rule)
.setSeverity("MINOR");
dbClient.activeRuleDao().insert(dbSession, active1);
dbClient.activeRuleDao().insert(dbSession, active2);
dbSession.commit();
activeRuleIndexer.indexAll();
// 0. assert rule child rule is minor
Optional<ActiveRuleDto> activeRuleDto = dbClient.activeRuleDao().selectByKey(dbSession, active2.getKey());
assertThat(activeRuleDto).isPresent();
assertThat(activeRuleDto.get().getSeverityString()).isEqualTo(Severity.MINOR);
// 1. reset child rule
wsActivateRule.newRequest().setMethod("POST")
.setParam(PARAM_KEY, childProfile.getKee())
.setParam(PARAM_RULE, rule.getKey().toString())
.setParam(PARAM_RESET, "true")
.execute();
dbSession.clearCache();
// 2. assert rule child rule is NOT minor
activeRuleDto = dbClient.activeRuleDao().selectByKey(dbSession, active2.getKey());
assertThat(activeRuleDto).isPresent();
assertThat(activeRuleDto.get().getSeverityString()).isNotEqualTo(Severity.MINOR);
}
private QProfileDto createProfile(String lang) {
QProfileDto profile = QualityProfileTesting.newQualityProfileDto().setName("P" + lang).setLanguage(lang);
dbClient.qualityProfileDao().insert(dbSession, profile);
return profile;
}
private RuleDto createRule(String lang, String id) {
RuleDto rule = RuleTesting.newRule(RuleKey.of("blah", id))
.setLanguage(lang)
.setSeverity(Severity.BLOCKER)
.setStatus(RuleStatus.READY);
dbClient.ruleDao().insert(dbSession, rule);
ruleIndexer.commitAndIndex(dbSession, rule.getUuid());
return rule;
}
private ActiveRuleDto createActiveRule(RuleDto rule, QProfileDto profile) {
ActiveRuleDto activeRule = ActiveRuleDto.createFor(profile, rule)
.setSeverity(rule.getSeverityString());
dbClient.activeRuleDao().insert(dbSession, activeRule);
return activeRule;
}
}
| 19,552 | 40.869379 | 176 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/RemoveGroupActionIT.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.qualityprofile.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbTester;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_GROUP;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE;
public class RemoveGroupActionIT {
private static final String XOO = "xoo";
private static final Languages LANGUAGES = LanguageTesting.newLanguages(XOO);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create();
private final QProfileWsSupport wsSupport = new QProfileWsSupport(db.getDbClient(), userSession);
private final WsActionTester ws = new WsActionTester(new RemoveGroupAction(db.getDbClient(), wsSupport, LANGUAGES));
@Test
public void test_definition() {
WebService.Action def = ws.getDef();
assertThat(def.key()).isEqualTo("remove_group");
assertThat(def.isPost()).isTrue();
assertThat(def.isInternal()).isTrue();
assertThat(def.params()).extracting(WebService.Param::key).containsExactlyInAnyOrder("qualityProfile", "language", "group");
}
@Test
public void remove_group() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group = db.users().insertGroup();
db.qualityProfiles().addGroupPermission(profile, group);
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
TestResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, group.getName())
.execute();
assertThat(response.getStatus()).isEqualTo(204);
assertThat(db.getDbClient().qProfileEditGroupsDao().exists(db.getSession(), profile, group)).isFalse();
}
@Test
public void does_nothing_when_group_cannot_edit_profile() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group = db.users().insertGroup();
assertThat(db.getDbClient().qProfileEditGroupsDao().exists(db.getSession(), profile, group)).isFalse();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, group.getName())
.execute();
assertThat(db.getDbClient().qProfileEditGroupsDao().exists(db.getSession(), profile, group)).isFalse();
}
@Test
public void qp_administers_can_remove_group() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group = db.users().insertGroup();
db.qualityProfiles().addGroupPermission(profile, group);
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, group.getName())
.execute();
assertThat(db.getDbClient().qProfileEditGroupsDao().exists(db.getSession(), profile, group)).isFalse();
}
@Test
public void qp_editors_can_remove_group() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group = db.users().insertGroup();
db.qualityProfiles().addGroupPermission(profile, group);
UserDto userAllowedToEditProfile = db.users().insertUser();
db.qualityProfiles().addUserPermission(profile, userAllowedToEditProfile);
userSession.logIn(userAllowedToEditProfile);
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, group.getName())
.execute();
assertThat(db.getDbClient().qProfileEditGroupsDao().exists(db.getSession(), profile, group)).isFalse();
}
@Test
public void fail_when_group_does_not_exist() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, "unknown")
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage("No group with name 'unknown'");
}
@Test
public void fail_when_qprofile_does_not_exist() {
GroupDto group = db.users().insertGroup();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, "unknown")
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, group.getName())
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist");
}
@Test
public void fail_when_wrong_language() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage("unknown"));
GroupDto group = db.users().insertGroup();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, group.getName())
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage(format("Quality Profile for language 'xoo' and name '%s' does not exist", profile.getName()));
}
@Test
public void fail_when_qp_is_built_in() {
GroupDto group = db.users().insertGroup();
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO).setIsBuiltIn(true));
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, group.getName())
.execute();
})
.isInstanceOf(BadRequestException.class)
.hasMessage(String.format("Operation forbidden for built-in Quality Profile '%s' with language 'xoo'", profile.getName()));
}
@Test
public void fail_when_not_enough_permission() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group = db.users().insertGroup();
userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_GROUP, group.getName())
.execute();
})
.isInstanceOf(ForbiddenException.class);
}
}
| 8,621 | 38.550459 | 129 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/RemoveProjectActionIT.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.qualityprofile.ws;
import java.net.HttpURLConnection;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
import org.sonar.api.resources.Languages;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ResourceTypesRule;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.verify;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
public class RemoveProjectActionIT {
private static final String LANGUAGE_1 = "xoo";
private static final String LANGUAGE_2 = "foo";
@Rule
public DbTester db = DbTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final DbClient dbClient = db.getDbClient();
private final Languages languages = LanguageTesting.newLanguages(LANGUAGE_1, LANGUAGE_2);
private final QProfileWsSupport wsSupport = new QProfileWsSupport(dbClient, userSession);
private final QualityProfileChangeEventService qualityProfileChangeEventService = Mockito.mock(QualityProfileChangeEventService.class);
private final RemoveProjectAction underTest = new RemoveProjectAction(dbClient, userSession, languages,
new ComponentFinder(dbClient, new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT)), wsSupport, qualityProfileChangeEventService);
private final WsActionTester ws = new WsActionTester(underTest);
@Test
public void definition() {
WebService.Action definition = ws.getDef();
assertThat(definition.since()).isEqualTo("5.2");
assertThat(definition.isPost()).isTrue();
assertThat(definition.key()).isEqualTo("remove_project");
assertThat(definition.params()).extracting(WebService.Param::key).containsOnly("qualityProfile", "project", "language");
WebService.Param languageParam = definition.param("language");
assertThat(languageParam.possibleValues()).containsOnly(LANGUAGE_1, LANGUAGE_2);
assertThat(languageParam.exampleValue()).isNull();
assertThat(languageParam.deprecatedSince()).isNullOrEmpty();
WebService.Param profileName = definition.param("qualityProfile");
assertThat(profileName.deprecatedSince()).isNullOrEmpty();
}
@Test
public void remove_profile_from_project() {
logInAsProfileAdmin();
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
QProfileDto profileLang1 = db.qualityProfiles().insert(p -> p.setLanguage(LANGUAGE_1));
QProfileDto profileLang2 = db.qualityProfiles().insert(p -> p.setLanguage(LANGUAGE_2));
db.qualityProfiles().associateWithProject(project, profileLang1);
db.qualityProfiles().associateWithProject(project, profileLang2);
TestResponse response = call(project, profileLang1);
assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
assertProjectIsNotAssociatedToProfile(project, profileLang1);
assertProjectIsAssociatedToProfile(project, profileLang2);
verify(qualityProfileChangeEventService).publishRuleActivationToSonarLintClients(project, null, profileLang1);
}
@Test
public void removal_does_not_fail_if_profile_is_not_associated_to_project() {
logInAsProfileAdmin();
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
QProfileDto profile = db.qualityProfiles().insert(qp -> qp.setLanguage("xoo"));
TestResponse response = call(project, profile);
assertThat(response.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
assertProjectIsNotAssociatedToProfile(project, profile);
verify(qualityProfileChangeEventService).publishRuleActivationToSonarLintClients(project, null, profile);
}
@Test
public void project_administrator_can_remove_profile() {
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
QProfileDto profile = db.qualityProfiles().insert(qp -> qp.setLanguage("xoo"));
db.qualityProfiles().associateWithProject(project, profile);
userSession.logIn(db.users().insertUser()).addProjectPermission(UserRole.ADMIN, project);
call(project, profile);
assertProjectIsNotAssociatedToProfile(project, profile);
verify(qualityProfileChangeEventService).publishRuleActivationToSonarLintClients(project, null, profile);
}
@Test
public void as_qprofile_editor_and_global_admin() {
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(LANGUAGE_1));
db.qualityProfiles().associateWithProject(project, profile);
UserDto user = db.users().insertUser();
db.qualityProfiles().addUserPermission(profile, user);
userSession.logIn(user).addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
call(project, profile);
assertProjectIsNotAssociatedToProfile(project, profile);
verify(qualityProfileChangeEventService).publishRuleActivationToSonarLintClients(project, null, profile);
}
@Test
public void as_qprofile_editor_fail_if_not_project_nor_global_admin() {
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(LANGUAGE_1));
db.qualityProfiles().associateWithProject(project, profile);
UserDto user = db.users().insertUser();
db.qualityProfiles().addUserPermission(profile, user);
userSession.logIn(user);
assertThatThrownBy(() -> call(project, profile))
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void fail_if_not_enough_permissions() {
userSession.logIn(db.users().insertUser());
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
QProfileDto profile = db.qualityProfiles().insert(qp -> qp.setLanguage("xoo"));
assertThatThrownBy(() -> call(project, profile))
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void fail_if_not_logged_in() {
userSession.anonymous();
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
QProfileDto profile = db.qualityProfiles().insert();
assertThatThrownBy(() -> call(project, profile))
.isInstanceOf(UnauthorizedException.class)
.hasMessage("Authentication is required");
}
@Test
public void fail_if_project_does_not_exist() {
logInAsProfileAdmin();
QProfileDto profile = db.qualityProfiles().insert();
assertThatThrownBy(() -> {
ws.newRequest()
.setParam("project", "unknown")
.setParam("profileKey", profile.getKee())
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Project 'unknown' not found");
}
@Test
public void fail_if_profile_does_not_exist() {
logInAsProfileAdmin();
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
assertThatThrownBy(() -> {
ws.newRequest()
.setParam("project", project.getKey())
.setParam("language", "xoo")
.setParam("qualityProfile", "unknown")
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist");
}
private void assertProjectIsAssociatedToProfile(ProjectDto project, QProfileDto profile) {
QProfileDto loaded = dbClient.qualityProfileDao().selectAssociatedToProjectAndLanguage(db.getSession(), project, profile.getLanguage());
assertThat(loaded.getKee()).isEqualTo(profile.getKee());
}
private void assertProjectIsNotAssociatedToProfile(ProjectDto project, QProfileDto profile) {
QProfileDto loaded = dbClient.qualityProfileDao().selectAssociatedToProjectAndLanguage(db.getSession(), project, profile.getLanguage());
assertThat(loaded == null || !loaded.getKee().equals(profile.getKee())).isTrue();
}
private void logInAsProfileAdmin() {
userSession.logIn(db.users().insertUser()).addPermission(ADMINISTER_QUALITY_PROFILES);
}
private TestResponse call(ProjectDto project, QProfileDto qualityProfile) {
TestRequest request = ws.newRequest()
.setParam("project", project.getKey())
.setParam("language", qualityProfile.getLanguage())
.setParam("qualityProfile", qualityProfile.getName());
return request.execute();
}
}
| 10,179 | 41.773109 | 143 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/RemoveUserActionIT.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.qualityprofile.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbTester;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LOGIN;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE;
public class RemoveUserActionIT {
private static final String XOO = "xoo";
private static final Languages LANGUAGES = LanguageTesting.newLanguages(XOO);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create();
private final QProfileWsSupport wsSupport = new QProfileWsSupport(db.getDbClient(), userSession);
private final WsActionTester ws = new WsActionTester(new RemoveUserAction(db.getDbClient(), wsSupport, LANGUAGES));
@Test
public void test_definition() {
WebService.Action def = ws.getDef();
assertThat(def.key()).isEqualTo("remove_user");
assertThat(def.isPost()).isTrue();
assertThat(def.isInternal()).isTrue();
assertThat(def.params()).extracting(WebService.Param::key).containsExactlyInAnyOrder("qualityProfile", "language", "login");
}
@Test
public void remove_user() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user = db.users().insertUser();
db.qualityProfiles().addUserPermission(profile, user);
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
TestResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
assertThat(response.getStatus()).isEqualTo(204);
assertThat(db.getDbClient().qProfileEditUsersDao().exists(db.getSession(), profile, user)).isFalse();
}
@Test
public void does_nothing_when_user_cannot_edit_profile() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user = db.users().insertUser();
assertThat(db.getDbClient().qProfileEditUsersDao().exists(db.getSession(), profile, user)).isFalse();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
assertThat(db.getDbClient().qProfileEditUsersDao().exists(db.getSession(), profile, user)).isFalse();
}
@Test
public void qp_administers_can_remove_user() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user = db.users().insertUser();
db.qualityProfiles().addUserPermission(profile, user);
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
assertThat(db.getDbClient().qProfileEditUsersDao().exists(db.getSession(), profile, user)).isFalse();
}
@Test
public void qp_editors_can_remove_user() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user = db.users().insertUser();
db.qualityProfiles().addUserPermission(profile, user);
UserDto userAllowedToEditProfile = db.users().insertUser();
db.qualityProfiles().addUserPermission(profile, userAllowedToEditProfile);
userSession.logIn(userAllowedToEditProfile);
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
assertThat(db.getDbClient().qProfileEditUsersDao().exists(db.getSession(), profile, user)).isFalse();
}
@Test
public void uses_global_permission() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user = db.users().insertUser();
db.qualityProfiles().addUserPermission(profile, user);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
assertThat(db.getDbClient().qProfileEditUsersDao().exists(db.getSession(), profile, user)).isFalse();
}
@Test
public void fail_when_user_does_not_exist() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_LOGIN, "unknown")
.execute())
.isInstanceOf(NotFoundException.class)
.hasMessageContaining("User with login 'unknown' is not found'");
}
@Test
public void fail_when_qprofile_does_not_exist() {
UserDto user = db.users().insertUser();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, "unknown")
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist");
}
@Test
public void fail_when_wrong_language() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage("unknown"));
UserDto user = db.users().insertUser();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage(format("Quality Profile for language 'xoo' and name '%s' does not exist", profile.getName()));
}
@Test
public void fail_when_qp_is_built_in() {
UserDto user = db.users().insertUser();
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO).setIsBuiltIn(true));
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
})
.isInstanceOf(BadRequestException.class)
.hasMessage(String.format("Operation forbidden for built-in Quality Profile '%s' with language 'xoo'", profile.getName()));
}
@Test
public void fail_when_not_enough_permission() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user = db.users().insertUser();
userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
})
.isInstanceOf(ForbiddenException.class);
}
}
| 9,219 | 38.91342 | 129 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/RenameActionIT.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.qualityprofile.ws;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.QualityProfileTesting;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import static java.util.Optional.ofNullable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
import static org.sonar.db.permission.GlobalPermission.SCAN;
public class RenameActionIT {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private DbClient dbClient = db.getDbClient();
private WsActionTester ws;
private String xoo1Key = "xoo1";
private String xoo2Key = "xoo2";
@Before
public void setUp() {
QProfileWsSupport wsSupport = new QProfileWsSupport(dbClient, userSession);
RenameAction underTest = new RenameAction(dbClient, userSession, wsSupport);
ws = new WsActionTester(underTest);
createProfiles();
}
@Test
public void rename() {
logInAsQProfileAdministrator();
String qualityProfileKey = createNewValidQualityProfileKey();
call(qualityProfileKey, "the new name");
QProfileDto reloaded = db.getDbClient().qualityProfileDao().selectByUuid(db.getSession(), qualityProfileKey);
assertThat(reloaded.getName()).isEqualTo("the new name");
}
@Test
public void fail_renaming_if_name_already_exists() {
logInAsQProfileAdministrator();
QProfileDto qualityProfile1 = QualityProfileTesting.newQualityProfileDto()
.setLanguage("xoo")
.setName("Old, valid name");
db.qualityProfiles().insert(qualityProfile1);
String qualityProfileKey1 = qualityProfile1.getKee();
QProfileDto qualityProfile2 = QualityProfileTesting.newQualityProfileDto()
.setLanguage("xoo")
.setName("Invalid, duplicated name");
db.qualityProfiles().insert(qualityProfile2);
String qualityProfileKey2 = qualityProfile2.getKee();
assertThatThrownBy(() -> {
call(qualityProfileKey1, "Invalid, duplicated name");
})
.isInstanceOf(BadRequestException.class)
.hasMessage("Quality profile already exists: Invalid, duplicated name");
}
@Test
public void as_qprofile_editor() {
QProfileDto qualityProfile = db.qualityProfiles().insert();
UserDto user = db.users().insertUser();
db.qualityProfiles().addUserPermission(qualityProfile, user);
userSession.logIn(user);
call(qualityProfile.getKee(), "the new name");
QProfileDto reloaded = db.getDbClient().qualityProfileDao().selectByUuid(db.getSession(), qualityProfile.getKee());
assertThat(reloaded.getName()).isEqualTo("the new name");
}
@Test
public void fail_if_parameter_profile_is_missing() {
logInAsQProfileAdministrator();
assertThatThrownBy(() -> {
call(null, "Other Sonar Way");
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The 'key' parameter is missing");
}
@Test
public void fail_if_parameter_name_is_missing() {
logInAsQProfileAdministrator();
assertThatThrownBy(() -> {
call("sonar-way-xoo1-13245", null);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The 'name' parameter is missing");
}
@Test
public void fail_if_not_profile_administrator() {
userSession.logIn(db.users().insertUser())
.addPermission(SCAN);
QProfileDto qualityProfile = QualityProfileTesting.newQualityProfileDto();
db.qualityProfiles().insert(qualityProfile);
String qualityProfileKey = qualityProfile.getKee();
assertThatThrownBy(() -> {
call(qualityProfileKey, "Hey look I am not quality profile admin!");
})
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void fail_if_not_logged_in() {
assertThatThrownBy(() -> {
call("sonar-way-xoo1-13245", "Not logged in");
})
.isInstanceOf(UnauthorizedException.class)
.hasMessage("Authentication is required");
}
@Test
public void fail_if_profile_does_not_exist() {
logInAsQProfileAdministrator();
assertThatThrownBy(() -> {
call("polop", "Uh oh, I don't know this profile");
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Quality Profile with key 'polop' does not exist");
}
@Test
public void fail_if_profile_is_built_in() {
logInAsQProfileAdministrator();
String qualityProfileKey = db.qualityProfiles().insert(p -> p.setIsBuiltIn(true)).getKee();
assertThatThrownBy(() -> {
call(qualityProfileKey, "the new name");
})
.isInstanceOf(BadRequestException.class);
}
@Test
public void fail_if_blank_renaming() {
String qualityProfileKey = createNewValidQualityProfileKey();
assertThatThrownBy(() -> {
call(qualityProfileKey, " ");
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The 'name' parameter is missing");
}
@Test
public void fail_renaming_if_profile_not_found() {
logInAsQProfileAdministrator();
assertThatThrownBy(() -> {
call("unknown", "the new name");
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Quality Profile with key 'unknown' does not exist");
}
@Test
public void definition() {
WebService.Action definition = ws.getDef();
assertThat(definition.key()).isEqualTo("rename");
assertThat(definition.isPost()).isTrue();
assertThat(definition.params()).extracting(Param::key).containsExactlyInAnyOrder("key", "name");
Param profile = definition.param("key");
assertThat(profile.deprecatedKey()).isNullOrEmpty();
}
private String createNewValidQualityProfileKey() {
QProfileDto qualityProfile = QualityProfileTesting.newQualityProfileDto();
db.qualityProfiles().insert(qualityProfile);
return qualityProfile.getKee();
}
private void createProfiles() {
db.qualityProfiles().insert(p -> p.setKee("sonar-way-xoo1-12345").setLanguage(xoo1Key).setName("Sonar way"));
QProfileDto parentXoo2 = db.qualityProfiles().insert(p -> p.setKee("sonar-way-xoo2-23456").setLanguage(xoo2Key).setName("Sonar way"));
db.qualityProfiles().insert(p -> p.setKee("my-sonar-way-xoo2-34567").setLanguage(xoo2Key).setName("My Sonar way").setParentKee(parentXoo2.getKee()));
}
private void logInAsQProfileAdministrator() {
userSession.logIn(db.users().insertUser()).addPermission(ADMINISTER_QUALITY_PROFILES);
}
private void call(@Nullable String key, @Nullable String name) {
TestRequest request = ws.newRequest()
.setMethod("POST");
ofNullable(key).ifPresent(k -> request.setParam("key", k));
ofNullable(name).ifPresent(n -> request.setParam("name", n));
request.execute();
}
}
| 8,348 | 32.665323 | 153 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/RestoreActionIT.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.qualityprofile.ws;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import javax.annotation.Nullable;
import org.apache.commons.io.IOUtils;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.qualityprofile.BulkChangeResult;
import org.sonar.server.qualityprofile.QProfileBackuper;
import org.sonar.server.qualityprofile.QProfileRestoreSummary;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import org.sonar.test.JsonAssert;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
public class RestoreActionIT {
private static final String A_LANGUAGE = "xoo";
@Rule
public DbTester db = DbTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final TestBackuper backuper = new TestBackuper();
private final Languages languages = LanguageTesting.newLanguages(A_LANGUAGE);
private final WsActionTester tester = new WsActionTester(new RestoreAction(db.getDbClient(), backuper, languages, userSession));
@Test
public void test_definition() {
WebService.Action definition = tester.getDef();
assertThat(definition.key()).isEqualTo("restore");
assertThat(definition.isPost()).isTrue();
assertThat(definition.responseExampleAsString()).isNull();
assertThat(definition.description()).isNotEmpty();
// parameters
assertThat(definition.params()).hasSize(1);
WebService.Param backupParam = definition.param("backup");
assertThat(backupParam.isRequired()).isTrue();
assertThat(backupParam.since()).isNull();
}
@Test
public void profile_is_restored_with_the_name_provided_in_backup() {
logInAsQProfileAdministrator();
TestResponse response = restore("<backup/>");
assertThat(backuper.restoredBackup).isEqualTo("<backup/>");
assertThat(backuper.restoredSummary.profile().getName()).isEqualTo("the-name-in-backup");
JsonAssert.assertJson(response.getInput()).isSimilarTo("{" +
" \"profile\": {" +
" \"name\": \"the-name-in-backup\"," +
" \"language\": \"xoo\"," +
" \"languageName\": \"Xoo\"," +
" \"isDefault\": false," +
" \"isInherited\": false" +
" }," +
" \"ruleSuccesses\": 0," +
" \"ruleFailures\": 0" +
"}");
}
@Test
public void throw_IAE_if_backup_is_missing() {
logInAsQProfileAdministrator();
assertThatThrownBy(() -> {
tester.newRequest()
.setMethod("POST")
.execute();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("A backup file must be provided");
}
@Test
public void throw_ForbiddenException_if_not_profile_administrator() {
userSession.logIn();
assertThatThrownBy(() -> {
restore("<backup/>");
})
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void throw_UnauthorizedException_if_not_logged_in() {
userSession.anonymous();
assertThatThrownBy(() -> {
restore("<backup/>");
})
.isInstanceOf(UnauthorizedException.class)
.hasMessage("Authentication is required");
}
private void logInAsQProfileAdministrator() {
userSession
.logIn()
.addPermission(ADMINISTER_QUALITY_PROFILES);
}
private TestResponse restore(String backupContent) {
TestRequest request = tester.newRequest()
.setMethod("POST")
.setParam("backup", backupContent);
return request.execute();
}
private static class TestBackuper implements QProfileBackuper {
private String restoredBackup;
private QProfileRestoreSummary restoredSummary;
@Override
public void backup(DbSession dbSession, QProfileDto profile, Writer backupWriter) {
throw new UnsupportedOperationException();
}
@Override
public QProfileRestoreSummary restore(DbSession dbSession, Reader backup, @Nullable String overriddenProfileName) {
if (restoredSummary != null) {
throw new IllegalStateException("Already restored");
}
try {
restoredBackup = IOUtils.toString(backup);
} catch (IOException e) {
throw new IllegalStateException(e);
}
QProfileDto profile = new QProfileDto()
.setKee("P1")
.setRulesProfileUuid("rp-P1")
.setLanguage("xoo")
.setName(overriddenProfileName != null ? overriddenProfileName : "the-name-in-backup");
restoredSummary = new QProfileRestoreSummary(profile, new BulkChangeResult());
return restoredSummary;
}
@Override
public QProfileRestoreSummary restore(DbSession dbSession, Reader backup, QProfileDto profile) {
throw new UnsupportedOperationException();
}
@Override
public QProfileRestoreSummary copy(DbSession dbSession, QProfileDto from, QProfileDto to) {
throw new UnsupportedOperationException();
}
}
}
| 6,358 | 33.005348 | 130 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/SearchActionIT.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.qualityprofile.ws;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.QualityProfileDbTester;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.MediaTypes;
import org.sonarqube.ws.Qualityprofiles.SearchWsResponse;
import org.sonarqube.ws.Qualityprofiles.SearchWsResponse.QualityProfile;
import static java.util.stream.IntStream.range;
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.sonar.api.rule.RuleStatus.DEPRECATED;
import static org.sonar.api.utils.DateUtils.parseDateTime;
import static org.sonar.db.qualityprofile.QualityProfileTesting.newQualityProfileDto;
import static org.sonar.server.language.LanguageTesting.newLanguage;
import static org.sonar.test.JsonAssert.assertJson;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_DEFAULTS;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_PROJECT;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE;
public class SearchActionIT {
private static final Language XOO1 = newLanguage("xoo1");
private static final Language XOO2 = newLanguage("xoo2");
private static final Languages LANGUAGES = new Languages(XOO1, XOO2);
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final QualityProfileDbTester qualityProfileDb = db.qualityProfiles();
private final DbClient dbClient = db.getDbClient();
private SearchAction underTest = new SearchAction(userSession, LANGUAGES, dbClient, new ComponentFinder(dbClient, null));
private WsActionTester ws = new WsActionTester(underTest);
@Test
public void no_profile() {
SearchWsResponse result = call(ws.newRequest());
assertThat(result.getProfilesList()).isEmpty();
}
@Test
public void empty_when_no_language_installed() {
WsActionTester ws = new WsActionTester(new SearchAction(userSession, new Languages(), dbClient, new ComponentFinder(dbClient, null)));
db.qualityProfiles().insert();
SearchWsResponse result = call(ws.newRequest());
assertThat(result.getProfilesList()).isEmpty();
}
@Test
public void filter_on_default_profile() {
QProfileDto defaultProfile1 = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
QProfileDto defaultProfile2 = db.qualityProfiles().insert(p -> p.setLanguage(XOO2.getKey()));
QProfileDto nonDefaultProfile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
db.qualityProfiles().setAsDefault(defaultProfile1, defaultProfile2);
SearchWsResponse result = call(ws.newRequest().setParam(PARAM_DEFAULTS, "true"));
assertThat(result.getProfilesList()).extracting(QualityProfile::getKey)
.containsExactlyInAnyOrder(defaultProfile1.getKee(), defaultProfile2.getKee())
.doesNotContain(nonDefaultProfile.getKee());
}
@Test
public void does_not_filter_when_defaults_is_false() {
QProfileDto defaultProfile1 = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
QProfileDto defaultProfile2 = db.qualityProfiles().insert(p -> p.setLanguage(XOO2.getKey()));
QProfileDto nonDefaultProfile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
db.qualityProfiles().setAsDefault(defaultProfile1, defaultProfile2);
SearchWsResponse result = call(ws.newRequest().setParam(PARAM_DEFAULTS, "false"));
assertThat(result.getProfilesList()).extracting(QualityProfile::getKey)
.containsExactlyInAnyOrder(defaultProfile1.getKee(), defaultProfile2.getKee(), nonDefaultProfile.getKee());
}
@Test
public void filter_on_language() {
QProfileDto profile1OnXoo1 = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
QProfileDto profile2OnXoo1 = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
QProfileDto profileOnXoo2 = db.qualityProfiles().insert(p -> p.setLanguage(XOO2.getKey()));
SearchWsResponse result = call(ws.newRequest().setParam(PARAM_LANGUAGE, XOO1.getKey()));
assertThat(result.getProfilesList()).extracting(QualityProfile::getKey)
.containsExactlyInAnyOrder(profile1OnXoo1.getKee(), profile2OnXoo1.getKee())
.doesNotContain(profileOnXoo2.getKee());
}
@Test
public void ignore_profiles_on_unknown_language() {
QProfileDto profile1OnXoo1 = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
QProfileDto profile2OnXoo1 = db.qualityProfiles().insert(p -> p.setLanguage(XOO2.getKey()));
QProfileDto profileOnUnknownLanguage = db.qualityProfiles().insert(p -> p.setLanguage("unknown"));
SearchWsResponse result = call(ws.newRequest());
assertThat(result.getProfilesList()).extracting(QualityProfile::getKey)
.containsExactlyInAnyOrder(profile1OnXoo1.getKee(), profile2OnXoo1.getKee())
.doesNotContain(profileOnUnknownLanguage.getKee());
}
@Test
public void filter_on_profile_name() {
QProfileDto sonarWayOnXoo1 = db.qualityProfiles().insert(p -> p.setName("Sonar way").setLanguage(XOO1.getKey()));
QProfileDto sonarWayOnXoo2 = db.qualityProfiles().insert(p -> p.setName("Sonar way").setLanguage(XOO1.getKey()));
QProfileDto sonarWayInCamelCase = db.qualityProfiles().insert(p -> p.setName("Sonar Way").setLanguage(XOO2.getKey()));
QProfileDto anotherProfile = db.qualityProfiles().insert(p -> p.setName("Another").setLanguage(XOO2.getKey()));
SearchWsResponse result = call(ws.newRequest().setParam(PARAM_QUALITY_PROFILE, "Sonar way"));
assertThat(result.getProfilesList()).extracting(QualityProfile::getKey)
.containsExactlyInAnyOrder(sonarWayOnXoo1.getKee(), sonarWayOnXoo2.getKee())
.doesNotContain(anotherProfile.getKee(), sonarWayInCamelCase.getKee());
}
@Test
public void filter_on_defaults_and_name() {
QProfileDto sonarWayOnXoo1 = db.qualityProfiles().insert(p -> p.setName("Sonar way").setLanguage(XOO1.getKey()));
QProfileDto sonarWayOnXoo2 = db.qualityProfiles().insert(p -> p.setName("Sonar way").setLanguage(XOO2.getKey()));
QProfileDto anotherProfile = db.qualityProfiles().insert(p -> p.setName("Another").setLanguage(XOO2.getKey()));
db.qualityProfiles().setAsDefault(sonarWayOnXoo1, anotherProfile);
SearchWsResponse result = call(ws.newRequest()
.setParam(PARAM_DEFAULTS, "true")
.setParam(PARAM_QUALITY_PROFILE, "Sonar way"));
assertThat(result.getProfilesList()).extracting(QualityProfile::getKey)
.containsExactlyInAnyOrder(sonarWayOnXoo1.getKee())
.doesNotContain(sonarWayOnXoo2.getKee(), anotherProfile.getKee());
}
@Test
public void filter_on_project_key() {
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
QProfileDto profileOnXoo1 = db.qualityProfiles().insert(q -> q.setLanguage(XOO1.getKey()));
QProfileDto defaultProfileOnXoo1 = db.qualityProfiles().insert(q -> q.setLanguage(XOO1.getKey()));
QProfileDto defaultProfileOnXoo2 = db.qualityProfiles().insert(q -> q.setLanguage(XOO2.getKey()));
db.qualityProfiles().associateWithProject(project, profileOnXoo1);
db.qualityProfiles().setAsDefault(defaultProfileOnXoo1, defaultProfileOnXoo2);
SearchWsResponse result = call(ws.newRequest().setParam(PARAM_PROJECT, project.getKey()));
assertThat(result.getProfilesList())
.extracting(QualityProfile::getKey)
.containsExactlyInAnyOrder(profileOnXoo1.getKee(), defaultProfileOnXoo2.getKee())
.doesNotContain(defaultProfileOnXoo1.getKee());
}
@Test
public void filter_on_project_key_and_default() {
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
QProfileDto profileOnXoo1 = db.qualityProfiles().insert(q -> q.setLanguage(XOO1.getKey()));
QProfileDto defaultProfileOnXoo1 = db.qualityProfiles().insert(q -> q.setLanguage(XOO1.getKey()));
QProfileDto defaultProfileOnXoo2 = db.qualityProfiles().insert(q -> q.setLanguage(XOO2.getKey()));
db.qualityProfiles().associateWithProject(project, profileOnXoo1);
db.qualityProfiles().setAsDefault(defaultProfileOnXoo1, defaultProfileOnXoo2);
SearchWsResponse result = call(ws.newRequest()
.setParam(PARAM_PROJECT, project.getKey())
.setParam(PARAM_DEFAULTS, "true"));
assertThat(result.getProfilesList())
.extracting(QualityProfile::getKey)
.containsExactlyInAnyOrder(defaultProfileOnXoo2.getKee())
.doesNotContain(defaultProfileOnXoo1.getKee(), profileOnXoo1.getKee());
}
@Test
public void empty_when_filtering_on_project_and_no_language_installed() {
WsActionTester ws = new WsActionTester(new SearchAction(userSession, new Languages(), dbClient, new ComponentFinder(dbClient, null)));
db.qualityProfiles().insert();
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
QProfileDto profileOnXoo1 = db.qualityProfiles().insert(q -> q.setLanguage(XOO1.getKey()));
db.qualityProfiles().associateWithProject(project, profileOnXoo1);
SearchWsResponse result = call(ws.newRequest()
.setParam(PARAM_PROJECT, project.getKey())
.setParam(PARAM_DEFAULTS, "true"));
assertThat(result.getProfilesList()).isEmpty();
}
@Test
public void actions_when_user_is_global_qprofile_administer() {
QProfileDto customProfile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
QProfileDto builtInProfile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()).setIsBuiltIn(true));
QProfileDto defaultProfile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
db.qualityProfiles().setAsDefault(defaultProfile);
UserDto user = db.users().insertUser();
userSession.logIn(user).addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
SearchWsResponse result = call(ws.newRequest());
assertThat(result.getProfilesList())
.extracting(QualityProfile::getKey, qp -> qp.getActions().getEdit(), qp -> qp.getActions().getCopy(), qp -> qp.getActions().getSetAsDefault(),
qp -> qp.getActions().getDelete(), qp -> qp.getActions().getAssociateProjects())
.containsExactlyInAnyOrder(
tuple(customProfile.getKee(), true, true, true, true, true),
tuple(builtInProfile.getKee(), false, true, true, false, true),
tuple(defaultProfile.getKee(), true, true, false, false, false));
assertThat(result.getActions().getCreate()).isTrue();
}
@Test
public void actions_when_user_can_edit_profile() {
QProfileDto profile1 = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
QProfileDto profile2 = db.qualityProfiles().insert(p -> p.setLanguage(XOO2.getKey()));
QProfileDto profile3 = db.qualityProfiles().insert(p -> p.setLanguage(XOO2.getKey()));
QProfileDto builtInProfile = db.qualityProfiles().insert(p -> p.setLanguage(XOO2.getKey()).setIsBuiltIn(true));
UserDto user = db.users().insertUser();
GroupDto group = db.users().insertGroup();
db.qualityProfiles().addUserPermission(profile1, user);
db.qualityProfiles().addGroupPermission(profile3, group);
userSession.logIn(user).setGroups(group);
SearchWsResponse result = call(ws.newRequest());
assertThat(result.getProfilesList())
.extracting(QualityProfile::getKey, qp -> qp.getActions().getEdit(), qp -> qp.getActions().getCopy(), qp -> qp.getActions().getSetAsDefault(),
qp -> qp.getActions().getDelete(), qp -> qp.getActions().getAssociateProjects())
.containsExactlyInAnyOrder(
tuple(profile1.getKee(), true, false, false, false, false),
tuple(profile2.getKee(), false, false, false, false, false),
tuple(profile3.getKee(), true, false, false, false, false),
tuple(builtInProfile.getKee(), false, false, false, false, false));
assertThat(result.getActions().getCreate()).isFalse();
}
@Test
public void actions_when_not_logged_in() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
userSession.anonymous();
SearchWsResponse result = call(ws.newRequest());
assertThat(result.getProfilesList())
.extracting(QualityProfile::getKey, qp -> qp.getActions().getEdit(), qp -> qp.getActions().getCopy(), qp -> qp.getActions().getSetAsDefault(),
qp -> qp.getActions().getDelete(), qp -> qp.getActions().getAssociateProjects())
.containsExactlyInAnyOrder(tuple(profile.getKee(), false, false, false, false, false));
assertThat(result.getActions().getCreate()).isFalse();
}
@Test
public void statistics_on_active_rules() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
RuleDto rule = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()));
RuleDto deprecatedRule1 = db.rules().insertRule(r -> r.setStatus(DEPRECATED));
RuleDto deprecatedRule2 = db.rules().insertRule(r -> r.setStatus(DEPRECATED));
RuleDto inactiveRule = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()));
db.qualityProfiles().activateRule(profile, rule);
db.qualityProfiles().activateRule(profile, deprecatedRule1);
db.qualityProfiles().activateRule(profile, deprecatedRule2);
SearchWsResponse result = call(ws.newRequest());
assertThat(result.getProfilesList())
.extracting(QualityProfile::getActiveRuleCount, QualityProfile::getActiveDeprecatedRuleCount)
.containsExactlyInAnyOrder(tuple(3L, 2L));
}
@Test
public void statistics_on_projects() {
ProjectDto project1 = db.components().insertPrivateProject().getProjectDto();
ProjectDto project2 = db.components().insertPrivateProject().getProjectDto();
QProfileDto profileOnXoo1 = db.qualityProfiles().insert(q -> q.setLanguage(XOO1.getKey()));
QProfileDto defaultProfileOnXoo1 = db.qualityProfiles().insert(q -> q.setLanguage(XOO1.getKey()));
db.qualityProfiles().associateWithProject(project1, profileOnXoo1);
db.qualityProfiles().associateWithProject(project2, profileOnXoo1);
db.qualityProfiles().setAsDefault(defaultProfileOnXoo1);
SearchWsResponse result = call(ws.newRequest());
assertThat(result.getProfilesList())
.extracting(QualityProfile::hasProjectCount, QualityProfile::getProjectCount)
.containsExactlyInAnyOrder(tuple(true, 2L), tuple(false, 0L));
}
@Test
public void map_dates() {
long time = DateUtils.parseDateTime("2016-12-22T19:10:03+0100").getTime();
qualityProfileDb.insert(newQualityProfileDto()
.setLanguage(XOO1.getKey())
.setRulesUpdatedAt("2016-12-21T19:10:03+0100")
.setLastUsed(time)
.setUserUpdatedAt(time));
SearchWsResponse result = call(ws.newRequest());
assertThat(result.getProfilesCount()).isOne();
assertThat(result.getProfiles(0).getRulesUpdatedAt()).isEqualTo("2016-12-21T19:10:03+0100");
assertThat(parseDateTime(result.getProfiles(0).getLastUsed()).getTime()).isEqualTo(time);
assertThat(parseDateTime(result.getProfiles(0).getUserUpdatedAt()).getTime()).isEqualTo(time);
}
@Test
public void fail_if_project_does_not_exist() {
assertThatThrownBy(() -> {
call(ws.newRequest().setParam(PARAM_PROJECT, "unknown-project"));
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Project 'unknown-project' not found");
}
@Test
public void json_example() {
// languages
Language cs = newLanguage("cs", "C#");
Language java = newLanguage("java", "Java");
Language python = newLanguage("py", "Python");
// profiles
QProfileDto sonarWayCs = db.qualityProfiles().insert(
p -> p.setName("Sonar way").setKee("AU-TpxcA-iU5OvuD2FL3").setIsBuiltIn(true).setLanguage(cs.getKey()));
QProfileDto myCompanyProfile = db.qualityProfiles().insert(p -> p.setName("My Company Profile").setKee("iU5OvuD2FLz").setLanguage(java.getKey()));
QProfileDto myBuProfile = db.qualityProfiles().insert(
p -> p.setName("My BU Profile").setKee("AU-TpxcA-iU5OvuD2FL1").setParentKee(myCompanyProfile.getKee()).setLanguage(java.getKey()));
QProfileDto sonarWayPython = db.qualityProfiles().insert(
p -> p.setName("Sonar way").setKee("AU-TpxcB-iU5OvuD2FL7").setIsBuiltIn(true).setLanguage(python.getKey()));
db.qualityProfiles().setAsDefault(sonarWayCs, myCompanyProfile, sonarWayPython);
// rules
List<RuleDto> javaRules = range(0, 10).mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(java.getKey())))
.toList();
List<RuleDto> deprecatedJavaRules = range(0, 5)
.mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(java.getKey()).setStatus(DEPRECATED)))
.toList();
range(0, 7).forEach(i -> db.qualityProfiles().activateRule(myCompanyProfile, javaRules.get(i)));
range(0, 2).forEach(i -> db.qualityProfiles().activateRule(myCompanyProfile, deprecatedJavaRules.get(i)));
range(0, 10).forEach(i -> db.qualityProfiles().activateRule(myBuProfile, javaRules.get(i)));
range(0, 5).forEach(i -> db.qualityProfiles().activateRule(myBuProfile, deprecatedJavaRules.get(i)));
range(0, 2)
.mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(python.getKey())))
.forEach(rule -> db.qualityProfiles().activateRule(sonarWayPython, rule));
range(0, 3)
.mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(cs.getKey())))
.forEach(rule -> db.qualityProfiles().activateRule(sonarWayCs, rule));
// project
range(0, 7)
.mapToObj(i -> db.components().insertPrivateProject().getProjectDto())
.forEach(project -> db.qualityProfiles().associateWithProject(project, myBuProfile));
// User
UserDto user = db.users().insertUser();
db.qualityProfiles().addUserPermission(myCompanyProfile, user);
db.qualityProfiles().addUserPermission(myBuProfile, user);
userSession.logIn(user);
underTest = new SearchAction(userSession, new Languages(cs, java, python), dbClient, new ComponentFinder(dbClient, null));
ws = new WsActionTester(underTest);
String result = ws.newRequest().execute().getInput();
assertJson(result).ignoreFields("ruleUpdatedAt", "lastUsed", "userUpdatedAt")
.isSimilarTo(ws.getDef().responseExampleAsString());
}
@Test
public void definition() {
WebService.Action definition = ws.getDef();
assertThat(definition.key()).isEqualTo("search");
assertThat(definition.responseExampleAsString()).isNotEmpty();
assertThat(definition.isPost()).isFalse();
assertThat(definition.changelog())
.extracting(Change::getVersion, Change::getDescription)
.containsExactlyInAnyOrder(
tuple("6.5", "The parameters 'defaults', 'project' and 'language' can be combined without any constraint"),
tuple("6.6", "Add available actions 'edit', 'copy' and 'setAsDefault' and global action 'create'"),
tuple("7.0", "Add available actions 'delete' and 'associateProjects'"),
tuple("10.0", "Remove deprecated parameter 'project_key'. Please use 'project' instead."));
WebService.Param defaults = definition.param("defaults");
assertThat(defaults.defaultValue()).isEqualTo("false");
assertThat(defaults.description()).isEqualTo("If set to true, return only the quality profiles marked as default for each language");
WebService.Param projectKey = definition.param("project");
assertThat(projectKey.description()).isEqualTo("Project key");
assertThat(projectKey.deprecatedKey()).isNull();
WebService.Param language = definition.param("language");
assertThat(language.possibleValues()).containsExactly("xoo1", "xoo2");
assertThat(language.deprecatedSince()).isNull();
assertThat(language.description()).isEqualTo("Language key. If provided, only profiles for the given language are returned.");
WebService.Param profileName = definition.param("qualityProfile");
assertThat(profileName.deprecatedSince()).isNull();
assertThat(profileName.description()).isEqualTo("Quality profile name");
}
private SearchWsResponse call(TestRequest request) {
TestRequest wsRequest = request.setMediaType(MediaTypes.PROTOBUF);
return wsRequest.executeProtobuf(SearchWsResponse.class);
}
}
| 21,982 | 49.075171 | 150 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/SearchGroupsActionIT.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.qualityprofile.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbTester;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Qualityprofiles.SearchGroupsResponse;
import static java.lang.String.format;
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.sonar.api.server.ws.WebService.Param.PAGE;
import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
import static org.sonar.api.server.ws.WebService.Param.SELECTED;
import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
import static org.sonar.db.user.GroupTesting.newGroupDto;
import static org.sonar.test.JsonAssert.assertJson;
import static org.sonarqube.ws.MediaTypes.JSON;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE;
public class SearchGroupsActionIT {
private static final String XOO = "xoo";
private static final String FOO = "foo";
private static final Languages LANGUAGES = LanguageTesting.newLanguages(XOO, FOO);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create();
private final QProfileWsSupport wsSupport = new QProfileWsSupport(db.getDbClient(), userSession);
private final WsActionTester ws = new WsActionTester(new SearchGroupsAction(db.getDbClient(), wsSupport, LANGUAGES));
@Test
public void test_definition() {
WebService.Action def = ws.getDef();
assertThat(def.key()).isEqualTo("search_groups");
assertThat(def.isPost()).isFalse();
assertThat(def.isInternal()).isTrue();
assertThat(def.params()).extracting(WebService.Param::key)
.containsExactlyInAnyOrder("qualityProfile", "language", "selected", "q", "p", "ps");
}
@Test
public void test_example() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group1 = db.users().insertGroup(newGroupDto().setName("users").setDescription("Users"));
GroupDto group2 = db.users().insertGroup(newGroupDto().setName("administrators").setDescription("Administrators"));
db.qualityProfiles().addGroupPermission(profile, group1);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
String result = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "all")
.setMediaType(JSON)
.execute()
.getInput();
assertJson(ws.getDef().responseExampleAsString()).isSimilarTo(result);
}
@Test
public void search_all_groups() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group1 = db.users().insertGroup();
GroupDto group2 = db.users().insertGroup();
db.qualityProfiles().addGroupPermission(profile, group1);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
SearchGroupsResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "all")
.executeProtobuf(SearchGroupsResponse.class);
assertThat(response.getGroupsList()).extracting(SearchGroupsResponse.Group::getName, SearchGroupsResponse.Group::getDescription, SearchGroupsResponse.Group::getSelected)
.containsExactlyInAnyOrder(
tuple(group1.getName(), group1.getDescription(), true),
tuple(group2.getName(), group2.getDescription(), false));
}
@Test
public void search_selected_groups() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group1 = db.users().insertGroup();
GroupDto group2 = db.users().insertGroup();
db.qualityProfiles().addGroupPermission(profile, group1);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
SearchGroupsResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "selected")
.executeProtobuf(SearchGroupsResponse.class);
assertThat(response.getGroupsList()).extracting(SearchGroupsResponse.Group::getName, SearchGroupsResponse.Group::getDescription, SearchGroupsResponse.Group::getSelected)
.containsExactlyInAnyOrder(
tuple(group1.getName(), group1.getDescription(), true));
}
@Test
public void search_deselected_groups() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group1 = db.users().insertGroup();
GroupDto group2 = db.users().insertGroup();
db.qualityProfiles().addGroupPermission(profile, group1);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
SearchGroupsResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "deselected")
.executeProtobuf(SearchGroupsResponse.class);
assertThat(response.getGroupsList()).extracting(SearchGroupsResponse.Group::getName, SearchGroupsResponse.Group::getDescription, SearchGroupsResponse.Group::getSelected)
.containsExactlyInAnyOrder(
tuple(group2.getName(), group2.getDescription(), false));
}
@Test
public void search_by_name() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group1 = db.users().insertGroup("sonar-users-project");
GroupDto group2 = db.users().insertGroup("sonar-users-qprofile");
GroupDto group3 = db.users().insertGroup("sonar-admin");
db.qualityProfiles().addGroupPermission(profile, group1);
db.qualityProfiles().addGroupPermission(profile, group2);
db.qualityProfiles().addGroupPermission(profile, group3);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
SearchGroupsResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(TEXT_QUERY, "UsErS")
.setParam(SELECTED, "all")
.executeProtobuf(SearchGroupsResponse.class);
assertThat(response.getGroupsList()).extracting(SearchGroupsResponse.Group::getName)
.containsExactlyInAnyOrder(group1.getName(), group2.getName());
}
@Test
public void group_without_description() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group = db.users().insertGroup(newGroupDto().setDescription(null));
db.qualityProfiles().addGroupPermission(profile, group);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
SearchGroupsResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "all")
.executeProtobuf(SearchGroupsResponse.class);
assertThat(response.getGroupsList()).extracting(SearchGroupsResponse.Group::getName, SearchGroupsResponse.Group::hasDescription)
.containsExactlyInAnyOrder(tuple(group.getName(), false));
}
@Test
public void paging_search() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group3 = db.users().insertGroup("group3");
GroupDto group1 = db.users().insertGroup("group1");
GroupDto group2 = db.users().insertGroup("group2");
db.qualityProfiles().addGroupPermission(profile, group1);
db.qualityProfiles().addGroupPermission(profile, group2);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
assertThat(ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "all")
.setParam(PAGE, "1")
.setParam(PAGE_SIZE, "1")
.executeProtobuf(SearchGroupsResponse.class).getGroupsList())
.extracting(SearchGroupsResponse.Group::getName)
.containsExactly(group1.getName());
assertThat(ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "all")
.setParam(PAGE, "3")
.setParam(PAGE_SIZE, "1")
.executeProtobuf(SearchGroupsResponse.class).getGroupsList())
.extracting(SearchGroupsResponse.Group::getName)
.containsExactly(group3.getName());
assertThat(ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "all")
.setParam(PAGE, "1")
.setParam(PAGE_SIZE, "10")
.executeProtobuf(SearchGroupsResponse.class).getGroupsList())
.extracting(SearchGroupsResponse.Group::getName)
.containsExactly(group1.getName(), group2.getName(), group3.getName());
}
@Test
public void uses_global_permission() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group = db.users().insertGroup();
db.qualityProfiles().addGroupPermission(profile, group);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
SearchGroupsResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "all")
.executeProtobuf(SearchGroupsResponse.class);
assertThat(response.getGroupsList()).extracting(SearchGroupsResponse.Group::getName).containsExactlyInAnyOrder(group.getName());
}
@Test
public void qp_administers_can_search_groups() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group = db.users().insertGroup();
db.qualityProfiles().addGroupPermission(profile, group);
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
SearchGroupsResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "all")
.executeProtobuf(SearchGroupsResponse.class);
assertThat(response.getGroupsList()).extracting(SearchGroupsResponse.Group::getName).containsExactlyInAnyOrder(group.getName());
}
@Test
public void qp_editors_can_search_groups() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
GroupDto group = db.users().insertGroup();
db.qualityProfiles().addGroupPermission(profile, group);
UserDto userAllowedToEditProfile = db.users().insertUser();
db.qualityProfiles().addUserPermission(profile, userAllowedToEditProfile);
userSession.logIn(userAllowedToEditProfile);
SearchGroupsResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "all")
.executeProtobuf(SearchGroupsResponse.class);
assertThat(response.getGroupsList()).extracting(SearchGroupsResponse.Group::getName).containsExactlyInAnyOrder(group.getName());
}
@Test
public void fail_when_qprofile_does_not_exist() {
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, "unknown")
.setParam(PARAM_LANGUAGE, XOO)
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist");
}
@Test
public void fail_when_wrong_language() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, FOO)
.executeProtobuf(SearchGroupsResponse.class);
})
.isInstanceOf(NotFoundException.class)
.hasMessage(format("Quality Profile for language 'foo' and name '%s' does not exist", profile.getName()));
}
@Test
public void fail_when_not_enough_permission() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.execute();
})
.isInstanceOf(ForbiddenException.class);
}
}
| 14,011 | 41.850153 | 173 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/SearchUsersActionIT.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.qualityprofile.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbTester;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.issue.AvatarResolver;
import org.sonar.server.issue.AvatarResolverImpl;
import org.sonar.server.issue.FakeAvatarResolver;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Qualityprofiles.SearchUsersResponse;
import static java.lang.String.format;
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.sonar.api.server.ws.WebService.Param.PAGE;
import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
import static org.sonar.api.server.ws.WebService.Param.SELECTED;
import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
import static org.sonar.test.JsonAssert.assertJson;
import static org.sonarqube.ws.MediaTypes.JSON;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE;
public class SearchUsersActionIT {
private static final String XOO = "xoo";
private static final String FOO = "foo";
private static final Languages LANGUAGES = LanguageTesting.newLanguages(XOO, FOO);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create();
private final QProfileWsSupport wsSupport = new QProfileWsSupport(db.getDbClient(), userSession);
private AvatarResolver avatarResolver = new FakeAvatarResolver();
private WsActionTester ws = new WsActionTester(new SearchUsersAction(db.getDbClient(), wsSupport, LANGUAGES, avatarResolver));
@Test
public void test_definition() {
WebService.Action def = ws.getDef();
assertThat(def.key()).isEqualTo("search_users");
assertThat(def.isPost()).isFalse();
assertThat(def.isInternal()).isTrue();
assertThat(def.params()).extracting(WebService.Param::key)
.containsExactlyInAnyOrder("qualityProfile", "language", "selected", "q", "p", "ps");
}
@Test
public void test_example() {
avatarResolver = new AvatarResolverImpl();
ws = new WsActionTester(new SearchUsersAction(db.getDbClient(), wsSupport, LANGUAGES, avatarResolver));
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user1 = db.users().insertUser(u -> u.setLogin("admin").setName("Administrator").setEmail("admin@email.com"));
UserDto user2 = db.users().insertUser(u -> u.setLogin("george.orwell").setName("George Orwell").setEmail("george@orwell.com"));
db.qualityProfiles().addUserPermission(profile, user1);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
String result = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "all")
.setMediaType(JSON)
.execute()
.getInput();
assertJson(result).isSimilarTo(ws.getDef().responseExampleAsString());
}
@Test
public void search_all_users() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user1 = db.users().insertUser(u -> u.setEmail("user1@email.com"));
UserDto user2 = db.users().insertUser(u -> u.setEmail("user2@email.com"));
db.qualityProfiles().addUserPermission(profile, user1);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
SearchUsersResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "all")
.executeProtobuf(SearchUsersResponse.class);
assertThat(response.getUsersList())
.extracting(SearchUsersResponse.User::getLogin, SearchUsersResponse.User::getName, SearchUsersResponse.User::getAvatar, SearchUsersResponse.User::getSelected)
.containsExactlyInAnyOrder(
tuple(user1.getLogin(), user1.getName(), "user1@email.com_avatar", true),
tuple(user2.getLogin(), user2.getName(), "user2@email.com_avatar", false));
}
@Test
public void search_selected_users() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user1 = db.users().insertUser();
UserDto user2 = db.users().insertUser();
db.qualityProfiles().addUserPermission(profile, user1);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
SearchUsersResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "selected")
.executeProtobuf(SearchUsersResponse.class);
assertThat(response.getUsersList()).extracting(SearchUsersResponse.User::getLogin, SearchUsersResponse.User::getName, SearchUsersResponse.User::getSelected)
.containsExactlyInAnyOrder(
tuple(user1.getLogin(), user1.getName(), true));
}
@Test
public void search_deselected_users() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user1 = db.users().insertUser();
UserDto user2 = db.users().insertUser();
db.qualityProfiles().addUserPermission(profile, user1);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
SearchUsersResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "deselected")
.executeProtobuf(SearchUsersResponse.class);
assertThat(response.getUsersList()).extracting(SearchUsersResponse.User::getLogin, SearchUsersResponse.User::getName, SearchUsersResponse.User::getSelected)
.containsExactlyInAnyOrder(
tuple(user2.getLogin(), user2.getName(), false));
}
@Test
public void search_by_login() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user1 = db.users().insertUser();
UserDto user2 = db.users().insertUser();
db.qualityProfiles().addUserPermission(profile, user1);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
SearchUsersResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(TEXT_QUERY, user1.getLogin())
.setParam(SELECTED, "all")
.executeProtobuf(SearchUsersResponse.class);
assertThat(response.getUsersList()).extracting(SearchUsersResponse.User::getLogin)
.containsExactlyInAnyOrder(user1.getLogin());
}
@Test
public void search_by_name() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user1 = db.users().insertUser(u -> u.setName("John Doe"));
UserDto user2 = db.users().insertUser(u -> u.setName("Jane Doe"));
UserDto user3 = db.users().insertUser(u -> u.setName("John Smith"));
db.qualityProfiles().addUserPermission(profile, user1);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
SearchUsersResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(TEXT_QUERY, "ohn")
.setParam(SELECTED, "all")
.executeProtobuf(SearchUsersResponse.class);
assertThat(response.getUsersList()).extracting(SearchUsersResponse.User::getLogin)
.containsExactlyInAnyOrder(user1.getLogin(), user3.getLogin());
}
@Test
public void user_without_email() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user = db.users().insertUser(u -> u.setEmail(null));
db.qualityProfiles().addUserPermission(profile, user);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
SearchUsersResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "all")
.executeProtobuf(SearchUsersResponse.class);
assertThat(response.getUsersList()).extracting(SearchUsersResponse.User::getLogin, SearchUsersResponse.User::hasAvatar)
.containsExactlyInAnyOrder(tuple(user.getLogin(), false));
}
@Test
public void paging_search() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user2 = db.users().insertUser(u -> u.setName("user2"));
UserDto user3 = db.users().insertUser(u -> u.setName("user3"));
UserDto user1 = db.users().insertUser(u -> u.setName("user1"));
db.qualityProfiles().addUserPermission(profile, user1);
db.qualityProfiles().addUserPermission(profile, user2);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
assertThat(ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "all")
.setParam(PAGE, "1")
.setParam(PAGE_SIZE, "1")
.executeProtobuf(SearchUsersResponse.class).getUsersList())
.extracting(SearchUsersResponse.User::getLogin)
.containsExactly(user1.getLogin());
assertThat(ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "all")
.setParam(PAGE, "3")
.setParam(PAGE_SIZE, "1")
.executeProtobuf(SearchUsersResponse.class).getUsersList())
.extracting(SearchUsersResponse.User::getLogin)
.containsExactly(user3.getLogin());
assertThat(ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "all")
.setParam(PAGE, "1")
.setParam(PAGE_SIZE, "10")
.executeProtobuf(SearchUsersResponse.class).getUsersList())
.extracting(SearchUsersResponse.User::getLogin)
.containsExactly(user1.getLogin(), user2.getLogin(), user3.getLogin());
}
@Test
public void uses_global_permission() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user1 = db.users().insertUser();
db.qualityProfiles().addUserPermission(profile, user1);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
SearchUsersResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "all")
.executeProtobuf(SearchUsersResponse.class);
assertThat(response.getUsersList()).extracting(SearchUsersResponse.User::getLogin).containsExactlyInAnyOrder(user1.getLogin());
}
@Test
public void qp_administers_can_search_users() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user = db.users().insertUser();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
SearchUsersResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "all")
.executeProtobuf(SearchUsersResponse.class);
assertThat(response.getUsersList()).extracting(SearchUsersResponse.User::getLogin).containsExactlyInAnyOrder(user.getLogin());
}
@Test
public void qp_editors_can_search_users() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user = db.users().insertUser();
UserDto userAllowedToEditProfile = db.users().insertUser();
db.qualityProfiles().addUserPermission(profile, userAllowedToEditProfile);
userSession.logIn(userAllowedToEditProfile);
SearchUsersResponse response = ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.setParam(SELECTED, "all")
.executeProtobuf(SearchUsersResponse.class);
assertThat(response.getUsersList()).extracting(SearchUsersResponse.User::getLogin).containsExactlyInAnyOrder(user.getLogin(), userAllowedToEditProfile.getLogin());
}
@Test
public void fail_when_qprofile_does_not_exist() {
UserDto user = db.users().insertUser();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, "unknown")
.setParam(PARAM_LANGUAGE, XOO)
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist");
}
@Test
public void fail_when_wrong_language() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user1 = db.users().insertUser();
db.qualityProfiles().addUserPermission(profile, user1);
userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, FOO)
.executeProtobuf(SearchUsersResponse.class);
})
.isInstanceOf(NotFoundException.class)
.hasMessage(format("Quality Profile for language 'foo' and name '%s' does not exist", profile.getName()));
}
@Test
public void fail_when_not_enough_permission() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO));
UserDto user = db.users().insertUser();
userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES);
assertThatThrownBy(() -> ws.newRequest()
.setParam(PARAM_QUALITY_PROFILE, profile.getName())
.setParam(PARAM_LANGUAGE, XOO)
.execute())
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
}
| 15,113 | 42.059829 | 167 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/SetDefaultActionIT.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.qualityprofile.ws;
import org.assertj.core.api.Fail;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.QualityProfileTesting;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_KEY;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE;
public class SetDefaultActionIT {
private static final String XOO_1_KEY = "xoo1";
private static final String XOO_2_KEY = "xoo2";
@Rule
public DbTester db = DbTester.create();
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
private DbClient dbClient;
private QProfileWsSupport wsSupport;
private SetDefaultAction underTest;
private WsActionTester ws;
/** Single, default quality profile for language xoo1 */
private QProfileDto xoo1Profile;
/** Parent quality profile for language xoo2 (not a default) */
private QProfileDto xoo2Profile;
/** Child quality profile for language xoo2, set as default */
private QProfileDto xoo2Profile2;
@Before
public void setUp() {
dbClient = db.getDbClient();
wsSupport = new QProfileWsSupport(dbClient, userSessionRule);
underTest = new SetDefaultAction(LanguageTesting.newLanguages(XOO_1_KEY, XOO_2_KEY), dbClient, userSessionRule, wsSupport);
xoo1Profile = QualityProfileTesting.newQualityProfileDto().setLanguage(XOO_1_KEY);
xoo2Profile = QualityProfileTesting.newQualityProfileDto().setLanguage(XOO_2_KEY);
xoo2Profile2 = QualityProfileTesting.newQualityProfileDto().setLanguage(XOO_2_KEY).setParentKee(xoo2Profile.getKee());
dbClient.qualityProfileDao().insert(db.getSession(), xoo1Profile, xoo2Profile, xoo2Profile2);
db.commit();
db.qualityProfiles().setAsDefault(xoo1Profile, xoo2Profile2);
ws = new WsActionTester(underTest);
}
@Test
public void definition() {
WebService.Action definition = ws.getDef();
assertThat(definition).isNotNull();
assertThat(definition.isPost()).isTrue();
assertThat(definition.params()).extracting(Param::key).containsExactlyInAnyOrder("qualityProfile", "language");
}
@Test
public void set_default_profile_using_language_and_name() {
logInAsQProfileAdministrator();
checkDefaultProfile(XOO_1_KEY, xoo1Profile.getKee());
checkDefaultProfile(XOO_2_KEY, xoo2Profile2.getKee());
TestResponse response = ws.newRequest().setMethod("POST")
.setParam("language", xoo2Profile.getLanguage())
.setParam("qualityProfile", xoo2Profile.getName())
.execute();
assertThat(response.getInput()).isEmpty();
checkDefaultProfile(XOO_1_KEY, xoo1Profile.getKee());
checkDefaultProfile(XOO_2_KEY, xoo2Profile.getKee());
}
@Test
public void fail_to_set_default_profile_using_language_and_invalid_name() {
logInAsQProfileAdministrator();
try {
TestResponse response = ws.newRequest().setMethod("POST")
.setParam("language", XOO_2_KEY)
.setParam("qualityProfile", "Unknown")
.execute();
Fail.failBecauseExceptionWasNotThrown(NotFoundException.class);
} catch (NotFoundException nfe) {
assertThat(nfe).hasMessage("Quality Profile for language 'xoo2' and name 'Unknown' does not exist");
checkDefaultProfile(XOO_1_KEY, xoo1Profile.getKee());
checkDefaultProfile(XOO_2_KEY, xoo2Profile2.getKee());
}
}
@Test
public void throw_ForbiddenException_if_not_profile_administrator() {
userSessionRule.logIn();
assertThatThrownBy(() -> {
ws.newRequest().setMethod("POST")
.setParam(PARAM_QUALITY_PROFILE, xoo2Profile.getName())
.setParam(PARAM_LANGUAGE, xoo2Profile.getLanguage())
.execute();
})
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void throw_UnauthorizedException_if_not_logged_in() {
assertThatThrownBy(() -> {
ws.newRequest().setMethod("POST")
.setParam(PARAM_KEY, xoo2Profile.getKee())
.execute();
})
.isInstanceOf(UnauthorizedException.class)
.hasMessage("Authentication is required");
}
private void logInAsQProfileAdministrator() {
userSessionRule
.logIn()
.addPermission(ADMINISTER_QUALITY_PROFILES);
}
private void checkDefaultProfile(String language, String key) {
assertThat(dbClient.qualityProfileDao().selectDefaultProfile(db.getSession(), language).getKee()).isEqualTo(key);
}
}
| 6,203 | 36.373494 | 127 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/ws/ShowActionIT.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.qualityprofile.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import org.sonar.server.rule.index.RuleIndex;
import org.sonar.server.rule.index.RuleIndexer;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.MediaTypes;
import org.sonarqube.ws.Qualityprofiles.ShowResponse;
import org.sonarqube.ws.Qualityprofiles.ShowResponse.CompareToSonarWay;
import org.sonarqube.ws.Qualityprofiles.ShowResponse.QualityProfile;
import static java.util.stream.IntStream.range;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.rule.RuleStatus.DEPRECATED;
import static org.sonar.api.utils.DateUtils.parseDateTime;
import static org.sonar.server.language.LanguageTesting.newLanguage;
import static org.sonar.test.JsonAssert.assertJson;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_COMPARE_TO_SONAR_WAY;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_KEY;
public class ShowActionIT {
private static Language XOO1 = newLanguage("xoo1");
private static Language XOO2 = newLanguage("xoo2");
private static Languages LANGUAGES = new Languages(XOO1, XOO2);
@Rule
public EsTester es = EsTester.create();
@Rule
public DbTester db = DbTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private RuleIndexer ruleIndexer = new RuleIndexer(es.client(), db.getDbClient());
private ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(db.getDbClient(), es.client());
private RuleIndex ruleIndex = new RuleIndex(es.client(), System2.INSTANCE);
private WsActionTester ws = new WsActionTester(
new ShowAction(db.getDbClient(), new QProfileWsSupport(db.getDbClient(), userSession), LANGUAGES, ruleIndex));
@Test
public void profile_info() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
ShowResponse result = call(ws.newRequest().setParam(PARAM_KEY, profile.getKee()));
assertThat(result.getProfile())
.extracting(QualityProfile::getKey, QualityProfile::getName, QualityProfile::getIsBuiltIn, QualityProfile::getLanguage, QualityProfile::getLanguageName,
QualityProfile::getIsInherited)
.containsExactly(profile.getKee(), profile.getName(), profile.isBuiltIn(), profile.getLanguage(), XOO1.getName(), false);
}
@Test
public void default_profile() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
db.qualityProfiles().setAsDefault(profile);
ShowResponse result = call(ws.newRequest().setParam(PARAM_KEY, profile.getKee()));
assertThat(result.getProfile().getIsDefault()).isTrue();
}
@Test
public void non_default_profile() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
QProfileDto defaultProfile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
db.qualityProfiles().setAsDefault(defaultProfile);
ShowResponse result = call(ws.newRequest().setParam(PARAM_KEY, profile.getKee()));
assertThat(result.getProfile().getIsDefault()).isFalse();
}
@Test
public void map_dates() {
long time = DateUtils.parseDateTime("2016-12-22T19:10:03+0100").getTime();
QProfileDto profile = db.qualityProfiles().insert(p -> p
.setLanguage(XOO1.getKey())
.setRulesUpdatedAt("2016-12-21T19:10:03+0100")
.setLastUsed(time)
.setUserUpdatedAt(time));
ShowResponse result = call(ws.newRequest().setParam(PARAM_KEY, profile.getKee()));
assertThat(result.getProfile().getRulesUpdatedAt()).isEqualTo("2016-12-21T19:10:03+0100");
assertThat(parseDateTime(result.getProfile().getLastUsed()).getTime()).isEqualTo(time);
assertThat(parseDateTime(result.getProfile().getUserUpdatedAt()).getTime()).isEqualTo(time);
}
@Test
public void statistics() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
// Active rules
range(0, 10)
.mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(XOO1.getKey())))
.forEach(r -> db.qualityProfiles().activateRule(profile, r));
// Deprecated rules
range(0, 3)
.mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()).setStatus(DEPRECATED)))
.forEach(r -> db.qualityProfiles().activateRule(profile, r));
// Projects
range(0, 7)
.mapToObj(i -> db.components().insertPrivateProject().getProjectDto())
.forEach(project -> db.qualityProfiles().associateWithProject(project, profile));
ShowResponse result = call(ws.newRequest().setParam(PARAM_KEY, profile.getKee()));
assertThat(result.getProfile())
.extracting(QualityProfile::getActiveRuleCount, QualityProfile::getActiveDeprecatedRuleCount, QualityProfile::getProjectCount)
.containsExactly(13L, 3L, 7L);
}
@Test
public void compare_to_sonar_way_profile() {
QProfileDto sonarWayProfile = db.qualityProfiles().insert(p -> p.setIsBuiltIn(true).setName("Sonar way").setLanguage(XOO1.getKey()));
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
RuleDto commonRule = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()));
RuleDto sonarWayRule1 = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()));
RuleDto sonarWayRule2 = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()));
RuleDto profileRule1 = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()));
RuleDto profileRule2 = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()));
RuleDto profileRule3 = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()));
db.qualityProfiles().activateRule(profile, commonRule);
db.qualityProfiles().activateRule(profile, profileRule1);
db.qualityProfiles().activateRule(profile, profileRule2);
db.qualityProfiles().activateRule(profile, profileRule3);
db.qualityProfiles().activateRule(sonarWayProfile, commonRule);
db.qualityProfiles().activateRule(sonarWayProfile, sonarWayRule1);
db.qualityProfiles().activateRule(sonarWayProfile, sonarWayRule2);
ruleIndexer.indexAll();
activeRuleIndexer.indexAll();
CompareToSonarWay result = call(ws.newRequest()
.setParam(PARAM_KEY, profile.getKee())
.setParam(PARAM_COMPARE_TO_SONAR_WAY, "true"))
.getCompareToSonarWay();
assertThat(result)
.extracting(CompareToSonarWay::getProfile, CompareToSonarWay::getProfileName, CompareToSonarWay::getMissingRuleCount)
.containsExactly(sonarWayProfile.getKee(), sonarWayProfile.getName(), 2L);
}
@Test
public void compare_to_sonar_way_profile_when_same_active_rules() {
QProfileDto sonarWayProfile = db.qualityProfiles().insert(p -> p.setIsBuiltIn(true).setName("Sonar way").setLanguage(XOO1.getKey()));
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
RuleDto commonRule = db.rules().insertRule(r -> r.setLanguage(XOO1.getKey()));
db.qualityProfiles().activateRule(profile, commonRule);
db.qualityProfiles().activateRule(sonarWayProfile, commonRule);
ruleIndexer.indexAll();
activeRuleIndexer.indexAll();
CompareToSonarWay result = call(ws.newRequest()
.setParam(PARAM_KEY, profile.getKee())
.setParam(PARAM_COMPARE_TO_SONAR_WAY, "true"))
.getCompareToSonarWay();
assertThat(result)
.extracting(CompareToSonarWay::getProfile, CompareToSonarWay::getProfileName, CompareToSonarWay::getMissingRuleCount)
.containsExactly(sonarWayProfile.getKee(), sonarWayProfile.getName(), 0L);
}
@Test
public void no_comparison_when_sonar_way_does_not_exist() {
QProfileDto anotherSonarWayProfile = db.qualityProfiles().insert(p -> p.setIsBuiltIn(true).setName("Another Sonar way").setLanguage(XOO1.getKey()));
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
ShowResponse result = call(ws.newRequest()
.setParam(PARAM_KEY, profile.getKee())
.setParam(PARAM_COMPARE_TO_SONAR_WAY, "true"));
assertThat(result.hasCompareToSonarWay()).isFalse();
}
@Test
public void no_comparison_when_profile_is_built_in() {
QProfileDto sonarWayProfile = db.qualityProfiles().insert(p -> p.setIsBuiltIn(true).setName("Sonar way").setLanguage(XOO1.getKey()));
QProfileDto anotherBuiltInProfile = db.qualityProfiles().insert(p -> p.setIsBuiltIn(true).setLanguage(XOO1.getKey()));
ShowResponse result = call(ws.newRequest()
.setParam(PARAM_KEY, anotherBuiltInProfile.getKee())
.setParam(PARAM_COMPARE_TO_SONAR_WAY, "true"));
assertThat(result.hasCompareToSonarWay()).isFalse();
}
@Test
public void no_comparison_if_sonar_way_is_not_built_in() {
QProfileDto sonarWayProfile = db.qualityProfiles().insert(p -> p.setIsBuiltIn(false).setName("Sonar way").setLanguage(XOO1.getKey()));
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
ShowResponse result = call(ws.newRequest()
.setParam(PARAM_KEY, profile.getKee())
.setParam(PARAM_COMPARE_TO_SONAR_WAY, "true"));
assertThat(result.hasCompareToSonarWay()).isFalse();
}
@Test
public void no_comparison_when_param_is_false() {
QProfileDto sonarWayProfile = db.qualityProfiles().insert(p -> p.setIsBuiltIn(true).setName("Sonar way").setLanguage(XOO1.getKey()));
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
ShowResponse result = call(ws.newRequest()
.setParam(PARAM_KEY, profile.getKee())
.setParam(PARAM_COMPARE_TO_SONAR_WAY, "false"));
assertThat(result.hasCompareToSonarWay()).isFalse();
}
@Test
public void compare_to_sonarqube_way_profile() {
QProfileDto sonarWayProfile = db.qualityProfiles().insert(p -> p.setIsBuiltIn(true).setName("SonarQube way").setLanguage(XOO1.getKey()));
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
CompareToSonarWay result = call(ws.newRequest()
.setParam(PARAM_KEY, profile.getKee())
.setParam(PARAM_COMPARE_TO_SONAR_WAY, "true"))
.getCompareToSonarWay();
assertThat(result)
.extracting(CompareToSonarWay::getProfile, CompareToSonarWay::getProfileName)
.containsExactly(sonarWayProfile.getKee(), sonarWayProfile.getName());
}
@Test
public void compare_to_sonar_way_over_sonarqube_way() {
QProfileDto sonarWayProfile = db.qualityProfiles().insert(p -> p.setIsBuiltIn(true).setName("Sonar way").setLanguage(XOO1.getKey()));
QProfileDto sonarQubeWayProfile = db.qualityProfiles().insert(p -> p.setIsBuiltIn(true).setName("SonarQube way").setLanguage(XOO1.getKey()));
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
CompareToSonarWay result = call(ws.newRequest()
.setParam(PARAM_KEY, profile.getKee())
.setParam(PARAM_COMPARE_TO_SONAR_WAY, "true"))
.getCompareToSonarWay();
assertThat(result)
.extracting(CompareToSonarWay::getProfile, CompareToSonarWay::getProfileName)
.containsExactly(sonarWayProfile.getKee(), sonarWayProfile.getName());
}
@Test
public void show() {
QProfileDto qualityProfile = db.qualityProfiles().insert(p -> p.setLanguage(XOO1.getKey()));
UserDto user = db.users().insertUser();
userSession.logIn(user);
ShowResponse result = call(ws.newRequest().setParam(PARAM_KEY, qualityProfile.getKee()));
assertThat(result.getProfile())
.extracting(QualityProfile::getKey)
.isEqualTo(qualityProfile.getKee());
}
@Test
public void fail_if_profile_language_is_not_supported() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setKee("unknown-profile").setLanguage("kotlin"));
assertThatThrownBy(() -> {
call(ws.newRequest().setParam(PARAM_KEY, profile.getKee()));
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Quality Profile with key 'unknown-profile' does not exist");
}
@Test
public void fail_if_profile_does_not_exist() {
assertThatThrownBy(() -> {
call(ws.newRequest().setParam(PARAM_KEY, "unknown-profile"));
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Quality Profile with key 'unknown-profile' does not exist");
}
@Test
public void json_example() {
Language cs = newLanguage("cs", "C#");
QProfileDto parentProfile = db.qualityProfiles().insert(
p -> p.setKee("AU-TpxcA-iU5OvuD2FL1")
.setName("Parent Company Profile")
.setLanguage(cs.getKey()));
QProfileDto profile = db.qualityProfiles().insert(p -> p
.setKee("AU-TpxcA-iU5OvuD2FL3")
.setName("My Company Profile")
.setLanguage(cs.getKey())
.setIsBuiltIn(false)
.setRulesUpdatedAt("2016-12-22T19:10:03+0100")
.setParentKee(parentProfile.getKee()));
// Active rules
range(0, 10)
.mapToObj(i -> db.rules().insertRule(r -> r.setLanguage(cs.getKey())))
.forEach(r -> db.qualityProfiles().activateRule(profile, r));
// Projects
range(0, 7)
.mapToObj(i -> db.components().insertPrivateProject().getProjectDto())
.forEach(project -> db.qualityProfiles().associateWithProject(project, profile));
ws = new WsActionTester(
new ShowAction(db.getDbClient(), new QProfileWsSupport(db.getDbClient(), userSession), new Languages(cs), ruleIndex));
String result = ws.newRequest().setParam(PARAM_KEY, profile.getKee()).execute().getInput();
assertJson(result).ignoreFields("rulesUpdatedAt", "lastUsed", "userUpdatedAt").isSimilarTo(ws.getDef().responseExampleAsString());
}
@Test
public void test_definition() {
WebService.Action action = ws.getDef();
assertThat(action.key()).isEqualTo("show");
assertThat(action.responseExampleAsString()).isNotEmpty();
assertThat(action.isPost()).isFalse();
assertThat(action.since()).isEqualTo("6.5");
WebService.Param profile = action.param("key");
assertThat(profile.isRequired()).isTrue();
assertThat(profile.isInternal()).isFalse();
assertThat(profile.description()).isNotEmpty();
WebService.Param compareToSonarWay = action.param("compareToSonarWay");
assertThat(compareToSonarWay.isRequired()).isFalse();
assertThat(compareToSonarWay.isInternal()).isTrue();
assertThat(compareToSonarWay.description()).isNotEmpty();
assertThat(compareToSonarWay.defaultValue()).isEqualTo("false");
assertThat(compareToSonarWay.possibleValues()).contains("true", "false");
}
private ShowResponse call(TestRequest request) {
TestRequest wsRequest = request.setMediaType(MediaTypes.PROTOBUF);
return wsRequest.executeProtobuf(ShowResponse.class);
}
}
| 16,221 | 43.322404 | 158 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/rule/RuleCreatorIT.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 com.google.common.collect.Sets;
import java.time.Instant;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.assertj.core.api.Fail;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import org.sonar.api.server.debt.DebtRemediationFunction;
import org.sonar.api.utils.System2;
import org.sonar.core.util.SequenceUuidFactory;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleDto.Format;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.rule.index.RuleIndex;
import org.sonar.server.rule.index.RuleIndexer;
import org.sonar.server.rule.index.RuleQuery;
import static java.util.Collections.singletonList;
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.junit.Assert.fail;
import static org.sonar.db.rule.RuleTesting.newCustomRule;
import static org.sonar.db.rule.RuleTesting.newRule;
import static org.sonar.server.util.TypeValidationsTesting.newFullTypeValidations;
public class RuleCreatorIT {
private final System2 system2 = new TestSystem2().setNow(Instant.now().toEpochMilli());
@Rule
public DbTester dbTester = DbTester.create(system2);
@Rule
public EsTester es = EsTester.create();
private final RuleIndex ruleIndex = new RuleIndex(es.client(), system2);
private final RuleIndexer ruleIndexer = new RuleIndexer(es.client(), dbTester.getDbClient());
private final DbSession dbSession = dbTester.getSession();
private final UuidFactory uuidFactory = new SequenceUuidFactory();
private final RuleCreator underTest = new RuleCreator(system2, new RuleIndexer(es.client(), dbTester.getDbClient()), dbTester.getDbClient(), newFullTypeValidations(), uuidFactory);
@Test
public void create_custom_rule() {
// insert template rule
RuleDto templateRule = createTemplateRule();
// Create custom rule
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setMarkdownDescription("Some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY)
.setParameters(ImmutableMap.of("regex", "a.*"));
RuleKey customRuleKey = underTest.create(dbSession, newRule);
RuleDto rule = dbTester.getDbClient().ruleDao().selectOrFailByKey(dbSession, customRuleKey);
assertThat(rule).isNotNull();
assertThat(rule.getKey()).isEqualTo(RuleKey.of("java", "CUSTOM_RULE"));
assertThat(rule.getPluginKey()).isEqualTo("sonarjava");
assertThat(rule.getTemplateUuid()).isEqualTo(templateRule.getUuid());
assertThat(rule.getName()).isEqualTo("My custom");
assertThat(rule.getDefaultRuleDescriptionSection().getContent()).isEqualTo("Some description");
assertThat(rule.getSeverityString()).isEqualTo("MAJOR");
assertThat(rule.getStatus()).isEqualTo(RuleStatus.READY);
assertThat(rule.getLanguage()).isEqualTo("java");
assertThat(rule.getConfigKey()).isEqualTo("S001");
assertThat(rule.getDefRemediationFunction()).isEqualTo("LINEAR_OFFSET");
assertThat(rule.getDefRemediationGapMultiplier()).isEqualTo("1h");
assertThat(rule.getDefRemediationBaseEffort()).isEqualTo("5min");
assertThat(rule.getGapDescription()).isEqualTo("desc");
assertThat(rule.getTags()).containsOnly("usertag1", "usertag2");
assertThat(rule.getSystemTags()).containsOnly("tag1", "tag4");
assertThat(rule.getSecurityStandards()).containsOnly("owaspTop10:a1", "cwe:123");
assertThat(rule.isExternal()).isFalse();
assertThat(rule.isAdHoc()).isFalse();
List<RuleParamDto> params = dbTester.getDbClient().ruleDao().selectRuleParamsByRuleKey(dbSession, customRuleKey);
assertThat(params).hasSize(1);
RuleParamDto param = params.get(0);
// From template rule
assertThat(param.getName()).isEqualTo("regex");
assertThat(param.getDescription()).isEqualTo("Reg ex");
assertThat(param.getType()).isEqualTo("STRING");
// From user
assertThat(param.getDefaultValue()).isEqualTo("a.*");
assertThat(ruleIndex.search(new RuleQuery(), new SearchOptions()).getUuids()).containsOnly(rule.getUuid(), templateRule.getUuid());
}
@Test
public void create_custom_rule_with_empty_parameter_value() {
// insert template rule
RuleDto templateRule = createTemplateRule();
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setMarkdownDescription("some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY)
.setParameters(ImmutableMap.of("regex", ""));
RuleKey customRuleKey = underTest.create(dbSession, newRule);
List<RuleParamDto> params = dbTester.getDbClient().ruleDao().selectRuleParamsByRuleKey(dbSession, customRuleKey);
assertThat(params).hasSize(1);
RuleParamDto param = params.get(0);
assertThat(param.getName()).isEqualTo("regex");
assertThat(param.getDescription()).isEqualTo("Reg ex");
assertThat(param.getType()).isEqualTo("STRING");
assertThat(param.getDefaultValue()).isNull();
}
@Test
public void create_custom_rule_with_no_parameter_value() {
// insert template rule
RuleDto templateRule = createTemplateRuleWithIntArrayParam();
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setMarkdownDescription("some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY);
RuleKey customRuleKey = underTest.create(dbSession, newRule);
List<RuleParamDto> params = dbTester.getDbClient().ruleDao().selectRuleParamsByRuleKey(dbSession, customRuleKey);
assertThat(params).hasSize(1);
RuleParamDto param = params.get(0);
assertThat(param.getName()).isEqualTo("myIntegers");
assertThat(param.getDescription()).isEqualTo("My Integers");
assertThat(param.getType()).isEqualTo("INTEGER,multiple=true,values=1;2;3");
assertThat(param.getDefaultValue()).isNull();
}
@Test
public void create_custom_rule_with_multiple_parameter_values() {
// insert template rule
RuleDto templateRule = createTemplateRuleWithIntArrayParam();
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setMarkdownDescription("some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY)
.setParameters(ImmutableMap.of("myIntegers", "1,3"));
RuleKey customRuleKey = underTest.create(dbSession, newRule);
List<RuleParamDto> params = dbTester.getDbClient().ruleDao().selectRuleParamsByRuleKey(dbSession, customRuleKey);
assertThat(params).hasSize(1);
RuleParamDto param = params.get(0);
assertThat(param.getName()).isEqualTo("myIntegers");
assertThat(param.getDescription()).isEqualTo("My Integers");
assertThat(param.getType()).isEqualTo("INTEGER,multiple=true,values=1;2;3");
assertThat(param.getDefaultValue()).isEqualTo("1,3");
}
@Test
public void batch_create_custom_rules() {
// insert template rule
RuleDto templateRule = createTemplateRuleWithIntArrayParam();
NewCustomRule firstRule = NewCustomRule.createForCustomRule("CUSTOM_RULE_1", templateRule.getKey())
.setName("My custom")
.setMarkdownDescription("some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY);
NewCustomRule secondRule = NewCustomRule.createForCustomRule("CUSTOM_RULE_2", templateRule.getKey())
.setName("My custom")
.setMarkdownDescription("some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY);
List<RuleKey> customRuleKeys = underTest.create(dbSession, Arrays.asList(firstRule, secondRule));
List<RuleDto> rules = dbTester.getDbClient().ruleDao().selectByKeys(dbSession, customRuleKeys);
assertThat(rules).hasSize(2);
assertThat(rules).asList()
.extracting("ruleKey")
.containsOnly("CUSTOM_RULE_1", "CUSTOM_RULE_2");
}
@Test
public void fail_to_create_custom_rules_when_wrong_rule_template() {
// insert rule
RuleDto rule = newRule(RuleKey.of("java", "S001")).setIsTemplate(false);
dbTester.rules().insert(rule);
dbSession.commit();
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", rule.getKey())
.setName("My custom")
.setMarkdownDescription("some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY)
.setParameters(ImmutableMap.of("regex", "a.*"));
assertThatThrownBy(() -> underTest.create(dbSession, singletonList(newRule)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("This rule is not a template rule: java:S001");
}
@Test
public void fail_to_create_custom_rules_when_removed_rule_template() {
// insert rule
RuleDto rule = createTemplateRule();
newRule(RuleKey.of("java", "S001")).setIsTemplate(false);
rule.setStatus(RuleStatus.REMOVED);
dbTester.rules().update(rule);
dbSession.commit();
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", rule.getKey())
.setName("My custom")
.setMarkdownDescription("Some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY);
List<NewCustomRule> newRules = singletonList(newRule);
assertThatThrownBy(() -> underTest.create(dbSession, newRules))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The template key doesn't exist: java:S001");
}
@Test
public void fail_to_create_custom_rule_with_invalid_parameter() {
// insert template rule
RuleDto templateRule = createTemplateRuleWithIntArrayParam();
assertThatThrownBy(() -> {
// Create custom rule
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setMarkdownDescription("Some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY)
.setParameters(ImmutableMap.of("myIntegers", "1,polop,2"));
underTest.create(dbSession, newRule);
})
.isInstanceOf(BadRequestException.class)
.hasMessage("Value 'polop' must be an integer.");
}
@Test
public void fail_to_create_custom_rule_with_invalid_parameters() {
// insert template rule
RuleDto templateRule = createTemplateRuleWithTwoIntParams();
// Create custom rule
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setMarkdownDescription("Some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY)
.setParameters(ImmutableMap.of("first", "polop", "second", "palap"));
try {
underTest.create(dbSession, newRule);
Fail.failBecauseExceptionWasNotThrown(BadRequestException.class);
} catch (BadRequestException badRequest) {
assertThat(badRequest.errors().toString()).contains("palap").contains("polop");
}
}
@Test
public void fail_to_create_custom_rule_with_empty_description() {
// insert template rule
RuleDto templateRule = createTemplateRuleWithTwoIntParams();
// Create custom rule
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setMarkdownDescription("Some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY)
.setMarkdownDescription("");
assertThatExceptionOfType(BadRequestException.class)
.isThrownBy(() -> underTest.create(dbSession, newRule))
.withMessage("The description is missing");
}
@Test
public void reactivate_custom_rule_if_already_exists_in_removed_status() {
String key = "CUSTOM_RULE";
RuleDto templateRule = createTemplateRule();
RuleDto rule = newCustomRule(templateRule, "Old description")
.setRuleKey(key)
.setStatus(RuleStatus.REMOVED)
.setName("Old name")
.setDescriptionFormat(Format.MARKDOWN)
.setSeverity(Severity.INFO);
dbTester.rules().insert(rule);
dbTester.rules().insertRuleParam(rule, param -> param.setDefaultValue("a.*"));
dbSession.commit();
// Create custom rule with same key, but with different values
NewCustomRule newRule = NewCustomRule.createForCustomRule(key, templateRule.getKey())
.setName("New name")
.setMarkdownDescription("New description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY)
.setParameters(ImmutableMap.of("regex", "c.*"));
RuleKey customRuleKey = underTest.create(dbSession, newRule);
RuleDto result = dbTester.getDbClient().ruleDao().selectOrFailByKey(dbSession, customRuleKey);
assertThat(result.getKey()).isEqualTo(RuleKey.of("java", key));
assertThat(result.getStatus()).isEqualTo(RuleStatus.READY);
// These values should be the same than before
assertThat(result.getName()).isEqualTo("Old name");
assertThat(result.getDefaultRuleDescriptionSection().getContent()).isEqualTo("Old description");
assertThat(result.getSeverityString()).isEqualTo(Severity.INFO);
List<RuleParamDto> params = dbTester.getDbClient().ruleDao().selectRuleParamsByRuleKey(dbSession, customRuleKey);
assertThat(params).hasSize(1);
assertThat(params.get(0).getDefaultValue()).isEqualTo("a.*");
}
@Test
public void generate_reactivation_exception_when_rule_exists_in_removed_status_and_prevent_reactivation_parameter_is_true() {
String key = "CUSTOM_RULE";
RuleDto templateRule = createTemplateRule();
RuleDto rule = newCustomRule(templateRule, "Old description")
.setRuleKey(key)
.setStatus(RuleStatus.REMOVED)
.setName("Old name")
.setSeverity(Severity.INFO);
dbTester.rules().insert(rule);
dbTester.rules().insertRuleParam(rule, param -> param.setDefaultValue("a.*"));
dbSession.commit();
// Create custom rule with same key, but with different values
NewCustomRule newRule = NewCustomRule.createForCustomRule(key, templateRule.getKey())
.setName("New name")
.setMarkdownDescription("some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY)
.setParameters(ImmutableMap.of("regex", "c.*"))
.setPreventReactivation(true);
try {
underTest.create(dbSession, newRule);
fail();
} catch (Exception e) {
assertThat(e).isInstanceOf(ReactivationException.class);
ReactivationException reactivationException = (ReactivationException) e;
assertThat(reactivationException.ruleKey()).isEqualTo(rule.getKey());
}
}
@Test
public void fail_to_create_custom_rule_when_invalid_key() {
// insert template rule
RuleDto templateRule = createTemplateRule();
NewCustomRule newRule = NewCustomRule.createForCustomRule("*INVALID*", templateRule.getKey())
.setName("My custom")
.setMarkdownDescription("some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY)
.setParameters(ImmutableMap.of("regex", "a.*"));
assertThatThrownBy(() -> underTest.create(dbSession, newRule))
.isInstanceOf(BadRequestException.class)
.hasMessage("The rule key \"*INVALID*\" is invalid, it should only contain: a-z, 0-9, \"_\"");
}
@Test
public void fail_to_create_custom_rule_when_rule_key_already_exists() {
// insert template rule
RuleDto templateRule = createTemplateRule();
// Create a custom rule
AtomicReference<NewCustomRule> newRule = new AtomicReference<>(NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setMarkdownDescription("some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY)
.setParameters(ImmutableMap.of("regex", "a.*")));
underTest.create(dbSession, newRule.get());
// Create another custom rule having same key
newRule.set(NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My another custom")
.setMarkdownDescription("some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY)
.setParameters(ImmutableMap.of("regex", "a.*")));
assertThatThrownBy(() -> underTest.create(dbSession, newRule.get()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("A rule with the key 'CUSTOM_RULE' already exists");
}
@Test
public void fail_to_create_custom_rule_when_missing_name() {
// insert template rule
RuleDto templateRule = createTemplateRule();
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setMarkdownDescription("some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY)
.setParameters(ImmutableMap.of("regex", "a.*"));
assertThatThrownBy(() -> underTest.create(dbSession, newRule))
.isInstanceOf(BadRequestException.class)
.hasMessage("The name is missing");
}
@Test
public void fail_to_create_custom_rule_when_missing_description() {
// insert template rule
RuleDto templateRule = createTemplateRule();
assertThatThrownBy(() -> {
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY)
.setParameters(ImmutableMap.of("regex", "a.*"));
underTest.create(dbSession, newRule);
})
.isInstanceOf(BadRequestException.class)
.hasMessage("The description is missing");
}
@Test
public void fail_to_create_custom_rule_when_missing_severity() {
// insert template rule
RuleDto templateRule = createTemplateRule();
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setMarkdownDescription("some description")
.setStatus(RuleStatus.READY)
.setParameters(ImmutableMap.of("regex", "a.*"));
assertThatThrownBy(() -> underTest.create(dbSession, newRule))
.isInstanceOf(BadRequestException.class)
.hasMessage("The severity is missing");
}
@Test
public void fail_to_create_custom_rule_when_invalid_severity() {
// insert template rule
RuleDto templateRule = createTemplateRule();
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setMarkdownDescription("some description")
.setSeverity("INVALID")
.setStatus(RuleStatus.READY)
.setParameters(ImmutableMap.of("regex", "a.*"));
assertThatThrownBy(() -> underTest.create(dbSession, newRule))
.isInstanceOf(BadRequestException.class)
.hasMessage("Severity \"INVALID\" is invalid");
}
@Test
public void fail_to_create_custom_rule_when_missing_status() {
// insert template rule
RuleDto templateRule = createTemplateRule();
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey())
.setName("My custom")
.setMarkdownDescription("some description")
.setSeverity(Severity.MAJOR)
.setParameters(ImmutableMap.of("regex", "a.*"));
assertThatThrownBy(() -> underTest.create(dbSession, newRule))
.isInstanceOf(BadRequestException.class)
.hasMessage("The status is missing");
}
@Test
public void fail_to_create_custom_rule_when_wrong_rule_template() {
// insert rule
RuleDto rule = newRule(RuleKey.of("java", "S001")).setIsTemplate(false);
dbTester.rules().insert(rule);
dbSession.commit();
// Create custom rule with unknown template rule
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", rule.getKey())
.setName("My custom")
.setMarkdownDescription("some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY)
.setParameters(ImmutableMap.of("regex", "a.*"));
assertThatThrownBy(() -> underTest.create(dbSession, newRule))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("This rule is not a template rule: java:S001");
}
@Test
public void fail_to_create_custom_rule_when_null_template() {
assertThatThrownBy(() -> {
// Create custom rule
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", null)
.setName("My custom")
.setMarkdownDescription("Some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY);
underTest.create(dbSession, newRule);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Template key should be set");
}
@Test
public void fail_to_create_custom_rule_when_unknown_template() {
assertThatThrownBy(() -> {
// Create custom rule
NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", RuleKey.of("java", "S001"))
.setName("My custom")
.setMarkdownDescription("Some description")
.setSeverity(Severity.MAJOR)
.setStatus(RuleStatus.READY);
underTest.create(dbSession, newRule);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The template key doesn't exist: java:S001");
}
private RuleDto createTemplateRule() {
RuleDto templateRule = RuleTesting.newRule(RuleKey.of("java", "S001"))
.setIsTemplate(true)
.setLanguage("java")
.setPluginKey("sonarjava")
.setConfigKey("S001")
.setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name())
.setDefRemediationGapMultiplier("1h")
.setDefRemediationBaseEffort("5min")
.setGapDescription("desc")
.setTags(Sets.newHashSet("usertag1", "usertag2"))
.setSystemTags(Sets.newHashSet("tag1", "tag4"))
.setSecurityStandards(Sets.newHashSet("owaspTop10:a1", "cwe:123"))
.setCreatedAt(new Date().getTime())
.setUpdatedAt(new Date().getTime());
dbTester.rules().insert(templateRule);
dbTester.rules().insertRuleParam(templateRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(".*"));
ruleIndexer.commitAndIndex(dbTester.getSession(), templateRule.getUuid());
return templateRule;
}
private RuleDto createTemplateRuleWithIntArrayParam() {
RuleDto templateRule = newRule(RuleKey.of("java", "S002"))
.setIsTemplate(true)
.setLanguage("java")
.setConfigKey("S002")
.setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name())
.setDefRemediationGapMultiplier("1h")
.setDefRemediationBaseEffort("5min")
.setGapDescription("desc")
.setCreatedAt(new Date().getTime())
.setUpdatedAt(new Date().getTime());
dbTester.rules().insert(templateRule);
dbTester.rules().insertRuleParam(templateRule,
param -> param.setName("myIntegers").setType("INTEGER,multiple=true,values=1;2;3").setDescription("My Integers").setDefaultValue("1"));
ruleIndexer.commitAndIndex(dbTester.getSession(), templateRule.getUuid());
return templateRule;
}
private RuleDto createTemplateRuleWithTwoIntParams() {
RuleDto templateRule = newRule(RuleKey.of("java", "S003"))
.setIsTemplate(true)
.setLanguage("java")
.setConfigKey("S003")
.setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name())
.setDefRemediationGapMultiplier("1h")
.setDefRemediationBaseEffort("5min")
.setGapDescription("desc")
.setCreatedAt(new Date().getTime())
.setUpdatedAt(new Date().getTime());
dbTester.rules().insert(templateRule);
dbTester.rules().insertRuleParam(templateRule, param -> param.setName("first").setType("INTEGER").setDescription("First integer").setDefaultValue("0"));
dbTester.rules().insertRuleParam(templateRule, param -> param.setName("second").setType("INTEGER").setDescription("Second integer").setDefaultValue("0"));
return templateRule;
}
}
| 25,577 | 40.254839 | 182 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/rule/RuleUpdaterIT.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 com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import org.sonar.api.server.debt.DebtRemediationFunction;
import org.sonar.api.server.debt.internal.DefaultDebtRemediationFunction;
import org.sonar.api.utils.System2;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.ActiveRuleKey;
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.QualityProfileTesting;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.rule.index.RuleIndex;
import org.sonar.server.rule.index.RuleIndexer;
import org.sonar.server.rule.index.RuleQuery;
import org.sonar.server.tester.UserSessionRule;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.rule.Severity.CRITICAL;
import static org.sonar.db.rule.RuleTesting.newCustomRule;
import static org.sonar.db.rule.RuleTesting.newRule;
import static org.sonar.db.rule.RuleTesting.newTemplateRule;
import static org.sonar.server.rule.RuleUpdate.createForCustomRule;
import static org.sonar.server.rule.RuleUpdate.createForPluginRule;
public class RuleUpdaterIT {
static final RuleKey RULE_KEY = RuleKey.of("java", "S001");
private final System2 system2 = new TestSystem2().setNow(Instant.now().toEpochMilli());
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create(system2);
@Rule
public EsTester es = EsTester.create();
private final RuleIndex ruleIndex = new RuleIndex(es.client(), system2);
private final RuleIndexer ruleIndexer = new RuleIndexer(es.client(), db.getDbClient());
private final DbSession dbSession = db.getSession();
private final UuidFactoryFast uuidFactory = UuidFactoryFast.getInstance();
private final RuleUpdater underTest = new RuleUpdater(db.getDbClient(), ruleIndexer, uuidFactory, system2);
@Test
public void do_not_update_rule_with_removed_status() {
db.rules().insert(newRule(RULE_KEY).setStatus(RuleStatus.REMOVED));
dbSession.commit();
RuleUpdate update = createForPluginRule(RULE_KEY)
.setTags(Sets.newHashSet("java9"));
assertThatThrownBy(() -> {
underTest.update(dbSession, update, userSessionRule);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Rule with REMOVED status cannot be updated: java:S001");
}
@Test
public void no_changes() {
RuleDto ruleDto = RuleTesting.newRule(RULE_KEY)
// the following fields are not supposed to be updated
.setNoteData("my *note*")
.setNoteUserUuid("me")
.setTags(ImmutableSet.of("tag1"))
.setRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE.name())
.setRemediationGapMultiplier("1d")
.setRemediationBaseEffort("5min");
db.rules().insert(ruleDto);
dbSession.commit();
RuleUpdate update = createForPluginRule(RULE_KEY);
assertThat(update.isEmpty()).isTrue();
underTest.update(dbSession, update, userSessionRule);
dbSession.clearCache();
RuleDto rule = db.getDbClient().ruleDao().selectOrFailByKey(dbSession, RULE_KEY);
assertThat(rule.getNoteData()).isEqualTo("my *note*");
assertThat(rule.getNoteUserUuid()).isEqualTo("me");
assertThat(rule.getTags()).containsOnly("tag1");
assertThat(rule.getRemediationFunction()).isEqualTo(DebtRemediationFunction.Type.CONSTANT_ISSUE.name());
assertThat(rule.getRemediationGapMultiplier()).isEqualTo("1d");
assertThat(rule.getRemediationBaseEffort()).isEqualTo("5min");
}
@Test
public void set_markdown_note() {
UserDto user = db.users().insertUser();
userSessionRule.logIn(user);
RuleDto ruleDto = RuleTesting.newRule(RULE_KEY)
.setNoteData(null)
.setNoteUserUuid(null)
// the following fields are not supposed to be updated
.setTags(ImmutableSet.of("tag1"))
.setRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE.name())
.setRemediationGapMultiplier("1d")
.setRemediationBaseEffort("5min");
db.rules().insert(ruleDto);
dbSession.commit();
RuleUpdate update = createForPluginRule(RULE_KEY)
.setMarkdownNote("my *note*");
underTest.update(dbSession, update, userSessionRule);
dbSession.clearCache();
RuleDto rule = db.getDbClient().ruleDao().selectOrFailByKey(dbSession, RULE_KEY);
assertThat(rule.getNoteData()).isEqualTo("my *note*");
assertThat(rule.getNoteUserUuid()).isEqualTo(user.getUuid());
assertThat(rule.getNoteCreatedAt()).isNotNull();
assertThat(rule.getNoteUpdatedAt()).isNotNull();
// no other changes
assertThat(rule.getTags()).containsOnly("tag1");
assertThat(rule.getRemediationFunction()).isEqualTo(DebtRemediationFunction.Type.CONSTANT_ISSUE.name());
assertThat(rule.getRemediationGapMultiplier()).isEqualTo("1d");
assertThat(rule.getRemediationBaseEffort()).isEqualTo("5min");
}
@Test
public void remove_markdown_note() {
RuleDto ruleDto = RuleTesting.newRule(RULE_KEY)
.setNoteData("my *note*")
.setNoteUserUuid("me");
db.rules().insert(ruleDto);
dbSession.commit();
RuleUpdate update = createForPluginRule(RULE_KEY)
.setMarkdownNote(null);
underTest.update(dbSession, update, userSessionRule);
dbSession.clearCache();
RuleDto rule = db.getDbClient().ruleDao().selectOrFailByKey(dbSession, RULE_KEY);
assertThat(rule.getNoteData()).isNull();
assertThat(rule.getNoteUserUuid()).isNull();
assertThat(rule.getNoteCreatedAt()).isNull();
assertThat(rule.getNoteUpdatedAt()).isNull();
}
@Test
public void set_tags() {
// insert db
db.rules().insert(RuleTesting.newRule(RULE_KEY)
.setTags(Sets.newHashSet("security"))
.setSystemTags(Sets.newHashSet("java8", "javadoc")));
dbSession.commit();
// java8 is a system tag -> ignore
RuleUpdate update = createForPluginRule(RULE_KEY)
.setTags(Sets.newHashSet("bug", "java8"));
underTest.update(dbSession, update, userSessionRule);
RuleDto rule = db.getDbClient().ruleDao().selectOrFailByKey(dbSession, RULE_KEY);
assertThat(rule.getTags()).containsOnly("bug");
assertThat(rule.getSystemTags()).containsOnly("java8", "javadoc");
// verify that tags are indexed in index
List<String> tags = ruleIndex.listTags(null, 10);
assertThat(tags).containsExactly("bug", "java8", "javadoc");
}
@Test
public void remove_tags() {
RuleDto ruleDto = RuleTesting.newRule(RULE_KEY)
.setUuid("57a3af91-32f8-48b0-9e11-0eac14ffa915")
.setTags(Sets.newHashSet("security"))
.setSystemTags(Sets.newHashSet("java8", "javadoc"));
db.rules().insert(ruleDto);
dbSession.commit();
RuleUpdate update = createForPluginRule(RULE_KEY)
.setTags(null);
underTest.update(dbSession, update, userSessionRule);
dbSession.clearCache();
RuleDto rule = db.getDbClient().ruleDao().selectOrFailByKey(dbSession, RULE_KEY);
assertThat(rule.getTags()).isEmpty();
assertThat(rule.getSystemTags()).containsOnly("java8", "javadoc");
// verify that tags are indexed in index
List<String> tags = ruleIndex.listTags(null, 10);
assertThat(tags).containsExactly("java8", "javadoc");
}
@Test
public void override_debt() {
db.rules().insert(newRule(RULE_KEY)
.setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name())
.setDefRemediationGapMultiplier("1d")
.setDefRemediationBaseEffort("5min"));
dbSession.commit();
DefaultDebtRemediationFunction fn = new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE, null, "1min");
RuleUpdate update = createForPluginRule(RULE_KEY)
.setDebtRemediationFunction(fn);
underTest.update(dbSession, update, userSessionRule);
dbSession.clearCache();
// verify debt is overridden
RuleDto rule = db.getDbClient().ruleDao().selectOrFailByKey(dbSession, RULE_KEY);
assertThat(rule.getRemediationFunction()).isEqualTo(DebtRemediationFunction.Type.CONSTANT_ISSUE.name());
assertThat(rule.getRemediationGapMultiplier()).isNull();
assertThat(rule.getRemediationBaseEffort()).isEqualTo("1min");
assertThat(rule.getDefRemediationFunction()).isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET.name());
assertThat(rule.getDefRemediationGapMultiplier()).isEqualTo("1d");
assertThat(rule.getDefRemediationBaseEffort()).isEqualTo("5min");
}
@Test
public void override_debt_only_offset() {
db.rules().insert(newRule(RULE_KEY)
.setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR.name())
.setDefRemediationGapMultiplier("1d")
.setDefRemediationBaseEffort(null));
dbSession.commit();
RuleUpdate update = createForPluginRule(RULE_KEY)
.setDebtRemediationFunction(new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.LINEAR, "2d", null));
underTest.update(dbSession, update, userSessionRule);
dbSession.clearCache();
// verify debt is overridden
RuleDto rule = db.getDbClient().ruleDao().selectOrFailByKey(dbSession, RULE_KEY);
assertThat(rule.getRemediationFunction()).isEqualTo(DebtRemediationFunction.Type.LINEAR.name());
assertThat(rule.getRemediationGapMultiplier()).isEqualTo("2d");
assertThat(rule.getRemediationBaseEffort()).isNull();
assertThat(rule.getDefRemediationFunction()).isEqualTo(DebtRemediationFunction.Type.LINEAR.name());
assertThat(rule.getDefRemediationGapMultiplier()).isEqualTo("1d");
assertThat(rule.getDefRemediationBaseEffort()).isNull();
}
@Test
public void override_debt_from_linear_with_offset_to_constant() {
db.rules().insert(newRule(RULE_KEY)
.setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name())
.setDefRemediationGapMultiplier("1d")
.setDefRemediationBaseEffort("5min"));
dbSession.commit();
RuleUpdate update = createForPluginRule(RULE_KEY)
.setDebtRemediationFunction(new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE, null, "10min"));
underTest.update(dbSession, update, userSessionRule);
dbSession.clearCache();
// verify debt is overridden
RuleDto rule = db.getDbClient().ruleDao().selectOrFailByKey(dbSession, RULE_KEY);
assertThat(rule.getRemediationFunction()).isEqualTo(DebtRemediationFunction.Type.CONSTANT_ISSUE.name());
assertThat(rule.getRemediationGapMultiplier()).isNull();
assertThat(rule.getRemediationBaseEffort()).isEqualTo("10min");
assertThat(rule.getDefRemediationFunction()).isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET.name());
assertThat(rule.getDefRemediationGapMultiplier()).isEqualTo("1d");
assertThat(rule.getDefRemediationBaseEffort()).isEqualTo("5min");
}
@Test
public void reset_remediation_function() {
RuleDto ruleDto = RuleTesting.newRule(RULE_KEY)
.setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR.name())
.setDefRemediationGapMultiplier("1d")
.setDefRemediationBaseEffort("5min")
.setRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE.name())
.setRemediationGapMultiplier(null)
.setRemediationBaseEffort("1min");
db.rules().insert(ruleDto);
dbSession.commit();
RuleUpdate update = createForPluginRule(RULE_KEY)
.setDebtRemediationFunction(null);
underTest.update(dbSession, update, userSessionRule);
dbSession.clearCache();
// verify debt is coming from default values
RuleDto rule = db.getDbClient().ruleDao().selectOrFailByKey(dbSession, RULE_KEY);
assertThat(rule.getDefRemediationFunction()).isEqualTo(DebtRemediationFunction.Type.LINEAR.name());
assertThat(rule.getDefRemediationGapMultiplier()).isEqualTo("1d");
assertThat(rule.getDefRemediationBaseEffort()).isEqualTo("5min");
assertThat(rule.getRemediationFunction()).isNull();
assertThat(rule.getRemediationGapMultiplier()).isNull();
assertThat(rule.getRemediationBaseEffort()).isNull();
}
@Test
public void update_custom_rule() {
RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001"));
db.rules().insert(templateRule);
db.rules().insertRuleParam(templateRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(".*"));
db.rules().insertRuleParam(templateRule, param -> param.setName("format").setType("STRING").setDescription("Format"));
RuleDto customRule = newCustomRule(templateRule, "Old description")
.setName("Old name")
.setSeverity(Severity.MINOR)
.setStatus(RuleStatus.BETA);
db.rules().insert(customRule);
db.rules().insertRuleParam(customRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue("a.*"));
db.rules().insertRuleParam(customRule, param -> param.setName("format").setType("STRING").setDescription("Format").setDefaultValue(null));
// Update custom rule
RuleUpdate update = createForCustomRule(customRule.getKey())
.setName("New name")
.setMarkdownDescription("New description")
.setSeverity("MAJOR")
.setStatus(RuleStatus.READY)
.setParameters(ImmutableMap.of("regex", "b.*"));
underTest.update(dbSession, update, userSessionRule);
dbSession.clearCache();
// Verify custom rule is updated
RuleDto customRuleReloaded = db.getDbClient().ruleDao().selectOrFailByKey(dbSession, customRule.getKey());
assertThat(customRuleReloaded).isNotNull();
assertThat(customRuleReloaded.getName()).isEqualTo("New name");
assertThat(customRuleReloaded.getDefaultRuleDescriptionSection().getContent()).isEqualTo("New description");
assertThat(customRuleReloaded.getSeverityString()).isEqualTo("MAJOR");
assertThat(customRuleReloaded.getStatus()).isEqualTo(RuleStatus.READY);
List<RuleParamDto> params = db.getDbClient().ruleDao().selectRuleParamsByRuleKey(dbSession, customRuleReloaded.getKey());
assertThat(params).extracting(RuleParamDto::getDefaultValue).containsOnly("b.*", null);
// Verify in index
assertThat(ruleIndex.search(new RuleQuery().setQueryText("New name"), new SearchOptions()).getUuids()).containsOnly(customRule.getUuid());
assertThat(ruleIndex.search(new RuleQuery().setQueryText("New description"), new SearchOptions()).getUuids()).containsOnly(customRule.getUuid());
assertThat(ruleIndex.search(new RuleQuery().setQueryText("Old name"), new SearchOptions()).getTotal()).isZero();
assertThat(ruleIndex.search(new RuleQuery().setQueryText("Old description"), new SearchOptions()).getTotal()).isZero();
}
@Test
public void update_custom_rule_with_empty_parameter() {
RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001"));
db.rules().insert(templateRule);
db.rules().insertRuleParam(templateRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(null));
RuleDto customRule = newCustomRule(templateRule, "Old description")
.setName("Old name")
.setSeverity(Severity.MINOR)
.setStatus(RuleStatus.BETA);
db.rules().insert(customRule);
db.rules().insertRuleParam(customRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(null));
dbSession.commit();
// Update custom rule without setting a value for the parameter
RuleUpdate update = createForCustomRule(customRule.getKey())
.setName("New name")
.setMarkdownDescription("New description")
.setSeverity("MAJOR")
.setStatus(RuleStatus.READY);
underTest.update(dbSession, update, userSessionRule);
dbSession.clearCache();
// Verify custom rule is updated
List<RuleParamDto> params = db.getDbClient().ruleDao().selectRuleParamsByRuleKey(dbSession, customRule.getKey());
assertThat(params.get(0).getDefaultValue()).isNull();
}
@Test
public void update_active_rule_parameters_when_updating_custom_rule() {
// Create template rule with 3 parameters
RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001")).setLanguage("xoo");
RuleDto templateRuleDefinition = templateRule;
db.rules().insert(templateRuleDefinition);
db.rules().insertRuleParam(templateRuleDefinition, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(".*"));
db.rules().insertRuleParam(templateRuleDefinition, param -> param.setName("format").setType("STRING").setDescription("format").setDefaultValue("csv"));
db.rules().insertRuleParam(templateRuleDefinition, param -> param.setName("message").setType("STRING").setDescription("message"));
// Create custom rule
RuleDto customRule = newCustomRule(templateRule)
.setSeverity(Severity.MAJOR)
.setLanguage("xoo");
db.rules().insert(customRule);
RuleParamDto ruleParam1 = db.rules().insertRuleParam(customRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue("a.*"));
db.rules().insertRuleParam(customRule, param -> param.setName("format").setType("STRING").setDescription("format").setDefaultValue("txt"));
db.rules().insertRuleParam(customRule, param -> param.setName("message").setType("STRING").setDescription("message"));
// Create a quality profile
QProfileDto profileDto = QualityProfileTesting.newQualityProfileDto();
db.getDbClient().qualityProfileDao().insert(dbSession, profileDto);
dbSession.commit();
// Activate the custom rule
ActiveRuleDto activeRuleDto = new ActiveRuleDto()
.setProfileUuid(profileDto.getRulesProfileUuid())
.setRuleUuid(customRule.getUuid())
.setSeverity(Severity.BLOCKER);
db.getDbClient().activeRuleDao().insert(dbSession, activeRuleDto);
db.getDbClient().activeRuleDao().insertParam(dbSession, activeRuleDto, new ActiveRuleParamDto()
.setActiveRuleUuid(activeRuleDto.getUuid())
.setRulesParameterUuid(ruleParam1.getUuid())
.setKey(ruleParam1.getName())
.setValue(ruleParam1.getDefaultValue()));
dbSession.commit();
// Update custom rule parameter 'regex', add 'message' and remove 'format'
RuleUpdate update = createForCustomRule(customRule.getKey())
.setParameters(ImmutableMap.of("regex", "b.*", "message", "a message"));
underTest.update(dbSession, update, userSessionRule);
// Verify custom rule parameters has been updated
List<RuleParamDto> params = db.getDbClient().ruleDao().selectRuleParamsByRuleKey(dbSession, customRule.getKey());
assertThat(params).hasSize(3);
Map<String, RuleParamDto> paramsByKey = paramsByName(params);
assertThat(paramsByKey.get("regex")).isNotNull();
assertThat(paramsByKey.get("regex").getDefaultValue()).isEqualTo("b.*");
assertThat(paramsByKey.get("message")).isNotNull();
assertThat(paramsByKey.get("message").getDefaultValue()).isEqualTo("a message");
assertThat(paramsByKey.get("format")).isNotNull();
assertThat(paramsByKey.get("format").getDefaultValue()).isNull();
// Verify that severity has not changed
ActiveRuleDto activeRuleReloaded = db.getDbClient().activeRuleDao().selectByKey(dbSession, ActiveRuleKey.of(profileDto, customRule.getKey())).get();
assertThat(activeRuleReloaded.getSeverityString()).isEqualTo(Severity.BLOCKER);
// Verify active rule parameters has been updated
List<ActiveRuleParamDto> activeRuleParams = db.getDbClient().activeRuleDao().selectParamsByActiveRuleUuid(dbSession, activeRuleReloaded.getUuid());
assertThat(activeRuleParams).hasSize(2);
Map<String, ActiveRuleParamDto> activeRuleParamsByKey = ActiveRuleParamDto.groupByKey(activeRuleParams);
assertThat(activeRuleParamsByKey.get("regex").getValue()).isEqualTo("b.*");
assertThat(activeRuleParamsByKey.get("message").getValue()).isEqualTo("a message");
assertThat(activeRuleParamsByKey.get("format")).isNull();
}
@Test
public void fail_to_update_custom_rule_when_empty_name() {
// Create template rule
RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001"));
db.rules().insert(templateRule);
// Create custom rule
RuleDto customRule = newCustomRule(templateRule);
db.rules().insert(customRule);
dbSession.commit();
// Update custom rule
RuleUpdate update = createForCustomRule(customRule.getKey())
.setName("")
.setMarkdownDescription("New desc");
assertThatThrownBy(() -> {
underTest.update(dbSession, update, userSessionRule);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The name is missing");
}
@Test
public void fail_to_update_custom_rule_when_empty_description() {
// Create template rule
RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001"));
db.rules().insert(templateRule);
// Create custom rule
RuleDto customRule = newCustomRule(templateRule);
db.rules().insert(customRule);
dbSession.commit();
assertThatThrownBy(() -> {
underTest.update(dbSession,
createForCustomRule(customRule.getKey()).setName("New name").setMarkdownDescription(""),
userSessionRule);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The description is missing");
}
@Test
public void fail_to_update_plugin_rule_if_name_is_set() {
RuleDto ruleDto = db.rules().insert(newRule(RuleKey.of("java", "S01")));
dbSession.commit();
assertThatThrownBy(() -> {
createForPluginRule(ruleDto.getKey()).setName("New name");
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Not a custom rule");
}
@Test
public void fail_to_update_plugin_rule_if_description_is_set() {
RuleDto ruleDto = db.rules().insert(newRule(RuleKey.of("java", "S01")));
dbSession.commit();
assertThatThrownBy(() -> {
createForPluginRule(ruleDto.getKey()).setMarkdownDescription("New description");
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Not a custom rule");
}
@Test
public void fail_to_update_plugin_rule_if_severity_is_set() {
RuleDto ruleDto = db.rules().insert(newRule(RuleKey.of("java", "S01")));
dbSession.commit();
assertThatThrownBy(() -> {
createForPluginRule(ruleDto.getKey()).setSeverity(CRITICAL);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Not a custom rule");
}
private static Map<String, RuleParamDto> paramsByName(List<RuleParamDto> params) {
return params.stream().collect(Collectors.toMap(RuleParamDto::getName, p -> p));
}
}
| 24,201 | 42.29517 | 168 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/rule/ws/ActiveRuleCompleterIT.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.ws;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Languages;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.rule.RuleDto;
import org.sonarqube.ws.Rules;
import static org.assertj.core.api.Assertions.assertThat;
public class ActiveRuleCompleterIT {
@Rule
public DbTester dbTester = DbTester.create();
@Test
public void test_completeShow() {
ActiveRuleCompleter underTest = new ActiveRuleCompleter(dbTester.getDbClient(), new Languages());
RuleDto rule = dbTester.rules().insert();
QProfileDto qualityProfile = dbTester.qualityProfiles().insert();
ActiveRuleDto activeRule = dbTester.qualityProfiles().activateRule(qualityProfile, rule);
List<Rules.Active> result = underTest.completeShow(dbTester.getSession(), rule);
assertThat(result).extracting(Rules.Active::getQProfile).containsExactlyInAnyOrder(qualityProfile.getKee());
assertThat(result).extracting(Rules.Active::getSeverity).containsExactlyInAnyOrder(activeRule.getSeverityString());
}
}
| 2,019 | 37.846154 | 119 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/rule/ws/AppActionIT.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.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.rule.RuleRepositoryDto;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsActionTester;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.test.JsonAssert.assertJson;
public class AppActionIT {
private static final Language LANG1 = LanguageTesting.newLanguage("xoo", "Xoo");
private static final Language LANG2 = LanguageTesting.newLanguage("ws", "Whitespace");
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private Languages languages = new Languages(LANG1, LANG2);
private AppAction underTest = new AppAction(languages, db.getDbClient(), userSession);
private WsActionTester ws = new WsActionTester(underTest);
@Test
public void test_definition() {
WebService.Action definition = ws.getDef();
assertThat(definition.isInternal()).isTrue();
assertThat(definition.key()).isEqualTo("app");
assertThat(definition.params()).isEmpty();
}
@Test
public void response_contains_rule_repositories() {
insertRules();
String json = ws.newRequest().execute().getInput();
assertJson(json).isSimilarTo("{" +
"\"repositories\": [" +
" {" +
" \"key\": \"xoo\"," +
" \"name\": \"SonarQube\"," +
" \"language\": \"xoo\"" +
" }," +
" {" +
" \"key\": \"java\"," +
" \"name\": \"SonarQube\"," +
" \"language\": \"ws\"" +
" }" +
" ]" +
"}");
}
@Test
public void response_contains_languages() {
String json = ws.newRequest().execute().getInput();
assertJson(json).isSimilarTo("{" +
"\"languages\": {" +
" \"xoo\": \"Xoo\"," +
" \"ws\": \"Whitespace\"" +
" }" +
"}");
}
@Test
public void canWrite_is_true_if_user_is_profile_administrator() {
userSession.addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES);
String json = ws.newRequest().execute().getInput();
assertJson(json).isSimilarTo("{ \"canWrite\": true }");
}
@Test
public void canWrite_is_false_if_user_is_not_profile_administrator() {
userSession.addPermission(GlobalPermission.SCAN);
String json = ws.newRequest().execute().getInput();
assertJson(json).isSimilarTo("{ \"canWrite\": false }");
}
private void insertRules() {
RuleRepositoryDto repo1 = new RuleRepositoryDto("xoo", "xoo", "SonarQube");
RuleRepositoryDto repo2 = new RuleRepositoryDto("java", "ws", "SonarQube");
db.getDbClient().ruleRepositoryDao().insert(db.getSession(), asList(repo1, repo2));
db.getSession().commit();
}
}
| 3,958 | 31.991667 | 88 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/rule/ws/CreateActionIT.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.ws;
import java.util.Set;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Languages;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import org.sonar.api.utils.System2;
import org.sonar.core.util.SequenceUuidFactory;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbTester;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.rule.RuleCreator;
import org.sonar.server.rule.RuleDescriptionFormatter;
import org.sonar.server.rule.index.RuleIndexer;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.text.MacroInterpreter;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.sonar.api.rules.RuleType.BUG;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
import static org.sonar.db.rule.RuleTesting.newCustomRule;
import static org.sonar.db.rule.RuleTesting.newTemplateRule;
import static org.sonar.server.util.TypeValidationsTesting.newFullTypeValidations;
import static org.sonar.test.JsonAssert.assertJson;
public class CreateActionIT {
private final System2 system2 = mock(System2.class);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create(system2);
@Rule
public EsTester es = EsTester.create();
private final UuidFactory uuidFactory = new SequenceUuidFactory();
private final WsActionTester ws = new WsActionTester(new CreateAction(db.getDbClient(),
new RuleCreator(system2, new RuleIndexer(es.client(), db.getDbClient()), db.getDbClient(), newFullTypeValidations(), uuidFactory),
new RuleMapper(new Languages(), createMacroInterpreter(), new RuleDescriptionFormatter()),
new RuleWsSupport(db.getDbClient(), userSession)));
@Test
public void check_definition() {
assertThat(ws.getDef().isPost()).isTrue();
assertThat(ws.getDef().isInternal()).isFalse();
assertThat(ws.getDef().responseExampleAsString()).isNotNull();
assertThat(ws.getDef().description()).isNotNull();
}
@Test
public void create_custom_rule() {
logInAsQProfileAdministrator();
// Template rule
RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001"))
.setType(BUG)
.setTags(Set.of())
.setLanguage("js")
.setSystemTags(Set.of("systag1", "systag2"));
db.rules().insert(templateRule);
db.rules().insertRuleParam(templateRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(".*"));
String result = ws.newRequest()
.setParam("customKey", "MY_CUSTOM")
.setParam("templateKey", templateRule.getKey().toString())
.setParam("name", "My custom rule")
.setParam("markdownDescription", "Description")
.setParam("severity", "MAJOR")
.setParam("status", "BETA")
.setParam("type", BUG.name())
.setParam("params", "regex=a.*")
.execute().getInput();
assertJson(result).isSimilarTo("{\n" +
" \"rule\": {\n" +
" \"key\": \"java:MY_CUSTOM\",\n" +
" \"repo\": \"java\",\n" +
" \"name\": \"My custom rule\",\n" +
" \"htmlDesc\": \"Description\",\n" +
" \"severity\": \"MAJOR\",\n" +
" \"status\": \"BETA\",\n" +
" \"type\": \"BUG\",\n" +
" \"internalKey\": \"configKey_S001\",\n" +
" \"isTemplate\": false,\n" +
" \"templateKey\": \"java:S001\",\n" +
" \"sysTags\": [\"systag1\", \"systag2\"],\n" +
" \"lang\": \"js\",\n" +
" \"params\": [\n" +
" {\n" +
" \"key\": \"regex\",\n" +
" \"htmlDesc\": \"Reg ex\",\n" +
" \"defaultValue\": \"a.*\",\n" +
" \"type\": \"STRING\"\n" +
" }\n" +
" ]\n" +
" }\n" +
"}\n");
}
@Test
public void create_custom_rule_with_preventReactivation_param_to_true() {
logInAsQProfileAdministrator();
RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001"));
db.rules().insert(templateRule);
// insert a removed rule
RuleDto customRule = newCustomRule(templateRule, "Description")
.setRuleKey("MY_CUSTOM")
.setStatus(RuleStatus.REMOVED)
.setName("My custom rule")
.setDescriptionFormat(RuleDto.Format.MARKDOWN)
.setSeverity(Severity.MAJOR);
db.rules().insert(customRule);
TestResponse response = ws.newRequest()
.setParam("customKey", "MY_CUSTOM")
.setParam("templateKey", templateRule.getKey().toString())
.setParam("name", "My custom rule")
.setParam("markdownDescription", "Description")
.setParam("severity", "MAJOR")
.setParam("preventReactivation", "true")
.execute();
assertThat(response.getStatus()).isEqualTo(409);
assertJson(response.getInput()).isSimilarTo("{\n" +
" \"rule\": {\n" +
" \"key\": \"java:MY_CUSTOM\",\n" +
" \"repo\": \"java\",\n" +
" \"name\": \"My custom rule\",\n" +
" \"htmlDesc\": \"Description\",\n" +
" \"severity\": \"MAJOR\",\n" +
" \"status\": \"REMOVED\",\n" +
" \"isTemplate\": false\n" +
" }\n" +
"}\n");
}
@Test
public void create_custom_rule_of_non_existing_template_should_fail() {
logInAsQProfileAdministrator();
TestRequest request = ws.newRequest()
.setParam("customKey", "MY_CUSTOM")
.setParam("templateKey", "non:existing")
.setParam("name", "My custom rule")
.setParam("markdownDescription", "Description")
.setParam("severity", "MAJOR")
.setParam("preventReactivation", "true");
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The template key doesn't exist: non:existing");
}
@Test
public void create_custom_rule_of_removed_template_should_fail() {
logInAsQProfileAdministrator();
RuleDto templateRule = db.rules().insert(r -> r.setIsTemplate(true).setStatus(RuleStatus.REMOVED));
TestRequest request = ws.newRequest()
.setParam("customKey", "MY_CUSTOM")
.setParam("templateKey", templateRule.getKey().toString())
.setParam("name", "My custom rule")
.setParam("markdownDescription", "Description")
.setParam("severity", "MAJOR")
.setParam("preventReactivation", "true");
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The template key doesn't exist: " + templateRule.getKey());
}
@Test
public void throw_IllegalArgumentException_if_status_is_removed() {
logInAsQProfileAdministrator();
RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001"));
TestRequest request = ws.newRequest()
.setParam("customKey", "MY_CUSTOM")
.setParam("templateKey", templateRule.getKey().toString())
.setParam("name", "My custom rule")
.setParam("markdownDescription", "Description")
.setParam("severity", "MAJOR")
.setParam("status", "REMOVED")
.setParam("preventReactivation", "true");
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Value of parameter 'status' (REMOVED) must be one of: [BETA, DEPRECATED, READY]");
}
@Test
public void status_set_to_default() {
logInAsQProfileAdministrator();
RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001"));
db.rules().insert(templateRule);
String result = ws.newRequest()
.setParam("customKey", "MY_CUSTOM")
.setParam("templateKey", templateRule.getKey().toString())
.setParam("name", "My custom rule")
.setParam("markdownDescription", "Description")
.setParam("status", "BETA")
.setParam("type", BUG.name())
.execute().getInput();
assertJson(result).isSimilarTo("{\n" +
" \"rule\": {\n" +
" \"severity\": \"MAJOR\"" +
" }\n" +
"}\n");
}
@Test
public void throw_ForbiddenException_if_not_profile_administrator() {
userSession.logIn();
assertThatThrownBy(() -> ws.newRequest().execute())
.isInstanceOf(ForbiddenException.class);
}
@Test
public void throw_UnauthorizedException_if_not_logged_in() {
assertThatThrownBy(() -> ws.newRequest().execute())
.isInstanceOf(UnauthorizedException.class);
}
private static MacroInterpreter createMacroInterpreter() {
MacroInterpreter macroInterpreter = mock(MacroInterpreter.class);
doAnswer(returnsFirstArg()).when(macroInterpreter).interpret(anyString());
return macroInterpreter;
}
private void logInAsQProfileAdministrator() {
userSession
.logIn()
.addPermission(ADMINISTER_QUALITY_PROFILES);
}
}
| 10,177 | 35.480287 | 143 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/rule/ws/DeleteActionIT.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.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.qualityprofile.QProfileRules;
import org.sonar.server.rule.index.RuleIndexer;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
public class DeleteActionIT {
private static final long PAST = 10000L;
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester dbTester = DbTester.create();
@Rule
public EsTester es = EsTester.create();
private DbClient dbClient = dbTester.getDbClient();
private DbSession dbSession = dbTester.getSession();
private RuleIndexer ruleIndexer = spy(new RuleIndexer(es.client(), dbClient));
private QProfileRules qProfileRules = mock(QProfileRules.class);
private RuleWsSupport ruleWsSupport = new RuleWsSupport(mock(DbClient.class), userSession);
private DeleteAction underTest = new DeleteAction(System2.INSTANCE, ruleIndexer, dbClient, qProfileRules, ruleWsSupport);
private WsActionTester tester = new WsActionTester(underTest);
@Test
public void delete_custom_rule() {
logInAsQProfileAdministrator();
RuleDto templateRule = dbTester.rules().insert(
r -> r.setIsTemplate(true),
r -> r.setCreatedAt(PAST),
r -> r.setUpdatedAt(PAST));
RuleDto customRule = dbTester.rules().insert(
r -> r.setTemplateUuid(templateRule.getUuid()),
r -> r.setCreatedAt(PAST),
r -> r.setUpdatedAt(PAST));
tester.newRequest()
.setMethod("POST")
.setParam("key", customRule.getKey().toString())
.execute();
verify(ruleIndexer).commitAndIndex(any(), eq(customRule.getUuid()));
// Verify custom rule has status REMOVED
RuleDto customRuleReloaded = dbClient.ruleDao().selectOrFailByKey(dbSession, customRule.getKey());
assertThat(customRuleReloaded).isNotNull();
assertThat(customRuleReloaded.getStatus()).isEqualTo(RuleStatus.REMOVED);
assertThat(customRuleReloaded.getUpdatedAt()).isNotEqualTo(PAST);
}
@Test
public void throw_ForbiddenException_if_not_profile_administrator() {
userSession.logIn();
assertThatThrownBy(() -> {
tester.newRequest()
.setMethod("POST")
.setParam("key", "anyRuleKey")
.execute();
})
.isInstanceOf(ForbiddenException.class);
}
@Test
public void throw_UnauthorizedException_if_not_logged_in() {
assertThatThrownBy(() -> {
tester.newRequest()
.setMethod("POST")
.setParam("key", "anyRuleKey")
.execute();
})
.isInstanceOf(UnauthorizedException.class);
}
@Test
public void fail_to_delete_if_not_custom() {
logInAsQProfileAdministrator();
RuleDto rule = dbTester.rules().insert();
assertThatThrownBy(() -> {
tester.newRequest()
.setMethod("POST")
.setParam("key", rule.getKey().toString())
.execute();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Rule '" + rule.getKey().toString() + "' cannot be deleted because it is not a custom rule");
}
private void logInAsQProfileAdministrator() {
userSession
.logIn()
.addPermission(ADMINISTER_QUALITY_PROFILES);
}
}
| 4,832 | 34.536765 | 123 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/rule/ws/ListActionIT.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.ws;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.rule.RuleTesting;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Rules;
import static org.assertj.core.api.Assertions.assertThat;
public class ListActionIT {
private static final String RULE_KEY_1 = "S001";
private static final String RULE_KEY_2 = "S002";
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
ListAction underTest = new ListAction(dbTester.getDbClient());
WsActionTester tester = new WsActionTester(underTest);
@Test
public void define() {
WebService.Action def = tester.getDef();
assertThat(def.params()).isEmpty();
}
@Test
public void return_rules_in_protobuf() {
dbTester.rules().insert(RuleTesting.newRule(RuleKey.of("java", RULE_KEY_1)).setConfigKey(null).setName(null));
dbTester.rules().insert(RuleTesting.newRule(RuleKey.of("java", RULE_KEY_2)).setConfigKey("I002").setName("Rule Two"));
dbTester.getSession().commit();
Rules.ListResponse listResponse = tester.newRequest()
.executeProtobuf(Rules.ListResponse.class);
assertThat(listResponse.getRulesCount()).isEqualTo(2);
Rules.ListResponse.Rule ruleS001 = getRule(listResponse, RULE_KEY_1);
assertThat(ruleS001.getKey()).isEqualTo(RULE_KEY_1);
assertThat(ruleS001.getInternalKey()).isEmpty();
assertThat(ruleS001.getName()).isEmpty();
Rules.ListResponse.Rule ruleS002 = getRule(listResponse, RULE_KEY_2);
assertThat(ruleS002.getKey()).isEqualTo(RULE_KEY_2);
assertThat(ruleS002.getInternalKey()).isEqualTo("I002");
assertThat(ruleS002.getName()).isEqualTo("Rule Two");
}
private Rules.ListResponse.Rule getRule(Rules.ListResponse listResponse, String ruleKey) {
Optional<Rules.ListResponse.Rule> rule = listResponse.getRulesList().stream()
.filter(r -> ruleKey.equals(r.getKey()))
.findFirst();
assertThat(rule).isPresent();
return rule.get();
}
}
| 3,005 | 35.216867 | 122 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/rule/ws/RepositoriesActionIT.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.ws;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.rule.RuleRepositoryDto;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import static java.util.Arrays.asList;
public class RepositoriesActionIT {
private static final String EMPTY_JSON_RESPONSE = "{\"repositories\":[]}";
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private RepositoriesAction underTest = new RepositoriesAction(dbTester.getDbClient());
private WsActionTester tester = new WsActionTester(underTest);
@Before
public void setUp() {
DbSession dbSession = dbTester.getSession();
RuleRepositoryDto repo1 = new RuleRepositoryDto("xoo", "xoo", "SonarQube");
RuleRepositoryDto repo2 = new RuleRepositoryDto("java", "ws", "SonarQube");
RuleRepositoryDto repo3 = new RuleRepositoryDto("common-ws", "ws", "SonarQube Common");
dbTester.getDbClient().ruleRepositoryDao().insert(dbSession, asList(repo1, repo2, repo3));
dbSession.commit();
}
@Test
public void should_list_repositories() {
newRequest().execute().assertJson(this.getClass(), "repositories.json");
newRequest().setParam("language", "xoo").execute().assertJson(this.getClass(), "repositories_xoo.json");
newRequest().setParam("language", "ws").execute().assertJson(this.getClass(), "repositories_ws.json");
}
@Test
public void filter_repositories_by_name() {
newRequest().setParam("q", "common").execute().assertJson(this.getClass(), "repositories_common.json");
newRequest().setParam("q", "java").execute().assertJson(this.getClass(), "repositories_java.json");
newRequest().setParam("q", "sonar").execute().assertJson(this.getClass(), "repositories_sonar.json");
}
@Test
public void filter_repository_by_query(){
newRequest().setParam("q", "xo").execute().assertJson(this.getClass(),"repositories_xoo.json");
newRequest().setParam("q","w").execute().assertJson(this.getClass(),"repositories_common.json");
}
@Test
public void filter_repository_by_query_and_language(){
newRequest().setParam("q","ava").setParam("language","ws").execute().assertJson(this.getClass(),"repositories_java.json");
newRequest().setParam("q","w").setParam("language","ws").execute().assertJson(this.getClass(),"repositories_common.json");
}
@Test
public void do_not_consider_query_as_regexp_when_filtering_repositories_by_name() {
// invalid regexp : do not fail. Query is not a regexp.
newRequest().setParam("q", "[").execute().assertJson(EMPTY_JSON_RESPONSE);
// this is not the "match all" regexp
newRequest().setParam("q", ".*").execute().assertJson(EMPTY_JSON_RESPONSE);
}
protected TestRequest newRequest() {
return tester.newRequest();
}
}
| 3,766 | 38.652632 | 126 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/rule/ws/RuleQueryFactoryIT.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.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.ws.SimpleGetRequest;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.rule.index.RuleQuery;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsAction;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.rule.RuleStatus.DEPRECATED;
import static org.sonar.api.rule.RuleStatus.READY;
import static org.sonar.api.rule.Severity.CRITICAL;
import static org.sonar.api.rule.Severity.MAJOR;
import static org.sonar.api.rule.Severity.MINOR;
import static org.sonar.api.rules.RuleType.BUG;
import static org.sonar.api.rules.RuleType.CODE_SMELL;
import static org.sonar.api.server.ws.WebService.Param.ASCENDING;
import static org.sonar.api.server.ws.WebService.Param.SORT;
import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
import static org.sonar.db.qualityprofile.ActiveRuleDto.INHERITED;
import static org.sonar.db.qualityprofile.ActiveRuleDto.OVERRIDES;
import static org.sonar.server.rule.ws.RuleWsSupport.defineGenericRuleSearchParameters;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_ACTIVATION;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_ACTIVE_SEVERITIES;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_AVAILABLE_SINCE;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_COMPARE_TO_PROFILE;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_INCLUDE_EXTERNAL;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_INHERITANCE;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_IS_TEMPLATE;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_LANGUAGES;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_QPROFILE;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_REPOSITORIES;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_RULE_KEY;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_SEVERITIES;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_STATUSES;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_TAGS;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_TEMPLATE_KEY;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_TYPES;
public class RuleQueryFactoryIT {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private DbClient dbClient = db.getDbClient();
private RuleQueryFactory underTest = new RuleQueryFactory(dbClient);
private FakeAction fakeAction = new FakeAction(underTest);
@Test
public void create_empty_query() {
RuleQuery result = execute();
assertThat(result.getKey()).isNull();
assertThat(result.getActivation()).isNull();
assertThat(result.getActiveSeverities()).isNull();
assertThat(result.isAscendingSort()).isTrue();
assertThat(result.getAvailableSinceLong()).isNull();
assertThat(result.getInheritance()).isNull();
assertThat(result.includeExternal()).isFalse();
assertThat(result.isTemplate()).isNull();
assertThat(result.getLanguages()).isNull();
assertThat(result.getQueryText()).isNull();
assertThat(result.getQProfile()).isNull();
assertThat(result.getRepositories()).isNull();
assertThat(result.getRuleKey()).isNull();
assertThat(result.getSeverities()).isNull();
assertThat(result.getStatuses()).isEmpty();
assertThat(result.getTags()).isNull();
assertThat(result.templateKey()).isNull();
assertThat(result.getTypes()).isEmpty();
assertThat(result.getSortField()).isNull();
assertThat(result.getCompareToQProfile()).isNull();
}
@Test
public void create_rule_search_query() {
QProfileDto qualityProfile = db.qualityProfiles().insert();
QProfileDto compareToQualityProfile = db.qualityProfiles().insert();
RuleQuery result = executeRuleSearchQuery(
PARAM_RULE_KEY, "ruleKey",
PARAM_ACTIVATION, "true",
PARAM_ACTIVE_SEVERITIES, "MINOR,MAJOR",
PARAM_AVAILABLE_SINCE, "2016-01-01",
PARAM_INHERITANCE, "INHERITED,OVERRIDES",
PARAM_IS_TEMPLATE, "true",
PARAM_INCLUDE_EXTERNAL, "false",
PARAM_LANGUAGES, "java,js",
TEXT_QUERY, "S001",
PARAM_QPROFILE, qualityProfile.getKee(),
PARAM_COMPARE_TO_PROFILE, compareToQualityProfile.getKee(),
PARAM_REPOSITORIES, "pmd,checkstyle",
PARAM_SEVERITIES, "MINOR,CRITICAL",
PARAM_STATUSES, "DEPRECATED,READY",
PARAM_TAGS, "tag1,tag2",
PARAM_TEMPLATE_KEY, "architectural",
PARAM_TYPES, "CODE_SMELL,BUG",
SORT, "updatedAt",
ASCENDING, "false");
assertResult(result, qualityProfile, compareToQualityProfile);
assertThat(result.includeExternal()).isFalse();
}
@Test
public void include_external_is_mandatory_for_rule_search_query() {
db.qualityProfiles().insert();
db.qualityProfiles().insert();
Request request = new SimpleGetRequest();
assertThatThrownBy(() -> {
underTest.createRuleSearchQuery(db.getSession(), request);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The 'include_external' parameter is missing");
}
@Test
public void create_query() {
QProfileDto qualityProfile = db.qualityProfiles().insert();
QProfileDto compareToQualityProfile = db.qualityProfiles().insert();
RuleQuery result = execute(
PARAM_RULE_KEY, "ruleKey",
PARAM_ACTIVATION, "true",
PARAM_ACTIVE_SEVERITIES, "MINOR,MAJOR",
PARAM_AVAILABLE_SINCE, "2016-01-01",
PARAM_INHERITANCE, "INHERITED,OVERRIDES",
PARAM_IS_TEMPLATE, "true",
PARAM_INCLUDE_EXTERNAL, "true",
PARAM_LANGUAGES, "java,js",
TEXT_QUERY, "S001",
PARAM_QPROFILE, qualityProfile.getKee(),
PARAM_COMPARE_TO_PROFILE, compareToQualityProfile.getKee(),
PARAM_REPOSITORIES, "pmd,checkstyle",
PARAM_SEVERITIES, "MINOR,CRITICAL",
PARAM_STATUSES, "DEPRECATED,READY",
PARAM_TAGS, "tag1,tag2",
PARAM_TEMPLATE_KEY, "architectural",
PARAM_TYPES, "CODE_SMELL,BUG",
SORT, "updatedAt",
ASCENDING, "false");
assertResult(result, qualityProfile, compareToQualityProfile);
assertThat(result.includeExternal()).isFalse();
}
@Test
public void use_quality_profiles_language_if_available() {
QProfileDto qualityProfile = db.qualityProfiles().insert();
String qualityProfileKey = qualityProfile.getKee();
RuleQuery result = execute(
PARAM_LANGUAGES, "specifiedLanguage",
PARAM_ACTIVATION, "true",
PARAM_QPROFILE, qualityProfileKey);
assertThat(result.getLanguages()).containsExactly(qualityProfile.getLanguage());
}
@Test
public void use_specified_languages_if_no_quality_profile_available() {
RuleQuery result = execute(PARAM_LANGUAGES, "specifiedLanguage");
assertThat(result.getLanguages()).containsExactly("specifiedLanguage");
}
@Test
public void create_query_add_language_from_profile() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setName("Sonar way").setLanguage("xoo").setKee("sonar-way"));
RuleQuery result = execute(
PARAM_QPROFILE, profile.getKee(),
PARAM_LANGUAGES, "java,js");
assertThat(result.getQProfile().getKee()).isEqualTo(profile.getKee());
assertThat(result.getLanguages()).containsOnly("xoo");
}
@Test
public void filter_on_compare_to() {
QProfileDto compareToProfile = db.qualityProfiles().insert();
RuleQuery result = execute(
PARAM_COMPARE_TO_PROFILE, compareToProfile.getKee());
assertThat(result.getCompareToQProfile().getKee()).isEqualTo(compareToProfile.getKee());
}
public void fail_when_profile_does_not_exist() {
assertThatThrownBy(() -> {
execute(PARAM_QPROFILE, "unknown");
})
.isInstanceOf(NotFoundException.class)
.hasMessage("The specified qualityProfile 'unknown' does not exist");
}
@Test
public void fail_when_compare_to_profile_does_not_exist() {
QProfileDto qualityProfile = db.qualityProfiles().insert();
assertThatThrownBy(() -> {
execute(PARAM_QPROFILE, qualityProfile.getKee(),
PARAM_COMPARE_TO_PROFILE, "unknown");
})
.isInstanceOf(NotFoundException.class)
.hasMessage("The specified qualityProfile 'unknown' does not exist");
}
private void assertResult(RuleQuery result, QProfileDto qualityProfile, QProfileDto compareToQualityProfile) {
assertThat(result.getKey()).isEqualTo("ruleKey");
assertThat(result.getActivation()).isTrue();
assertThat(result.getActiveSeverities()).containsOnly(MINOR, MAJOR);
assertThat(result.isAscendingSort()).isFalse();
assertThat(result.getAvailableSinceLong()).isNotNull();
assertThat(result.getInheritance()).containsOnly(INHERITED, OVERRIDES);
assertThat(result.isTemplate()).isTrue();
assertThat(result.getLanguages()).containsOnly(qualityProfile.getLanguage());
assertThat(result.getQueryText()).isEqualTo("S001");
assertThat(result.getQProfile().getKee()).isEqualTo(qualityProfile.getKee());
assertThat(result.getCompareToQProfile().getKee()).isEqualTo(compareToQualityProfile.getKee());
assertThat(result.getRepositories()).containsOnly("pmd", "checkstyle");
assertThat(result.getRuleKey()).isNull();
assertThat(result.getSeverities()).containsOnly(MINOR, CRITICAL);
assertThat(result.getStatuses()).containsOnly(DEPRECATED, READY);
assertThat(result.getTags()).containsOnly("tag1", "tag2");
assertThat(result.templateKey()).isEqualTo("architectural");
assertThat(result.getTypes()).containsOnly(BUG, CODE_SMELL);
assertThat(result.getSortField()).isEqualTo("updatedAt");
}
private RuleQuery execute(String... paramsKeyAndValue) {
WsActionTester ws = new WsActionTester(fakeAction);
TestRequest request = ws.newRequest();
for (int i = 0; i < paramsKeyAndValue.length; i += 2) {
request.setParam(paramsKeyAndValue[i], paramsKeyAndValue[i + 1]);
}
request.execute();
return fakeAction.getRuleQuery();
}
private RuleQuery executeRuleSearchQuery(String... paramsKeyAndValue) {
SimpleGetRequest request = new SimpleGetRequest();
for (int i = 0; i < paramsKeyAndValue.length; i += 2) {
request.setParam(paramsKeyAndValue[i], paramsKeyAndValue[i + 1]);
}
return underTest.createRuleSearchQuery(db.getSession(), request);
}
private class FakeAction implements WsAction {
private final RuleQueryFactory ruleQueryFactory;
private RuleQuery ruleQuery;
private FakeAction(RuleQueryFactory ruleQueryFactory) {
this.ruleQueryFactory = ruleQueryFactory;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction("fake")
.setHandler(this);
defineGenericRuleSearchParameters(action);
}
@Override
public void handle(Request request, Response response) {
ruleQuery = ruleQueryFactory.createRuleQuery(db.getSession(), request);
}
RuleQuery getRuleQuery() {
return ruleQuery;
}
}
}
| 12,485 | 38.264151 | 122 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/rule/ws/SearchActionIT.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.ws;
import java.time.Clock;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
import org.sonar.api.resources.Languages;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rules.RuleType;
import org.sonar.api.server.debt.DebtRemediationFunction;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.core.util.UuidFactory;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.rule.RuleDescriptionSectionContextDto;
import org.sonar.db.rule.RuleDescriptionSectionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.language.LanguageTesting;
import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService;
import org.sonar.server.qualityprofile.ActiveRuleChange;
import org.sonar.server.qualityprofile.QProfileRules;
import org.sonar.server.qualityprofile.QProfileRulesImpl;
import org.sonar.server.qualityprofile.RuleActivation;
import org.sonar.server.qualityprofile.builtin.RuleActivator;
import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
import org.sonar.server.rule.RuleDescriptionFormatter;
import org.sonar.server.rule.index.RuleIndex;
import org.sonar.server.rule.index.RuleIndexer;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.text.MacroInterpreter;
import org.sonar.server.util.IntegerTypeValidation;
import org.sonar.server.util.StringTypeValidation;
import org.sonar.server.util.TypeValidations;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Common;
import org.sonarqube.ws.Rules;
import org.sonarqube.ws.Rules.Rule;
import org.sonarqube.ws.Rules.SearchResponse;
import static java.util.Arrays.asList;
import static java.util.Arrays.stream;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
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.assertj.guava.api.Assertions.entry;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.api.rule.Severity.BLOCKER;
import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.RESOURCES_SECTION_KEY;
import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection;
import static org.sonar.db.rule.RuleTesting.newRule;
import static org.sonar.db.rule.RuleTesting.newRuleWithoutDescriptionSection;
import static org.sonar.db.rule.RuleTesting.setSystemTags;
import static org.sonar.db.rule.RuleTesting.setTags;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_ACTIVATION;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_COMPARE_TO_PROFILE;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_QPROFILE;
import static org.sonar.server.rule.ws.RulesWsParameters.PARAM_RULE_KEY;
import static org.sonarqube.ws.Rules.Rule.DescriptionSection.Context.newBuilder;
public class SearchActionIT {
private static final String JAVA = "java";
@org.junit.Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final System2 system2 = new AlwaysIncreasingSystem2();
@org.junit.Rule
public DbTester db = DbTester.create(system2);
@org.junit.Rule
public EsTester es = EsTester.create();
private final RuleIndex ruleIndex = new RuleIndex(es.client(), system2);
private final RuleIndexer ruleIndexer = new RuleIndexer(es.client(), db.getDbClient());
private final ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(db.getDbClient(), es.client());
private final Languages languages = LanguageTesting.newLanguages(JAVA, "js");
private final ActiveRuleCompleter activeRuleCompleter = new ActiveRuleCompleter(db.getDbClient(), languages);
private final RuleQueryFactory ruleQueryFactory = new RuleQueryFactory(db.getDbClient());
private final MacroInterpreter macroInterpreter = mock(MacroInterpreter.class);
private final QualityProfileChangeEventService qualityProfileChangeEventService = mock(QualityProfileChangeEventService.class);
private final RuleMapper ruleMapper = new RuleMapper(languages, macroInterpreter, new RuleDescriptionFormatter());
private final SearchAction underTest = new SearchAction(ruleIndex, activeRuleCompleter, ruleQueryFactory, db.getDbClient(), ruleMapper,
new RuleWsSupport(db.getDbClient(), userSession));
private final TypeValidations typeValidations = new TypeValidations(asList(new StringTypeValidation(), new IntegerTypeValidation()));
private final RuleActivator ruleActivator = new RuleActivator(System2.INSTANCE, db.getDbClient(), typeValidations, userSession);
private final QProfileRules qProfileRules = new QProfileRulesImpl(db.getDbClient(), ruleActivator, ruleIndex, activeRuleIndexer,
qualityProfileChangeEventService);
private final WsActionTester ws = new WsActionTester(underTest);
private final UuidFactory uuidFactory = UuidFactoryFast.getInstance();
@Before
public void before() {
doReturn("interpreted").when(macroInterpreter).interpret(anyString());
}
@Test
public void test_definition() {
WebService.Action def = ws.getDef();
assertThat(def.isPost()).isFalse();
assertThat(def.since()).isEqualTo("4.4");
assertThat(def.isInternal()).isFalse();
assertThat(def.responseExampleAsString()).isNotEmpty();
assertThat(def.params()).hasSize(28);
WebService.Param compareToProfile = def.param("compareToProfile");
assertThat(compareToProfile.since()).isEqualTo("6.5");
assertThat(compareToProfile.isRequired()).isFalse();
assertThat(compareToProfile.isInternal()).isTrue();
assertThat(compareToProfile.description()).isEqualTo("Quality profile key to filter rules that are activated. Meant to compare easily to profile set in 'qprofile'");
}
@Test
public void return_empty_result() {
Rules.SearchResponse response = ws.newRequest()
.setParam(WebService.Param.FIELDS, "actives")
.executeProtobuf(Rules.SearchResponse.class);
assertThat(response.getTotal()).isZero();
assertThat(response.getP()).isOne();
assertThat(response.getPaging().getTotal()).isZero();
assertThat(response.getPaging().getPageIndex()).isOne();
assertThat(response.getPaging().getPageSize()).isNotZero();
assertThat(response.getRulesCount()).isZero();
}
@Test
public void return_all_rules() {
RuleDto rule1 = db.rules().insert(r1 -> r1.setLanguage("java").setNoteUserUuid(null));
RuleDto rule2 = db.rules().insert(r1 -> r1.setLanguage("java").setNoteUserUuid(null));
indexRules();
verify(r -> {
}, rule1, rule2);
}
@Test
public void return_note_login() {
UserDto user1 = db.users().insertUser();
RuleDto rule1 = db.rules().insert(r -> r.setNoteUserUuid(user1.getUuid()));
UserDto disableUser = db.users().insertDisabledUser();
RuleDto rule2 = db.rules().insert(r -> r.setNoteUserUuid(disableUser.getUuid()));
indexRules();
SearchResponse result = ws.newRequest()
.setParam("f", "noteLogin")
.executeProtobuf(SearchResponse.class);
assertThat(result.getRulesList())
.extracting(Rule::getKey, Rule::getNoteLogin)
.containsExactlyInAnyOrder(
tuple(rule1.getKey().toString(), user1.getLogin()),
tuple(rule2.getKey().toString(), disableUser.getLogin()));
}
@Test
public void dont_fail_if_note_author_no_longer_exists() {
// note: this can only happen due to DB corruption (user deleted)
RuleDto rule1 = db.rules().insert(r -> r.setNoteUserUuid("non-existent"));
indexRules();
SearchResponse result = ws.newRequest()
.setParam("f", "noteLogin")
.executeProtobuf(SearchResponse.class);
assertThat(result.getRulesList())
.extracting(Rule::getKey, Rule::getNoteLogin)
.containsExactlyInAnyOrder(
tuple(rule1.getKey().toString(), ""));
}
@Test
public void filter_by_rule_key() {
RuleDto rule1 = db.rules().insert(r1 -> r1.setLanguage("java").setNoteUserUuid(null));
db.rules().insert(r1 -> r1.setLanguage("java").setNoteUserUuid(null));
indexRules();
verify(r -> r.setParam(PARAM_RULE_KEY, rule1.getKey().toString()), rule1);
verifyNoResults(r -> r.setParam(PARAM_RULE_KEY, "missing"));
}
@Test
public void filter_by_rule_name() {
RuleDto rule1 = db.rules().insert(r1 -> r1.setName("Best rule ever").setNoteUserUuid(null));
RuleDto rule2 = db.rules().insert(r1 -> r1.setName("Some other stuff").setNoteUserUuid(null));
indexRules();
verify(r -> r.setParam("q", "Be"), rule1);
verify(r -> r.setParam("q", "Bes"), rule1);
verify(r -> r.setParam("q", "Best"), rule1);
verify(r -> r.setParam("q", "Best "), rule1);
verify(r -> r.setParam("q", "Best rule"), rule1);
verify(r -> r.setParam("q", "Best rule eve"), rule1);
verify(r -> r.setParam("q", "Best rule ever"), rule1);
verify(r -> r.setParam("q", "ru ev"), rule1);
verify(r -> r.setParam("q", "ru ever"), rule1);
verify(r -> r.setParam("q", "ev ve ver ru le"), rule1);
verify(r -> r.setParam("q", "other"), rule2);
}
@Test
public void filter_by_rule_name_requires_all_words_to_match() {
RuleDto rule1 = db.rules().insert(r1 -> r1.setName("Best rule ever").setNoteUserUuid(null));
RuleDto rule2 = db.rules().insert(r1 -> r1.setName("Some other stuff").setNoteUserUuid(null));
indexRules();
verify(r -> r.setParam("q", "Best other"));
verify(r -> r.setParam("q", "Best rule"), rule1);
verify(r -> r.setParam("q", "rule ever"), rule1);
}
@Test
public void filter_by_rule_name_does_not_interpret_query() {
RuleDto rule1 = db.rules().insert(r1 -> r1.setName("Best rule for-ever").setNoteUserUuid(null));
RuleDto rule2 = db.rules().insert(r1 -> r1.setName("Some other stuff").setNoteUserUuid(null));
indexRules();
// do not interpret "-" as a "not"
verify(r -> r.setParam("q", "-ever"), rule1);
}
@Test
public void filter_by_rule_description() {
RuleDto rule1 = db.rules().insert(
newRule(createDefaultRuleDescriptionSection(uuidFactory.create(), "This is the <bold>best</bold> rule now&for<b>ever</b>"))
.setNoteUserUuid(null));
db.rules().insert(r1 -> r1.setName("Some other stuff").setNoteUserUuid(null));
indexRules();
verify(r -> r.setParam("q", "Best "), rule1);
verify(r -> r.setParam("q", "bold"));
verify(r -> r.setParam("q", "now&forever"), rule1);
}
@Test
public void filter_with_context_specific_rule_description() {
RuleDescriptionSectionDto section1context1 = createRuleDescriptionSectionWithContext(RESOURCES_SECTION_KEY, "<div>I want to fix with Spring</div>", "ctx1");
RuleDescriptionSectionDto section1context2 = createRuleDescriptionSectionWithContext(RESOURCES_SECTION_KEY, "<div>Another context</div>", "ctx2");
RuleDto ruleDto = newRuleWithoutDescriptionSection()
.setNoteUserUuid(null)
.addRuleDescriptionSectionDto(section1context1)
.addRuleDescriptionSectionDto(section1context2);
db.rules().insert(ruleDto);
indexRules();
verify(r -> r.setParam("q", "Spring "), ruleDto);
verify(r -> r.setParam("q", "bold"));
verify(r -> r.setParam("q", "context"), ruleDto);
}
@Test
public void filter_by_rule_name_or_descriptions_requires_all_words_to_match_anywhere() {
RuleDto rule1 = db.rules().insert(newRuleWithoutDescriptionSection().setName("Best rule ever").setNoteUserUuid(null)
.addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "This is a good rule")));
db.rules().insert(newRuleWithoutDescriptionSection().setName("Another thing").setNoteUserUuid(null)
.addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "Another thing")));
indexRules();
verify(r -> r.setParam("q", "Best good"), rule1);
verify(r -> r.setParam("q", "Best Another"));
}
@Test
public void return_all_rule_fields_by_default() {
OffsetDateTime dateTime = OffsetDateTime.now(Clock.fixed(Instant.ofEpochMilli(1687816800000L), ZoneId.systemDefault()));
RuleDto rule = db.rules().insert(
r -> r.setCreatedAt(dateTime.toInstant().toEpochMilli()),
r -> r.setUpdatedAt(dateTime.toInstant().toEpochMilli()),
r -> r.setGapDescription("Gap Description"),
r -> r.setIsTemplate(true),
r -> r.setName("Name"),
r -> r.setRepositoryKey("repo_key"),
r -> r.setSeverity("MINOR"),
r -> r.setLanguage("java")
);
indexRules();
Rules.SearchResponse response = ws.newRequest().executeProtobuf(Rules.SearchResponse.class);
Rules.Rule result = response.getRules(0);
assertThat(result.getCreatedAt()).isEqualTo(dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ")));
assertThat(result.getUpdatedAt()).isEqualTo(dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ")));
assertThat(result.getGapDescription()).isEqualTo("Gap Description");
assertThat(result.hasIsTemplate()).isTrue();
assertThat(result.getName()).isEqualTo("Name");
assertThat(result.getRepo()).isEqualTo("repo_key");
assertThat(result.getSeverity()).isEqualTo("MINOR");
assertThat(result.getType().name()).isEqualTo(RuleType.valueOf(rule.getType()).name());
assertThat(result.getLang()).isEqualTo("java");
}
@Test
public void return_subset_of_fields() {
RuleDto rule = db.rules().insert(r -> r.setLanguage("java"));
indexRules();
Rules.SearchResponse response = ws.newRequest()
.setParam(WebService.Param.FIELDS, "createdAt,langName,educationPrinciples")
.executeProtobuf(Rules.SearchResponse.class);
Rules.Rule result = response.getRules(0);
// mandatory fields
assertThat(result.getKey()).isEqualTo(rule.getKey().toString());
assertThat(result.getType().getNumber()).isEqualTo(rule.getType());
// selected fields
assertThat(result.getCreatedAt()).isNotEmpty();
assertThat(result.getLangName()).isNotEmpty();
assertThat(result.getEducationPrinciples().getEducationPrinciplesList()).containsExactlyElementsOf(rule.getEducationPrinciples());
// not returned fields
assertThat(result.hasGapDescription()).isFalse();
assertThat(result.hasHtmlDesc()).isFalse();
assertThat(result.hasIsTemplate()).isFalse();
assertThat(result.hasLang()).isFalse();
assertThat(result.hasName()).isFalse();
assertThat(result.hasSeverity()).isFalse();
assertThat(result.hasRepo()).isFalse();
assertThat(result.hasUpdatedAt()).isFalse();
}
@Test
public void return_deprecatedKeys_in_response_on_demand() {
RuleDto rule1 = db.rules().insert(r -> r.setLanguage("java"));
db.rules().insertDeprecatedKey(r -> r.setRuleUuid(rule1.getUuid()).setOldRuleKey("oldrulekey").setOldRepositoryKey("oldrepositorykey"));
db.rules().insertDeprecatedKey(r -> r.setRuleUuid(rule1.getUuid()).setOldRuleKey("oldrulekey2").setOldRepositoryKey("oldrepositorykey2"));
RuleDto rule2 = db.rules().insert(r -> r.setLanguage("javascript"));
indexRules();
Rules.SearchResponse response = ws.newRequest()
.setParam(WebService.Param.FIELDS, "deprecatedKeys")
.executeProtobuf(Rules.SearchResponse.class);
System.err.println(response.getRulesList());
assertThat(response.getRulesList()).satisfies(l -> {
assertThat(l).hasSize(2);
assertThat(l).anySatisfy(e -> {
assertThat(e.getKey()).isEqualTo(rule1.getKey().toString());
assertThat(e.getType().getNumber()).isEqualTo(rule1.getType());
assertThat(e.getDeprecatedKeys()).isNotNull();
assertThat(e.getDeprecatedKeys().getDeprecatedKeyList()).contains("oldrepositorykey:oldrulekey", "oldrepositorykey2:oldrulekey2");
});
assertThat(l).anySatisfy(e -> {
assertThat(e.getKey()).isEqualTo(rule2.getKey().toString());
assertThat(e.getType().getNumber()).isEqualTo(rule2.getType());
assertThat(e.getDeprecatedKeys()).isNotNull();
assertThat(e.getDeprecatedKeys().getDeprecatedKeyList()).isEmpty();
});
});
}
@Test
public void should_filter_on_specific_tags() {
RuleDto rule1 = db.rules().insert(r -> r.setLanguage("java").setTags(Set.of("tag1", "tag2")));
db.rules().insert(r -> r.setLanguage("java"));
indexRules();
Consumer<TestRequest> request = r -> r
.setParam("f", "repo,name")
.setParam("tags", rule1.getTags().stream().collect(Collectors.joining(",")));
verify(request, rule1);
}
@Test
public void when_searching_for_several_tags_combine_them_with_OR() {
RuleDto bothTagsRule = db.rules().insert(r -> r.setLanguage("java"), setTags("tag1", "tag2"));
RuleDto oneTagRule = db.rules().insert(r -> r.setLanguage("java"), setTags("tag1"));
RuleDto otherTagRule = db.rules().insert(r -> r.setLanguage("java"), setTags("tag2"));
db.rules().insert(r -> r.setLanguage("java"), setTags());
indexRules();
Consumer<TestRequest> request = r -> r
.setParam("f", "repo,name")
.setParam("tags", "tag1,tag2");
verify(request, bothTagsRule, oneTagRule, otherTagRule);
}
@Test
public void should_list_tags_in_tags_facet() {
String[] tags = get101Tags();
db.rules().insert(setSystemTags("x"), setTags(tags));
indexRules();
SearchResponse result = ws.newRequest()
.setParam("f", "repo,name")
.setParam("facets", "tags")
.executeProtobuf(SearchResponse.class);
assertThat(result.getFacets().getFacets(0).getValuesList()).extracting(Common.FacetValue::getVal, Common.FacetValue::getCount)
.contains(tuple("tag0", 1L), tuple("tag25", 1L), tuple("tag99", 1L))
.doesNotContain(tuple("x", 1L));
}
@Test
public void should_list_tags_ordered_by_count_then_by_name_in_tags_facet() {
db.rules().insert(setSystemTags("tag7", "tag5", "tag3", "tag1", "tag9"), setTags("tag2", "tag4", "tag6", "tag8", "tagA"));
db.rules().insert(setSystemTags("tag2"), setTags());
indexRules();
SearchResponse result = ws.newRequest()
.setParam("f", "repo,name")
.setParam("facets", "tags")
.executeProtobuf(SearchResponse.class);
assertThat(result.getFacets().getFacets(0).getValuesList()).extracting(Common.FacetValue::getVal, Common.FacetValue::getCount)
.containsExactly(tuple("tag2", 2L), tuple("tag1", 1L), tuple("tag3", 1L), tuple("tag4", 1L), tuple("tag5", 1L), tuple("tag6", 1L), tuple("tag7", 1L), tuple("tag8", 1L),
tuple("tag9", 1L), tuple("tagA", 1L));
}
@Test
public void should_include_selected_matching_tag_in_facet() {
db.rules().insert(
setSystemTags("tag1", "tag2", "tag3", "tag4", "tag5", "tag6", "tag7", "tag8", "tag9", "tagA", "x"),
r -> r.setNoteUserUuid(null));
indexRules();
SearchResponse result = ws.newRequest()
.setParam("facets", "tags")
.setParam("tags", "x")
.executeProtobuf(SearchResponse.class);
assertThat(result.getFacets().getFacets(0).getValuesList()).extracting(v -> entry(v.getVal(), v.getCount())).contains(entry("x", 1L));
}
@Test
public void should_included_selected_non_matching_tag_in_facet() {
RuleDto rule = db.rules().insert(setSystemTags("tag1", "tag2", "tag3", "tag4", "tag5", "tag6", "tag7", "tag8", "tag9", "tagA"));
indexRules();
SearchResponse result = ws.newRequest()
.setParam("facets", "tags")
.setParam("tags", "x")
.executeProtobuf(SearchResponse.class);
assertThat(result.getFacets().getFacets(0).getValuesList()).extracting(v -> entry(v.getVal(), v.getCount())).contains(entry("x", 0L));
}
@Test
public void should_return_specific_tags() {
RuleDto rule = db.rules().insert(r -> r.setLanguage("java"), setTags("tag1", "tag2"));
indexRules();
SearchResponse result = ws.newRequest()
.setParam("f", "tags")
.executeProtobuf(SearchResponse.class);
assertThat(result.getRulesList()).extracting(Rule::getKey).containsExactly(rule.getKey().toString());
assertThat(result.getRulesList())
.extracting(Rule::getTags).flatExtracting(Rules.Tags::getTagsList)
.containsExactly(rule.getTags().toArray(new String[0]));
}
@Test
public void should_return_specified_fields() {
when(macroInterpreter.interpret(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
RuleDescriptionSectionDto section1context1 = createRuleDescriptionSectionWithContext(RESOURCES_SECTION_KEY, "<div>I want to fix with Spring</div>", "ctx1");
RuleDescriptionSectionDto section1context2 = createRuleDescriptionSectionWithContext(RESOURCES_SECTION_KEY, "<div>Another context</div>", "ctx2");
RuleDto rule = newRuleWithoutDescriptionSection()
.setLanguage("java")
.addRuleDescriptionSectionDto(section1context1)
.addRuleDescriptionSectionDto(section1context2);
db.rules().insert(rule);
indexRules();
checkField(rule, "repo", Rule::getRepo, rule.getRepositoryKey());
checkField(rule, "name", Rule::getName, rule.getName());
checkField(rule, "severity", Rule::getSeverity, rule.getSeverityString());
checkField(rule, "status", r -> r.getStatus().toString(), rule.getStatus().toString());
checkField(rule, "internalKey", Rule::getInternalKey, rule.getConfigKey());
checkField(rule, "isTemplate", Rule::getIsTemplate, rule.isTemplate());
checkField(rule, "sysTags",
r -> r.getSysTags().getSysTagsList().stream().collect(Collectors.joining(",")),
rule.getSystemTags().stream().collect(Collectors.joining(",")));
checkField(rule, "lang", Rule::getLang, rule.getLanguage());
checkField(rule, "langName", Rule::getLangName, languages.get(rule.getLanguage()).getName());
checkField(rule, "gapDescription", Rule::getGapDescription, rule.getGapDescription());
checkDescriptionSections(rule, rule.getRuleDescriptionSectionDtos().stream()
.map(SearchActionIT::toProtobufDto)
.collect(Collectors.toSet())
);
}
private RuleDescriptionSectionDto createRuleDescriptionSectionWithContext(String key, String content, @Nullable String contextKey) {
RuleDescriptionSectionContextDto contextDto = Optional.ofNullable(contextKey)
.map(c -> RuleDescriptionSectionContextDto.of(contextKey, contextKey + " display name"))
.orElse(null);
return RuleDescriptionSectionDto.builder()
.uuid(uuidFactory.create())
.key(key)
.content(content)
.context(contextDto)
.build();
}
private static Rule.DescriptionSection toProtobufDto(RuleDescriptionSectionDto section) {
Rule.DescriptionSection.Builder builder = Rule.DescriptionSection.newBuilder().setKey(section.getKey()).setContent(section.getContent());
if (section.getContext() != null) {
RuleDescriptionSectionContextDto context = section.getContext();
builder.setContext(newBuilder().setKey(context.getKey()).setDisplayName(context.getDisplayName()).build());
}
return builder.build();
}
@Test
public void return_lang_key_field_when_language_name_is_not_available() {
String unknownLanguage = "unknown_" + randomAlphanumeric(5);
RuleDto rule = db.rules().insert(r -> r.setLanguage(unknownLanguage));
indexRules();
SearchResponse result = ws.newRequest()
.setParam("f", "langName")
.executeProtobuf(SearchResponse.class);
assertThat(result.getTotal()).isOne();
assertThat(result.getPaging().getTotal()).isOne();
assertThat(result.getPaging().getPageIndex()).isOne();
assertThat(result.getRulesCount()).isOne();
Rule searchedRule = result.getRules(0);
assertThat(searchedRule).isNotNull();
assertThat(searchedRule.getLangName()).isEqualTo(unknownLanguage);
}
@Test
public void search_debt_rules_with_default_and_overridden_debt_values() {
db.rules().insert(r -> r.setLanguage("java")
.setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name())
.setDefRemediationGapMultiplier("1h")
.setDefRemediationBaseEffort("15min")
.setRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name())
.setRemediationGapMultiplier("2h")
.setRemediationBaseEffort("25min"));
indexRules();
SearchResponse result = ws.newRequest()
.setParam("f", "debtRemFn,remFnOverloaded,defaultDebtRemFn")
.executeProtobuf(SearchResponse.class);
assertThat(result.getTotal()).isOne();
assertThat(result.getPaging().getTotal()).isOne();
assertThat(result.getPaging().getPageIndex()).isOne();
assertThat(result.getRulesCount()).isOne();
Rule searchedRule = result.getRules(0);
assertThat(searchedRule).isNotNull();
assertThat(searchedRule.getDefaultRemFnGapMultiplier()).isEqualTo("1h");
assertThat(searchedRule.getDefaultRemFnBaseEffort()).isEqualTo("15min");
assertThat(searchedRule.getDefaultDebtRemFnType()).isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET.name());
assertThat(searchedRule.getDefaultRemFnBaseEffort()).isEqualTo("15min");
assertThat(searchedRule.getDefaultRemFnGapMultiplier()).isEqualTo("1h");
assertThat(searchedRule.getDefaultRemFnType()).isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET.name());
assertThat(searchedRule.getRemFnOverloaded()).isTrue();
assertThat(searchedRule.getRemFnGapMultiplier()).isEqualTo("2h");
assertThat(searchedRule.getRemFnBaseEffort()).isEqualTo("25min");
assertThat(searchedRule.getDebtRemFnType()).isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET.name());
}
@Test
public void search_debt_rules_with_default_linear_offset_and_overridden_constant_debt() {
db.rules().insert(r -> r.setLanguage("java")
.setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name())
.setDefRemediationGapMultiplier("1h")
.setDefRemediationBaseEffort("15min")
.setRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE.name())
.setRemediationGapMultiplier(null)
.setRemediationBaseEffort("5min"));
indexRules();
SearchResponse result = ws.newRequest()
.setParam("f", "debtRemFn,remFnOverloaded,defaultDebtRemFn")
.executeProtobuf(SearchResponse.class);
assertThat(result.getTotal()).isOne();
assertThat(result.getPaging().getTotal()).isOne();
assertThat(result.getPaging().getPageIndex()).isOne();
assertThat(result.getRulesCount()).isOne();
Rule searchedRule = result.getRules(0);
assertThat(searchedRule).isNotNull();
assertThat(searchedRule.getDefaultRemFnGapMultiplier()).isEqualTo("1h");
assertThat(searchedRule.getDefaultRemFnBaseEffort()).isEqualTo("15min");
assertThat(searchedRule.getDefaultDebtRemFnType()).isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET.name());
assertThat(searchedRule.getDefaultRemFnBaseEffort()).isEqualTo("15min");
assertThat(searchedRule.getDefaultRemFnGapMultiplier()).isEqualTo("1h");
assertThat(searchedRule.getDefaultRemFnType()).isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET.name());
assertThat(searchedRule.getRemFnOverloaded()).isTrue();
assertThat(searchedRule.getRemFnGapMultiplier()).isEmpty();
assertThat(searchedRule.getRemFnBaseEffort()).isEqualTo("5min");
assertThat(searchedRule.getDebtRemFnType()).isEqualTo(DebtRemediationFunction.Type.CONSTANT_ISSUE.name());
}
@Test
public void search_debt_rules_with_default_linear_offset_and_overridden_linear_debt() {
db.rules().insert(r -> r.setLanguage("java")
.setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name())
.setDefRemediationGapMultiplier("1h")
.setDefRemediationBaseEffort("15min")
.setRemediationFunction(DebtRemediationFunction.Type.LINEAR.name())
.setRemediationGapMultiplier("1h")
.setRemediationBaseEffort(null));
indexRules();
SearchResponse result = ws.newRequest()
.setParam("f", "debtRemFn,remFnOverloaded,defaultDebtRemFn")
.executeProtobuf(SearchResponse.class);
assertThat(result.getTotal()).isOne();
assertThat(result.getPaging().getTotal()).isOne();
assertThat(result.getPaging().getPageIndex()).isOne();
assertThat(result.getRulesCount()).isOne();
Rule searchedRule = result.getRules(0);
assertThat(searchedRule).isNotNull();
assertThat(searchedRule.getDefaultRemFnGapMultiplier()).isEqualTo("1h");
assertThat(searchedRule.getDefaultRemFnBaseEffort()).isEqualTo("15min");
assertThat(searchedRule.getDefaultDebtRemFnType()).isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET.name());
assertThat(searchedRule.getDefaultRemFnBaseEffort()).isEqualTo("15min");
assertThat(searchedRule.getDefaultRemFnGapMultiplier()).isEqualTo("1h");
assertThat(searchedRule.getDefaultRemFnType()).isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET.name());
assertThat(searchedRule.getRemFnOverloaded()).isTrue();
assertThat(searchedRule.getRemFnGapMultiplier()).isEqualTo("1h");
assertThat(searchedRule.getRemFnBaseEffort()).isEmpty();
assertThat(searchedRule.getDebtRemFnType()).isEqualTo(DebtRemediationFunction.Type.LINEAR.name());
}
@Test
public void search_template_rules() {
RuleDto templateRule = db.rules().insert(r -> r.setLanguage("java")
.setIsTemplate(true));
RuleDto rule = db.rules().insert(r -> r.setLanguage("java")
.setTemplateUuid(templateRule.getUuid()));
indexRules();
SearchResponse result = ws.newRequest()
.setParam("f", "isTemplate")
.setParam("is_template", "true")
.executeProtobuf(SearchResponse.class);
assertThat(result.getTotal()).isOne();
assertThat(result.getPaging().getTotal()).isOne();
assertThat(result.getPaging().getPageIndex()).isOne();
assertThat(result.getRulesCount()).isOne();
Rule searchedRule = result.getRules(0);
assertThat(searchedRule).isNotNull();
assertThat(searchedRule.getIsTemplate()).isTrue();
assertThat(searchedRule.getKey()).isEqualTo(templateRule.getRepositoryKey() + ":" + templateRule.getRuleKey());
}
@Test
public void search_custom_rules_from_template_key() {
RuleDto templateRule = db.rules().insert(r -> r.setLanguage("java")
.setIsTemplate(true));
RuleDto rule = db.rules().insert(r -> r.setLanguage("java")
.setTemplateUuid(templateRule.getUuid()));
indexRules();
SearchResponse result = ws.newRequest()
.setParam("f", "templateKey")
.setParam("template_key", templateRule.getRepositoryKey() + ":" + templateRule.getRuleKey())
.executeProtobuf(SearchResponse.class);
assertThat(result.getTotal()).isOne();
assertThat(result.getPaging().getTotal()).isOne();
assertThat(result.getPaging().getPageIndex()).isOne();
assertThat(result.getRulesCount()).isOne();
Rule searchedRule = result.getRules(0);
assertThat(searchedRule).isNotNull();
assertThat(searchedRule.getKey()).isEqualTo(rule.getRepositoryKey() + ":" + rule.getRuleKey());
assertThat(searchedRule.getTemplateKey()).isEqualTo(templateRule.getRepositoryKey() + ":" + templateRule.getRuleKey());
}
@Test
public void do_not_return_external_rule() {
db.rules().insert(r -> r.setIsExternal(true));
indexRules();
SearchResponse result = ws.newRequest().executeProtobuf(SearchResponse.class);
assertThat(result.getTotal()).isZero();
assertThat(result.getPaging().getTotal()).isZero();
assertThat(result.getPaging().getPageIndex()).isOne();
assertThat(result.getRulesCount()).isZero();
}
@Test
public void search_all_active_rules() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage("java"));
RuleDto rule = db.rules().insert(r -> r.setLanguage("java").setNoteUserUuid(null));
RuleActivation activation = RuleActivation.create(rule.getUuid(), BLOCKER, null);
qProfileRules.activateAndCommit(db.getSession(), profile, singleton(activation));
indexRules();
SearchResponse result = ws.newRequest()
.setParam("q", rule.getName())
.setParam("activation", "true")
.executeProtobuf(SearchResponse.class);
assertThat(result.getTotal()).isOne();
assertThat(result.getPaging().getTotal()).isOne();
assertThat(result.getPaging().getPageIndex()).isOne();
assertThat(result.getRulesCount()).isOne();
Rule searchedRule = result.getRules(0);
assertThat(searchedRule).isNotNull();
assertThat(searchedRule.getKey()).isEqualTo(rule.getRepositoryKey() + ":" + rule.getRuleKey());
assertThat(searchedRule.getName()).isEqualTo(rule.getName());
}
@Test
public void search_profile_active_rules() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage("java"));
QProfileDto waterproofProfile = db.qualityProfiles().insert(p -> p.setLanguage("java"));
RuleDto rule = db.rules().insert(r -> r.setLanguage("java"));
RuleParamDto ruleParam1 = db.rules().insertRuleParam(rule, p -> p.setDefaultValue("some value")
.setType("STRING")
.setDescription("My small description")
.setName("my_var"));
RuleParamDto ruleParam2 = db.rules().insertRuleParam(rule, p -> p.setDefaultValue("1")
.setType("INTEGER")
.setDescription("My small description")
.setName("the_var"));
// SONAR-7083
RuleParamDto ruleParam3 = db.rules().insertRuleParam(rule, p -> p.setDefaultValue(null)
.setType("STRING")
.setDescription("Empty Param")
.setName("empty_var"));
RuleActivation activation = RuleActivation.create(rule.getUuid());
List<ActiveRuleChange> activeRuleChanges1 = qProfileRules.activateAndCommit(db.getSession(), profile, singleton(activation));
qProfileRules.activateAndCommit(db.getSession(), waterproofProfile, singleton(activation));
assertThat(activeRuleChanges1).hasSize(1);
indexRules();
indexActiveRules();
SearchResponse result = ws.newRequest()
.setParam("f", "actives")
.setParam("q", rule.getName())
.setParam("activation", "true")
.setParam("qprofile", profile.getKee())
.executeProtobuf(SearchResponse.class);
assertThat(result.getTotal()).isOne();
assertThat(result.getPaging().getTotal()).isOne();
assertThat(result.getPaging().getPageIndex()).isOne();
assertThat(result.getRulesCount()).isOne();
assertThat(result.getActives()).isNotNull();
assertThat(result.getActives().getActives().get(rule.getKey().toString())).isNotNull();
assertThat(result.getActives().getActives().get(rule.getKey().toString()).getActiveListList()).hasSize(1);
// The rule without value is not inserted
Rules.Active activeList = result.getActives().getActives().get(rule.getKey().toString()).getActiveList(0);
assertThat(activeList.getParamsCount()).isEqualTo(2);
assertThat(activeList.getParamsList()).extracting("key", "value").containsExactlyInAnyOrder(
tuple(ruleParam1.getName(), ruleParam1.getDefaultValue()),
tuple(ruleParam2.getName(), ruleParam2.getDefaultValue()));
String unknownProfile = "unknown_profile" + randomAlphanumeric(5);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam("activation", "true")
.setParam("qprofile", unknownProfile)
.executeProtobuf(SearchResponse.class);
})
.isInstanceOf(NotFoundException.class)
.hasMessage("The specified qualityProfile '" + unknownProfile + "' does not exist");
}
@Test
public void search_for_active_rules_when_parameter_value_is_null() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage("java"));
RuleDto rule = db.rules().insert(r -> r.setLanguage("java"));
RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setDefaultValue("some value")
.setType("STRING")
.setDescription("My small description")
.setName("my_var"));
RuleActivation activation = RuleActivation.create(rule.getUuid());
List<ActiveRuleChange> activeRuleChanges = qProfileRules.activateAndCommit(db.getSession(), profile, singleton(activation));
// Insert directly in database a rule parameter with a null value
ActiveRuleParamDto activeRuleParam = ActiveRuleParamDto.createFor(ruleParam).setValue(null);
db.getDbClient().activeRuleDao().insertParam(db.getSession(), activeRuleChanges.get(0).getActiveRule(), activeRuleParam);
db.commit();
indexRules();
indexActiveRules();
SearchResponse result = ws.newRequest()
.setParam("f", "actives")
.setParam("q", rule.getName())
.setParam("activation", "true")
.setParam("qprofile", profile.getKee())
.executeProtobuf(SearchResponse.class);
assertThat(result.getTotal()).isOne();
assertThat(result.getPaging().getTotal()).isOne();
assertThat(result.getPaging().getPageIndex()).isOne();
assertThat(result.getRulesCount()).isOne();
assertThat(result.getActives()).isNotNull();
assertThat(result.getActives().getActives().get(rule.getKey().toString())).isNotNull();
assertThat(result.getActives().getActives().get(rule.getKey().toString()).getActiveListList()).hasSize(1);
Rules.Active activeList = result.getActives().getActives().get(rule.getKey().toString()).getActiveList(0);
assertThat(activeList.getParamsCount()).isEqualTo(2);
assertThat(activeList.getParamsList()).extracting("key", "value").containsExactlyInAnyOrder(
tuple(ruleParam.getName(), ruleParam.getDefaultValue()),
tuple(activeRuleParam.getKey(), ""));
}
/**
* When the user searches for inactive rules (for example for to "activate more"), then
* only rules of the quality profiles' language are relevant
*/
@Test
public void facet_filtering_when_searching_for_inactive_rules() {
QProfileDto profile = db.qualityProfiles().insert(q -> q.setLanguage("language1"));
// on same language, not activated => match
RuleDto rule1 = db.rules().insert(r -> r
.setLanguage(profile.getLanguage())
.setRepositoryKey("repositoryKey1")
.setSystemTags(new HashSet<>(singletonList("tag1")))
.setTags(emptySet())
.setSeverity("CRITICAL")
.setNoteUserUuid(null)
.setStatus(RuleStatus.BETA)
.setType(RuleType.CODE_SMELL));
// on same language, activated => no match
RuleDto rule2 = db.rules().insert(r -> r
.setLanguage(profile.getLanguage())
.setRepositoryKey("repositoryKey2")
.setSystemTags(new HashSet<>(singletonList("tag2")))
.setTags(emptySet())
.setSeverity("MAJOR")
.setNoteUserUuid(null)
.setStatus(RuleStatus.DEPRECATED)
.setType(RuleType.VULNERABILITY));
RuleActivation activation = RuleActivation.create(rule2.getUuid(), null, null);
qProfileRules.activateAndCommit(db.getSession(), profile, singleton(activation));
// on other language, not activated => no match
RuleDto rule3 = db.rules().insert(r -> r
.setLanguage("language3")
.setRepositoryKey("repositoryKey3")
.setSystemTags(new HashSet<>(singletonList("tag3")))
.setTags(emptySet())
.setNoteUserUuid(null)
.setSeverity("BLOCKER")
.setStatus(RuleStatus.READY)
.setType(RuleType.BUG));
indexRules();
indexActiveRules();
SearchResponse result = ws.newRequest()
.setParam("facets", "languages,repositories,tags,severities,statuses,types")
.setParam("activation", "false")
.setParam("qprofile", profile.getKee())
.executeProtobuf(SearchResponse.class);
assertThat(result.getRulesList())
.extracting(Rule::getKey)
.containsExactlyInAnyOrder(
rule1.getKey().toString());
assertThat(result.getFacets().getFacetsList().stream().filter(f -> "languages".equals(f.getProperty())).findAny().get().getValuesList())
.extracting(Common.FacetValue::getVal, Common.FacetValue::getCount)
.as("Facet languages")
.containsExactlyInAnyOrder(
tuple(rule1.getLanguage(), 1L),
// known limitation: irrelevant languages are shown in this case (SONAR-9683)
tuple(rule3.getLanguage(), 1L));
assertThat(result.getFacets().getFacetsList().stream().filter(f -> "tags".equals(f.getProperty())).findAny().get().getValuesList())
.extracting(Common.FacetValue::getVal, Common.FacetValue::getCount)
.as("Facet tags")
.containsExactlyInAnyOrder(
tuple(rule1.getSystemTags().iterator().next(), 1L));
assertThat(result.getFacets().getFacetsList().stream().filter(f -> "repositories".equals(f.getProperty())).findAny().get().getValuesList())
.extracting(Common.FacetValue::getVal, Common.FacetValue::getCount)
.as("Facet repositories")
.containsExactlyInAnyOrder(
tuple(rule1.getRepositoryKey(), 1L));
assertThat(result.getFacets().getFacetsList().stream().filter(f -> "severities".equals(f.getProperty())).findAny().get().getValuesList())
.extracting(Common.FacetValue::getVal, Common.FacetValue::getCount)
.as("Facet severities")
.containsExactlyInAnyOrder(
tuple("BLOCKER" /* rule2 */, 0L),
tuple("CRITICAL"/* rule1 */, 1L),
tuple("MAJOR", 0L),
tuple("MINOR", 0L),
tuple("INFO", 0L));
assertThat(result.getFacets().getFacetsList().stream().filter(f -> "statuses".equals(f.getProperty())).findAny().get().getValuesList())
.extracting(Common.FacetValue::getVal, Common.FacetValue::getCount)
.as("Facet statuses")
.containsExactlyInAnyOrder(
tuple("READY"/* rule2 */, 0L),
tuple("BETA" /* rule1 */, 1L),
tuple("DEPRECATED", 0L));
assertThat(result.getFacets().getFacetsList().stream().filter(f -> "types".equals(f.getProperty())).findAny().get().getValuesList())
.extracting(Common.FacetValue::getVal, Common.FacetValue::getCount)
.as("Facet types")
.containsExactlyInAnyOrder(
tuple("BUG" /* rule2 */, 0L),
tuple("CODE_SMELL"/* rule1 */, 1L),
tuple("VULNERABILITY", 0L),
tuple("SECURITY_HOTSPOT", 0L));
}
@Test
public void statuses_facet_should_be_sticky() {
RuleDto rule1 = db.rules().insert(r -> r.setLanguage("java"));
RuleDto rule2 = db.rules().insert(r -> r.setLanguage("java").setStatus(RuleStatus.BETA));
RuleDto rule3 = db.rules().insert(r -> r.setLanguage("java").setStatus(RuleStatus.DEPRECATED));
indexRules();
SearchResponse result = ws.newRequest()
.setParam("f", "status")
.setParam("status", "DEPRECATED")
.executeProtobuf(SearchResponse.class);
assertThat(result.getRulesCount()).isEqualTo(3);
assertThat(result.getRulesList()).extracting(Rule::getKey, r -> r.getStatus().name()).containsExactlyInAnyOrder(
tuple(rule1.getKey().toString(), rule1.getStatus().name()),
tuple(rule2.getKey().toString(), rule2.getStatus().name()),
tuple(rule3.getKey().toString(), rule3.getStatus().name()));
}
@Test
public void paging() {
for (int i = 0; i < 12; i++) {
db.rules().insert(r -> r.setLanguage("java"));
}
indexRules();
ws.newRequest()
.setParam(WebService.Param.PAGE, "2")
.setParam(WebService.Param.PAGE_SIZE, "9")
.execute()
.assertJson(this.getClass(), "paging.json");
}
@Test
public void compare_to_another_profile() {
QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(JAVA));
QProfileDto anotherProfile = db.qualityProfiles().insert(p -> p.setLanguage(JAVA));
RuleDto commonRule = db.rules().insertRule(r -> r.setLanguage(JAVA));
RuleDto profileRule1 = db.rules().insertRule(r -> r.setLanguage(JAVA));
RuleDto profileRule2 = db.rules().insertRule(r -> r.setLanguage(JAVA));
RuleDto profileRule3 = db.rules().insertRule(r -> r.setLanguage(JAVA));
RuleDto anotherProfileRule1 = db.rules().insertRule(r -> r.setLanguage(JAVA));
RuleDto anotherProfileRule2 = db.rules().insertRule(r -> r.setLanguage(JAVA));
db.qualityProfiles().activateRule(profile, commonRule);
db.qualityProfiles().activateRule(profile, profileRule1);
db.qualityProfiles().activateRule(profile, profileRule2);
db.qualityProfiles().activateRule(profile, profileRule3);
db.qualityProfiles().activateRule(anotherProfile, commonRule);
db.qualityProfiles().activateRule(anotherProfile, anotherProfileRule1);
db.qualityProfiles().activateRule(anotherProfile, anotherProfileRule2);
indexRules();
indexActiveRules();
SearchResponse result = ws.newRequest()
.setParam(PARAM_QPROFILE, profile.getKee())
.setParam(PARAM_ACTIVATION, "false")
.setParam(PARAM_COMPARE_TO_PROFILE, anotherProfile.getKee())
.executeProtobuf(SearchResponse.class);
assertThat(result.getRulesList())
.extracting(Rule::getKey)
.containsExactlyInAnyOrder(anotherProfileRule1.getKey().toString(), anotherProfileRule2.getKey().toString());
}
@SafeVarargs
private <T> void checkField(RuleDto rule, String fieldName, Function<Rule, T> responseExtractor, T... expected) {
SearchResponse result = ws.newRequest()
.setParam("f", fieldName)
.executeProtobuf(SearchResponse.class);
assertThat(result.getRulesList()).extracting(Rule::getKey).containsExactly(rule.getKey().toString());
assertThat(result.getRulesList()).extracting(responseExtractor).containsExactly(expected);
}
private void checkDescriptionSections(RuleDto rule, Set<Rule.DescriptionSection> expected) {
SearchResponse result = ws.newRequest()
.setParam("f", "descriptionSections")
.executeProtobuf(SearchResponse.class);
assertThat(result.getRulesList()).extracting(Rule::getKey).containsExactly(rule.getKey().toString());
List<Rule.DescriptionSection> actualSections = result.getRules(0).getDescriptionSections().getDescriptionSectionsList();
assertThat(actualSections).hasSameElementsAs(expected);
}
private void verifyNoResults(Consumer<TestRequest> requestPopulator) {
verify(requestPopulator);
}
private void verify(Consumer<TestRequest> requestPopulator, RuleDto... expectedRules) {
TestRequest request = ws.newRequest();
requestPopulator.accept(request);
Rules.SearchResponse response = request.executeProtobuf(Rules.SearchResponse.class);
assertThat(response.getP()).isOne();
assertThat(response.getPaging().getPageIndex()).isOne();
assertThat(response.getPaging().getPageSize()).isNotZero();
RuleKey[] expectedRuleKeys = stream(expectedRules).map(RuleDto::getKey).toList().toArray(new RuleKey[0]);
assertThat(response.getRulesList())
.extracting(r -> RuleKey.parse(r.getKey()))
.containsExactlyInAnyOrder(expectedRuleKeys);
assertThat(response.getTotal()).isEqualTo(expectedRules.length);
assertThat(response.getPaging().getTotal()).isEqualTo(expectedRules.length);
assertThat(response.getRulesCount()).isEqualTo(expectedRules.length);
}
private void indexRules() {
ruleIndexer.indexAll();
}
private void indexActiveRules() {
activeRuleIndexer.indexAll();
}
private String[] get101Tags() {
String[] tags = new String[101];
for (int i = 0; i < 100; i++) {
tags[i] = "tag" + i;
}
tags[100] = "tagA";
return tags;
}
}
| 49,008 | 43.838975 | 174 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/rule/ws/ShowActionIT.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.ws;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.resources.Languages;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RuleType;
import org.sonar.api.server.ws.WebService;
import org.sonar.core.util.UuidFactory;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.DbTester;
import org.sonar.db.qualityprofile.ActiveRuleDto;
import org.sonar.db.qualityprofile.ActiveRuleParamDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.rule.RuleDescriptionSectionContextDto;
import org.sonar.db.rule.RuleDescriptionSectionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.rule.RuleDescriptionFormatter;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.text.MacroInterpreter;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Common;
import org.sonarqube.ws.Rules;
import org.sonarqube.ws.Rules.Rule;
import org.sonarqube.ws.Rules.ShowResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.ArgumentMatchers.anyString;
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.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.RESOURCES_SECTION_KEY;
import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.ROOT_CAUSE_SECTION_KEY;
import static org.sonar.db.rule.RuleDescriptionSectionDto.DEFAULT_KEY;
import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection;
import static org.sonar.db.rule.RuleDto.Format.MARKDOWN;
import static org.sonar.db.rule.RuleTesting.newCustomRule;
import static org.sonar.db.rule.RuleTesting.newRule;
import static org.sonar.db.rule.RuleTesting.newRuleWithoutDescriptionSection;
import static org.sonar.db.rule.RuleTesting.newTemplateRule;
import static org.sonar.db.rule.RuleTesting.setTags;
import static org.sonar.server.language.LanguageTesting.newLanguage;
import static org.sonar.server.rule.ws.ShowAction.PARAM_ACTIVES;
import static org.sonar.server.rule.ws.ShowAction.PARAM_KEY;
import static org.sonarqube.ws.Common.RuleType.UNKNOWN;
import static org.sonarqube.ws.Common.RuleType.VULNERABILITY;
public class ShowActionIT {
private static final String INTERPRETED = "interpreted";
@org.junit.Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@org.junit.Rule
public DbTester db = DbTester.create();
private final UuidFactory uuidFactory = UuidFactoryFast.getInstance();
private final MacroInterpreter macroInterpreter = mock(MacroInterpreter.class);
private final Languages languages = new Languages(newLanguage("xoo", "Xoo"));
private final WsActionTester ws = new WsActionTester(
new ShowAction(db.getDbClient(), new RuleMapper(languages, macroInterpreter, new RuleDescriptionFormatter()),
new ActiveRuleCompleter(db.getDbClient(), languages),
new RuleWsSupport(db.getDbClient(), userSession)));
private UserDto userDto;
@Before
public void before() {
userDto = db.users().insertUser();
doReturn(INTERPRETED).when(macroInterpreter).interpret(anyString());
}
@Test
public void show_rule_key() {
RuleDto rule = db.rules().insert(r -> r.setNoteUserUuid(userDto.getUuid()));
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, rule.getKey().toString())
.executeProtobuf(ShowResponse.class);
assertThat(result.getRule()).extracting(Rule::getKey).isEqualTo(rule.getKey().toString());
}
@Test
public void show_rule_with_basic_info() {
RuleDto rule = db.rules().insert(r -> r.setNoteUserUuid(userDto.getUuid()));
RuleParamDto ruleParam = db.rules().insertRuleParam(rule);
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, rule.getKey().toString())
.executeProtobuf(ShowResponse.class);
Rule resultRule = result.getRule();
assertThat(resultRule.getKey()).isEqualTo(rule.getKey().toString());
assertThat(resultRule.getRepo()).isEqualTo(rule.getRepositoryKey());
assertThat(resultRule.getName()).isEqualTo(rule.getName());
assertThat(resultRule.getSeverity()).isEqualTo(rule.getSeverityString());
assertThat(resultRule.getStatus()).hasToString(rule.getStatus().toString());
assertThat(resultRule.getInternalKey()).isEqualTo(rule.getConfigKey());
assertThat(resultRule.getIsTemplate()).isEqualTo(rule.isTemplate());
assertThat(resultRule.getLang()).isEqualTo(rule.getLanguage());
assertThat(resultRule.getParams().getParamsList())
.extracting(Rule.Param::getKey, Rule.Param::getHtmlDesc, Rule.Param::getDefaultValue)
.containsExactlyInAnyOrder(tuple(ruleParam.getName(), ruleParam.getDescription(), ruleParam.getDefaultValue()));
assertThat(resultRule.getEducationPrinciples().getEducationPrinciplesList()).containsExactlyElementsOf(rule.getEducationPrinciples());
}
@Test
public void show_rule_tags() {
RuleDto rule = db.rules().insert(setTags("tag1", "tag2"), r -> r.setNoteData(null).setNoteUserUuid(null));
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, rule.getKey().toString())
.executeProtobuf(ShowResponse.class);
assertThat(result.getRule().getTags().getTagsList())
.containsExactly(rule.getTags().toArray(new String[0]));
}
@Test
public void show_rule_with_note_login() {
UserDto user = db.users().insertUser();
RuleDto rule = db.rules().insert(r -> r.setNoteUserUuid(user.getUuid()));
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, rule.getKey().toString())
.executeProtobuf(ShowResponse.class);
assertThat(result.getRule().getNoteLogin()).isEqualTo(user.getLogin());
}
@Test
public void show_rule_with_default_debt_infos() {
RuleDto rule = db.rules().insert(r -> r
.setDefRemediationFunction("LINEAR_OFFSET")
.setDefRemediationGapMultiplier("5d")
.setDefRemediationBaseEffort("10h")
.setGapDescription("gap desc")
.setNoteUserUuid(userDto.getUuid())
.setRemediationFunction(null)
.setRemediationGapMultiplier(null)
.setRemediationBaseEffort(null));
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, rule.getKey().toString())
.executeProtobuf(ShowResponse.class);
Rule resultRule = result.getRule();
assertThat(resultRule.getDefaultRemFnType()).isEqualTo("LINEAR_OFFSET");
assertThat(resultRule.getDefaultRemFnGapMultiplier()).isEqualTo("5d");
assertThat(resultRule.getDefaultRemFnBaseEffort()).isEqualTo("10h");
assertThat(resultRule.getGapDescription()).isEqualTo("gap desc");
assertThat(resultRule.getRemFnType()).isEqualTo("LINEAR_OFFSET");
assertThat(resultRule.getRemFnGapMultiplier()).isEqualTo("5d");
assertThat(resultRule.getRemFnBaseEffort()).isEqualTo("10h");
assertThat(resultRule.getRemFnOverloaded()).isFalse();
assertThat(resultRule.hasDeprecatedKeys()).isFalse();
}
@Test
public void show_rule_with_only_overridden_debt() {
RuleDto rule = db.rules().insert(r -> r
.setDefRemediationFunction(null)
.setDefRemediationGapMultiplier(null)
.setDefRemediationBaseEffort(null)
.setNoteData(null)
.setNoteUserUuid(null)
.setRemediationFunction("LINEAR_OFFSET")
.setRemediationGapMultiplier("5d")
.setRemediationBaseEffort("10h"));
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, rule.getKey().toString())
.executeProtobuf(ShowResponse.class);
Rule resultRule = result.getRule();
assertThat(resultRule.hasDefaultRemFnType()).isFalse();
assertThat(resultRule.hasDefaultRemFnGapMultiplier()).isFalse();
assertThat(resultRule.hasDefaultRemFnBaseEffort()).isFalse();
assertThat(resultRule.getRemFnType()).isEqualTo("LINEAR_OFFSET");
assertThat(resultRule.getRemFnGapMultiplier()).isEqualTo("5d");
assertThat(resultRule.getRemFnBaseEffort()).isEqualTo("10h");
assertThat(resultRule.getRemFnOverloaded()).isTrue();
assertThat(resultRule.hasDeprecatedKeys()).isFalse();
}
@Test
public void show_rule_with_default_and_overridden_debt_infos() {
RuleDto rule = db.rules().insert(r -> r
.setDefRemediationFunction("LINEAR_OFFSET")
.setDefRemediationGapMultiplier("5d")
.setDefRemediationBaseEffort("10h")
.setNoteData(null)
.setNoteUserUuid(null)
.setRemediationFunction("CONSTANT_ISSUE")
.setRemediationGapMultiplier(null)
.setRemediationBaseEffort("15h"));
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, rule.getKey().toString())
.executeProtobuf(ShowResponse.class);
Rule resultRule = result.getRule();
assertThat(resultRule.getDefaultRemFnType()).isEqualTo("LINEAR_OFFSET");
assertThat(resultRule.getDefaultRemFnType()).isEqualTo("LINEAR_OFFSET");
assertThat(resultRule.getDefaultRemFnGapMultiplier()).isEqualTo("5d");
assertThat(resultRule.getDefaultRemFnBaseEffort()).isEqualTo("10h");
assertThat(resultRule.getRemFnType()).isEqualTo("CONSTANT_ISSUE");
assertThat(resultRule.hasRemFnGapMultiplier()).isFalse();
assertThat(resultRule.getRemFnBaseEffort()).isEqualTo("15h");
assertThat(resultRule.getRemFnOverloaded()).isTrue();
assertThat(resultRule.hasDeprecatedKeys()).isFalse();
}
@Test
public void show_rule_with_no_default_and_no_overridden_debt() {
RuleDto rule = db.rules().insert(r -> r
.setDefRemediationFunction(null)
.setDefRemediationGapMultiplier(null)
.setDefRemediationBaseEffort(null)
.setNoteData(null)
.setNoteUserUuid(null)
.setRemediationFunction(null)
.setRemediationGapMultiplier(null)
.setRemediationBaseEffort(null));
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, rule.getKey().toString())
.executeProtobuf(ShowResponse.class);
Rule resultRule = result.getRule();
assertThat(resultRule.hasDefaultRemFnType()).isFalse();
assertThat(resultRule.hasDefaultRemFnGapMultiplier()).isFalse();
assertThat(resultRule.hasDefaultRemFnBaseEffort()).isFalse();
assertThat(resultRule.hasRemFnType()).isFalse();
assertThat(resultRule.hasRemFnGapMultiplier()).isFalse();
assertThat(resultRule.hasRemFnBaseEffort()).isFalse();
assertThat(resultRule.getRemFnOverloaded()).isFalse();
assertThat(resultRule.hasDeprecatedKeys()).isFalse();
}
@Test
public void show_deprecated_rule_debt_fields() {
RuleDto rule = db.rules().insert(r -> r
.setDefRemediationFunction("LINEAR_OFFSET")
.setDefRemediationGapMultiplier("5d")
.setDefRemediationBaseEffort("10h")
.setGapDescription("gap desc")
.setNoteData(null)
.setNoteUserUuid(null)
.setRemediationFunction("CONSTANT_ISSUE")
.setRemediationGapMultiplier(null)
.setRemediationBaseEffort("15h"));
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, rule.getKey().toString())
.executeProtobuf(ShowResponse.class);
Rule resultRule = result.getRule();
assertThat(resultRule.getDefaultRemFnType()).isEqualTo("LINEAR_OFFSET");
assertThat(resultRule.getDefaultRemFnGapMultiplier()).isEqualTo("5d");
assertThat(resultRule.getDefaultRemFnBaseEffort()).isEqualTo("10h");
assertThat(resultRule.getGapDescription()).isEqualTo("gap desc");
assertThat(resultRule.getDebtRemFnType()).isEqualTo("CONSTANT_ISSUE");
assertThat(resultRule.hasRemFnGapMultiplier()).isFalse();
assertThat(resultRule.getRemFnBaseEffort()).isEqualTo("15h");
assertThat(resultRule.getRemFnOverloaded()).isTrue();
assertThat(resultRule.hasDeprecatedKeys()).isFalse();
}
@Test
public void encode_html_description_of_custom_rule() {
RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001"));
db.rules().insert(templateRule);
RuleDto customRule = newCustomRule(templateRule, "<div>line1\nline2</div>")
.setDescriptionFormat(MARKDOWN)
.setNoteUserUuid(userDto.getUuid());
db.rules().insert(customRule);
doReturn("<div>line1<br/>line2</div>").when(macroInterpreter).interpret("<div>line1\nline2</div>");
ShowResponse result = ws.newRequest()
.setParam("key", customRule.getKey().toString())
.executeProtobuf(ShowResponse.class);
assertThat(result.getRule().getHtmlDesc()).isEqualTo(INTERPRETED);
assertThat(result.getRule().getTemplateKey()).isEqualTo(templateRule.getKey().toString());
verify(macroInterpreter, times(2)).interpret("<div>line1<br/>line2</div>");
}
@Test
public void show_external_rule() {
RuleDto externalRule = db.rules().insert(r -> r
.setIsExternal(true)
.setName("ext rule name")
.setNoteUserUuid(userDto.getUuid()));
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, externalRule.getKey().toString())
.executeProtobuf(ShowResponse.class);
Rule resultRule = result.getRule();
assertThat(resultRule.getName()).isEqualTo("ext rule name");
}
@Test
public void show_adhoc_rule() {
//Ad-hoc description has no description sections defined
RuleDto externalRule = db.rules().insert(newRuleWithoutDescriptionSection()
.setIsExternal(true)
.setIsAdHoc(true)
.setAdHocName("adhoc name")
.setAdHocDescription("<div>desc</div>")
.setAdHocSeverity(Severity.BLOCKER)
.setAdHocType(RuleType.VULNERABILITY)
.setNoteData(null)
.setNoteUserUuid(null));
doReturn("<div>desc2</div>").when(macroInterpreter).interpret(externalRule.getAdHocDescription());
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, externalRule.getKey().toString())
.executeProtobuf(ShowResponse.class);
Rule resultRule = result.getRule();
assertThat(resultRule)
.extracting(Rule::getName, Rule::getHtmlDesc, Rule::getSeverity, Rule::getType)
.containsExactlyInAnyOrder("adhoc name", "<div>desc2</div>", Severity.BLOCKER, VULNERABILITY);
assertThat(resultRule.getDescriptionSections().getDescriptionSectionsList())
.extracting(Rule.DescriptionSection::getKey, Rule.DescriptionSection::getContent)
.containsExactly(tuple(DEFAULT_KEY, "<div>desc2</div>"));
}
@Test
public void show_rule_desc_sections() {
when(macroInterpreter.interpret(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
RuleDescriptionSectionDto section1 = createRuleDescriptionSection(ROOT_CAUSE_SECTION_KEY, "<div>Root is Root</div>");
RuleDescriptionSectionDto section2 = createRuleDescriptionSection(ASSESS_THE_PROBLEM_SECTION_KEY, "<div>This is not a problem</div>");
RuleDescriptionSectionDto section3 = createRuleDescriptionSection(HOW_TO_FIX_SECTION_KEY, "<div>I don't want to fix</div>");
RuleDescriptionSectionDto section4context1 = createRuleDescriptionSectionWithContext(RESOURCES_SECTION_KEY, "<div>I want to fix with Spring</div>", "ctx1");
RuleDescriptionSectionDto section4context2 = createRuleDescriptionSectionWithContext(RESOURCES_SECTION_KEY, "<div>I want to fix with Servlet</div>", "ctx2");
RuleDto rule = createRuleWithDescriptionSections(section1, section2, section3, section4context1, section4context2);
rule.setType(RuleType.SECURITY_HOTSPOT);
rule.setNoteUserUuid(userDto.getUuid());
db.rules().insert(rule);
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, rule.getKey().toString())
.executeProtobuf(ShowResponse.class);
Rule resultRule = result.getRule();
assertThat(resultRule.getHtmlDesc()).isEmpty();
assertThat(resultRule.getMdDesc()).isEqualTo(resultRule.getHtmlDesc());
assertThat(resultRule.getDescriptionSections().getDescriptionSectionsList())
.extracting(Rule.DescriptionSection::getKey, Rule.DescriptionSection::getContent, section -> section.getContext().getKey(), section -> section.getContext().getDisplayName())
.containsExactlyInAnyOrder(
tuple(ROOT_CAUSE_SECTION_KEY, "<div>Root is Root</div>", "", ""),
tuple(ASSESS_THE_PROBLEM_SECTION_KEY, "<div>This is not a problem</div>", "", ""),
tuple(HOW_TO_FIX_SECTION_KEY, "<div>I don't want to fix</div>", "", ""),
tuple(RESOURCES_SECTION_KEY, "<div>I want to fix with Spring</div>", section4context1.getContext().getKey(), section4context1.getContext().getDisplayName()),
tuple(RESOURCES_SECTION_KEY, "<div>I want to fix with Servlet</div>", section4context2.getContext().getKey(), section4context2.getContext().getDisplayName())
);
}
@Test
public void show_rule_desc_sections_and_html_desc_with_macro() {
RuleDescriptionSectionDto section = createRuleDescriptionSection(DEFAULT_KEY, "<div>Testing macro: {rule:java:S001}</div>");
RuleDto rule = createRuleWithDescriptionSections(section);
rule.setType(RuleType.SECURITY_HOTSPOT);
rule.setNoteUserUuid(userDto.getUuid());
db.rules().insert(rule);
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, rule.getKey().toString())
.executeProtobuf(ShowResponse.class);
Rule resultRule = result.getRule();
assertThat(resultRule.getHtmlDesc()).isEqualTo(INTERPRETED);
assertThat(resultRule.getDescriptionSections().getDescriptionSectionsList())
.extracting(Rule.DescriptionSection::getKey, Rule.DescriptionSection::getContent)
.containsExactly(tuple(DEFAULT_KEY, INTERPRETED));
}
@Test
public void show_rule_desc_sections_and_markdown_desc_with_macro() {
RuleDescriptionSectionDto section = createRuleDescriptionSection(DEFAULT_KEY, "Testing macro: {rule:java:S001}");
RuleDto rule = createRuleWithDescriptionSections(section);
rule.setDescriptionFormat(MARKDOWN);
rule.setType(RuleType.SECURITY_HOTSPOT);
rule.setNoteUserUuid(userDto.getUuid());
db.rules().insert(rule);
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, rule.getKey().toString())
.executeProtobuf(ShowResponse.class);
Rule resultRule = result.getRule();
assertThat(resultRule.getHtmlDesc()).isEqualTo(INTERPRETED);
assertThat(resultRule.getDescriptionSections().getDescriptionSectionsList())
.extracting(Rule.DescriptionSection::getKey, Rule.DescriptionSection::getContent)
.containsExactly(tuple(DEFAULT_KEY, INTERPRETED));
}
@Test
public void show_if_advanced_sections_and_default_filters_out_default() {
when(macroInterpreter.interpret(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
RuleDescriptionSectionDto section1 = createRuleDescriptionSection(ROOT_CAUSE_SECTION_KEY, "<div>Root is Root</div>");
RuleDescriptionSectionDto defaultSection = createDefaultRuleDescriptionSection(uuidFactory.create(), "This is the default section");
RuleDto rule = createRuleWithDescriptionSections(section1, defaultSection);
rule.setType(RuleType.SECURITY_HOTSPOT);
rule.setNoteUserUuid(userDto.getUuid());
db.rules().insert(rule);
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, rule.getKey().toString())
.executeProtobuf(ShowResponse.class);
Rule resultRule = result.getRule();
assertThat(resultRule.getHtmlDesc()).contains(defaultSection.getContent());
assertThat(resultRule.getMdDesc()).isEqualTo(resultRule.getHtmlDesc());
assertThat(resultRule.getDescriptionSections().getDescriptionSectionsList())
.extracting(Rule.DescriptionSection::getKey, Rule.DescriptionSection::getContent)
.containsExactlyInAnyOrder(tuple(ROOT_CAUSE_SECTION_KEY, "<div>Root is Root</div>"));
}
@Test
public void show_rule_markdown_description() {
when(macroInterpreter.interpret(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
var section = createRuleDescriptionSection(DEFAULT_KEY, "*toto is toto*");
RuleDto rule = createRuleWithDescriptionSections(section);
rule.setDescriptionFormat(MARKDOWN);
rule.setNoteUserUuid(userDto.getUuid());
db.rules().insert(rule);
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, rule.getKey().toString())
.executeProtobuf(ShowResponse.class);
Rule resultRule = result.getRule();
assertThat(resultRule.getHtmlDesc()).contains("<strong>toto is toto</strong>");
assertThat(resultRule.getMdDesc()).contains("*toto is toto*");
assertThat(resultRule.getDescriptionSections().getDescriptionSectionsList())
.extracting(Rule.DescriptionSection::getKey, Rule.DescriptionSection::getContent)
.contains(tuple(DEFAULT_KEY, "<strong>toto is toto</strong>"));
}
@Test
public void ignore_predefined_info_on_adhoc_rule() {
RuleDto externalRule = newRule(createDefaultRuleDescriptionSection(uuidFactory.create(), "<div>predefined desc</div>"))
.setIsExternal(true)
.setIsAdHoc(true)
.setName("predefined name")
.setSeverity(Severity.BLOCKER)
.setType(RuleType.VULNERABILITY)
.setAdHocName("adhoc name")
.setAdHocDescription("<div>adhoc desc</div>")
.setAdHocSeverity(Severity.MAJOR)
.setAdHocType(RuleType.CODE_SMELL)
.setNoteData(null)
.setNoteUserUuid(null);
externalRule = db.rules().insert(externalRule);
doReturn("<div>adhoc desc</div>").when(macroInterpreter).interpret(externalRule.getAdHocDescription());
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, externalRule.getKey().toString())
.executeProtobuf(ShowResponse.class);
Rule resultRule = result.getRule();
assertThat(resultRule)
.extracting(Rule::getName, Rule::getHtmlDesc, Rule::getSeverity, Rule::getType)
.containsExactlyInAnyOrder("adhoc name", "<div>adhoc desc</div>", Severity.MAJOR, Common.RuleType.CODE_SMELL);
}
@Test
public void adhoc_info_are_empty_when_no_metadata() {
RuleDto externalRule = db.rules().insert(r -> r
.setIsExternal(true)
.setIsAdHoc(true)
.setName(null)
.setDescriptionFormat(null)
.setSeverity((String) null)
.setNoteData(null)
.setNoteUserUuid(null)
.setAdHocDescription(null)
.setType(0)
.setAdHocSeverity(null)
.setAdHocName(null)
.setAdHocType(0));
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, externalRule.getKey().toString())
.executeProtobuf(ShowResponse.class);
Rule resultRule = result.getRule();
assertThat(resultRule)
.extracting(Rule::hasName, Rule::hasHtmlDesc, Rule::hasSeverity, Rule::getType)
.containsExactlyInAnyOrder(false, false, false, UNKNOWN);
}
@Test
public void show_rule_with_activation() {
RuleDto rule = db.rules().insert(r -> r.setNoteData(null).setNoteUserUuid(null));
RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setType("STRING").setDescription("Reg *exp*").setDefaultValue(".*"));
QProfileDto qProfile = db.qualityProfiles().insert();
ActiveRuleDto activeRule = db.qualityProfiles().activateRule(qProfile, rule);
db.getDbClient().activeRuleDao().insertParam(db.getSession(), activeRule, new ActiveRuleParamDto()
.setRulesParameterUuid(ruleParam.getUuid())
.setKey(ruleParam.getName())
.setValue(".*?"));
db.commit();
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, rule.getKey().toString())
.setParam(PARAM_ACTIVES, "true")
.executeProtobuf(ShowResponse.class);
List<Rules.Active> actives = result.getActivesList();
assertThat(actives).extracting(Rules.Active::getQProfile).containsExactly(qProfile.getKee());
assertThat(actives).extracting(Rules.Active::getSeverity).containsExactly(activeRule.getSeverityString());
assertThat(actives).extracting(Rules.Active::getInherit).containsExactly("NONE");
assertThat(actives.get(0).getParamsList())
.extracting(Rules.Active.Param::getKey, Rules.Active.Param::getValue)
.containsExactlyInAnyOrder(tuple(ruleParam.getName(), ".*?"));
}
@Test
public void show_rule_without_activation() {
RuleDto rule = db.rules().insert(r -> r.setNoteData(null).setNoteUserUuid(null));
QProfileDto qProfile = db.qualityProfiles().insert();
db.qualityProfiles().activateRule(qProfile, rule);
ShowResponse result = ws.newRequest()
.setParam(PARAM_KEY, rule.getKey().toString())
.setParam(PARAM_ACTIVES, "false")
.executeProtobuf(ShowResponse.class);
assertThat(result.getActivesList()).isEmpty();
}
@Test
public void test_definition() {
WebService.Action def = ws.getDef();
assertThat(def.isPost()).isFalse();
assertThat(def.since()).isEqualTo("4.2");
assertThat(def.isInternal()).isFalse();
assertThat(def.responseExampleAsString()).isNotEmpty();
assertThat(def.params())
.extracting(WebService.Param::key, WebService.Param::isRequired)
.containsExactlyInAnyOrder(
tuple("key", true),
tuple("actives", false));
}
private RuleDescriptionSectionDto createRuleDescriptionSection(String key, String content) {
return createRuleDescriptionSectionWithContext(key, content, null);
}
private RuleDescriptionSectionDto createRuleDescriptionSectionWithContext(String key, String content, @Nullable String contextKey) {
RuleDescriptionSectionContextDto contextDto = Optional.ofNullable(contextKey)
.map(c -> RuleDescriptionSectionContextDto.of(contextKey, contextKey + " display name"))
.orElse(null);
return RuleDescriptionSectionDto.builder()
.uuid(uuidFactory.create())
.key(key)
.content(content)
.context(contextDto)
.build();
}
private RuleDto createRuleWithDescriptionSections(RuleDescriptionSectionDto... sections) {
var rule = newRuleWithoutDescriptionSection();
for (var section : sections) {
rule.addRuleDescriptionSectionDto(section);
}
return rule;
}
}
| 27,299 | 43.032258 | 179 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/rule/ws/TagsActionIT.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.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.es.EsClient;
import org.sonar.server.es.EsTester;
import org.sonar.server.rule.index.RuleIndex;
import org.sonar.server.rule.index.RuleIndexer;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.db.rule.RuleTesting.setSystemTags;
import static org.sonar.db.rule.RuleTesting.setTags;
import static org.sonar.test.JsonAssert.assertJson;
public class TagsActionIT {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create();
@Rule
public EsTester es = EsTester.create();
private final DbClient dbClient = db.getDbClient();
private final EsClient esClient = es.client();
private final RuleIndex ruleIndex = new RuleIndex(esClient, System2.INSTANCE);
private final RuleIndexer ruleIndexer = new RuleIndexer(esClient, dbClient);
private final WsActionTester ws = new WsActionTester(new org.sonar.server.rule.ws.TagsAction(ruleIndex));
@Test
public void definition() {
WebService.Action action = ws.getDef();
assertThat(action.description()).isNotEmpty();
assertThat(action.responseExampleAsString()).isNotEmpty();
assertThat(action.isPost()).isFalse();
assertThat(action.isInternal()).isFalse();
assertThat(action.params()).hasSize(2);
WebService.Param query = action.param("q");
assertThat(query).isNotNull();
assertThat(query.isRequired()).isFalse();
assertThat(query.description()).isNotEmpty();
assertThat(query.exampleValue()).isNotEmpty();
WebService.Param pageSize = action.param("ps");
assertThat(pageSize).isNotNull();
assertThat(pageSize.isRequired()).isFalse();
assertThat(pageSize.defaultValue()).isEqualTo("10");
assertThat(pageSize.description()).isNotEmpty();
assertThat(pageSize.exampleValue()).isNotEmpty();
}
@Test
public void system_tag() {
RuleDto r = db.rules().insert(setSystemTags("tag"), setTags());
ruleIndexer.commitAndIndex(db.getSession(), r.getUuid());
String result = ws.newRequest().execute().getInput();
assertJson(result).isSimilarTo("{\"tags\":[\"tag\"]}");
}
@Test
public void tag() {
RuleDto r = db.rules().insert(setSystemTags(), setTags("tag"));
ruleIndexer.commitAndIndex(db.getSession(), r.getUuid());
ruleIndexer.commitAndIndex(db.getSession(), r.getUuid());
String result = ws.newRequest().execute().getInput();
assertJson(result).isSimilarTo("{\"tags\":[\"tag\"]}");
}
}
| 3,667 | 36.050505 | 107 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/rule/ws/UpdateActionIT.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.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Languages;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import org.sonar.api.utils.System2;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.rule.RuleDescriptionSectionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsClient;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.rule.RuleDescriptionFormatter;
import org.sonar.server.rule.RuleUpdater;
import org.sonar.server.rule.index.RuleIndexer;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.text.MacroInterpreter;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsAction;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Rules;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.sonar.api.server.debt.DebtRemediationFunction.Type.LINEAR;
import static org.sonar.api.server.debt.DebtRemediationFunction.Type.LINEAR_OFFSET;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection;
import static org.sonar.db.rule.RuleTesting.newRule;
import static org.sonar.db.rule.RuleTesting.setSystemTags;
import static org.sonar.db.rule.RuleTesting.setTags;
import static org.sonar.server.rule.ws.UpdateAction.PARAM_KEY;
import static org.sonar.server.rule.ws.UpdateAction.PARAM_MARKDOWN_NOTE;
import static org.sonar.server.rule.ws.UpdateAction.PARAM_REMEDIATION_FN_BASE_EFFORT;
import static org.sonar.server.rule.ws.UpdateAction.PARAM_REMEDIATION_FN_GAP_MULTIPLIER;
import static org.sonar.server.rule.ws.UpdateAction.PARAM_REMEDIATION_FN_TYPE;
import static org.sonar.server.rule.ws.UpdateAction.PARAM_TAGS;
import static org.sonar.test.JsonAssert.assertJson;
public class UpdateActionIT {
private static final long PAST = 10000L;
@Rule
public DbTester db = DbTester.create();
@Rule
public EsTester es = EsTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final DbClient dbClient = db.getDbClient();
private final EsClient esClient = es.client();
private final RuleDescriptionFormatter ruleDescriptionFormatter = new RuleDescriptionFormatter();
private final Languages languages = new Languages();
private final RuleMapper mapper = new RuleMapper(languages, createMacroInterpreter(), ruleDescriptionFormatter);
private final RuleIndexer ruleIndexer = new RuleIndexer(esClient, dbClient);
private final UuidFactoryFast uuidFactory = UuidFactoryFast.getInstance();
private final RuleUpdater ruleUpdater = new RuleUpdater(dbClient, ruleIndexer, uuidFactory, System2.INSTANCE);
private final WsAction underTest = new UpdateAction(dbClient, ruleUpdater, mapper, userSession, new RuleWsSupport(db.getDbClient(), userSession));
private final WsActionTester ws = new WsActionTester(underTest);
@Test
public void check_definition() {
assertThat(ws.getDef().isPost()).isTrue();
assertThat(ws.getDef().isInternal()).isFalse();
assertThat(ws.getDef().responseExampleAsString()).isNotNull();
assertThat(ws.getDef().description()).isNotNull();
}
@Test
public void update_custom_rule() {
logInAsQProfileAdministrator();
RuleDto templateRule = db.rules().insert(
r -> r.setRuleKey(RuleKey.of("java", "S001")),
r -> r.setIsTemplate(true),
r -> r.setNoteUserUuid(null),
r -> r.setCreatedAt(PAST),
r -> r.setUpdatedAt(PAST));
db.rules().insertRuleParam(templateRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(".*"));
RuleDto customRule = newRule(RuleKey.of("java", "MY_CUSTOM"), createRuleDescriptionSectionDto())
.setName("Old custom")
.setSeverity(Severity.MINOR)
.setStatus(RuleStatus.BETA)
.setTemplateUuid(templateRule.getUuid())
.setLanguage("js")
.setNoteUserUuid(null)
.setCreatedAt(PAST)
.setUpdatedAt(PAST);
customRule = db.rules().insert(customRule);
db.rules().insertRuleParam(customRule, param -> param.setName("regex").setType("a").setDescription("Reg ex"));
TestResponse request = ws.newRequest().setMethod("POST")
.setParam("key", customRule.getKey().toString())
.setParam("name", "My custom rule")
.setParam("markdown_description", "Description")
.setParam("severity", "MAJOR")
.setParam("status", "BETA")
.setParam("params", "regex=a.*")
.execute();
assertJson(request.getInput()).isSimilarTo("{\n" +
" \"rule\": {\n" +
" \"key\": \"java:MY_CUSTOM\",\n" +
" \"repo\": \"java\",\n" +
" \"name\": \"My custom rule\",\n" +
" \"htmlDesc\": \"Description\",\n" +
" \"severity\": \"MAJOR\",\n" +
" \"status\": \"BETA\",\n" +
" \"isTemplate\": false,\n" +
" \"templateKey\": \"java:S001\",\n" +
" \"params\": [\n" +
" {\n" +
" \"key\": \"regex\",\n" +
" \"htmlDesc\": \"Reg ex\",\n" +
" \"defaultValue\": \"a.*\"\n" +
" }\n" +
" ]\n" +
" }\n" +
"}\n");
}
@Test
public void update_tags() {
logInAsQProfileAdministrator();
RuleDto rule = db.rules().insert(setSystemTags("stag1", "stag2"), setTags("tag1", "tag2"), r -> r.setNoteData(null).setNoteUserUuid(null));
Rules.UpdateResponse result = ws.newRequest().setMethod("POST")
.setParam(PARAM_KEY, rule.getKey().toString())
.setParam(PARAM_TAGS, "tag2,tag3")
.executeProtobuf(Rules.UpdateResponse.class);
Rules.Rule updatedRule = result.getRule();
assertThat(updatedRule).isNotNull();
assertThat(updatedRule.getKey()).isEqualTo(rule.getKey().toString());
assertThat(updatedRule.getSysTags().getSysTagsList()).containsExactly(rule.getSystemTags().toArray(new String[0]));
assertThat(updatedRule.getTags().getTagsList()).containsExactly("tag2", "tag3");
}
@Test
public void update_rule_remediation_function() {
logInAsQProfileAdministrator();
RuleDto rule = db.rules().insert(
r -> r.setDefRemediationFunction(LINEAR.toString()),
r -> r.setDefRemediationGapMultiplier("10d"),
r -> r.setDefRemediationBaseEffort(null),
r -> r.setNoteUserUuid(null));
String newOffset = LINEAR_OFFSET.toString();
String newMultiplier = "15d";
String newEffort = "5min";
Rules.UpdateResponse result = ws.newRequest().setMethod("POST")
.setParam("key", rule.getKey().toString())
.setParam(PARAM_REMEDIATION_FN_TYPE, newOffset)
.setParam(PARAM_REMEDIATION_FN_GAP_MULTIPLIER, newMultiplier)
.setParam(PARAM_REMEDIATION_FN_BASE_EFFORT, newEffort)
.executeProtobuf(Rules.UpdateResponse.class);
Rules.Rule updatedRule = result.getRule();
assertThat(updatedRule).isNotNull();
assertThat(updatedRule.getKey()).isEqualTo(rule.getKey().toString());
assertThat(updatedRule.getDefaultRemFnType()).isEqualTo(rule.getDefRemediationFunction());
assertThat(updatedRule.getDefaultRemFnGapMultiplier()).isEqualTo(rule.getDefRemediationGapMultiplier());
assertThat(updatedRule.getDefaultRemFnBaseEffort()).isEmpty();
assertThat(updatedRule.getGapDescription()).isEqualTo(rule.getGapDescription());
assertThat(updatedRule.getRemFnType()).isEqualTo(newOffset);
assertThat(updatedRule.getRemFnGapMultiplier()).isEqualTo(newMultiplier);
assertThat(updatedRule.getRemFnBaseEffort()).isEqualTo(newEffort);
// check database
RuleDto updatedRuleDto = db.getDbClient().ruleDao().selectByKey(db.getSession(), rule.getKey())
.orElseThrow(() -> new IllegalStateException("Cannot load metadata"));
assertThat(updatedRuleDto.getRemediationFunction()).isEqualTo(newOffset);
assertThat(updatedRuleDto.getRemediationGapMultiplier()).isEqualTo(newMultiplier);
assertThat(updatedRuleDto.getRemediationBaseEffort()).isEqualTo(newEffort);
}
@Test
public void update_note() {
UserDto userHavingUpdatingNote = db.users().insertUser();
RuleDto rule = db.rules().insert(m -> m.setNoteData("old data").setNoteUserUuid(userHavingUpdatingNote.getUuid()));
UserDto userAuthenticated = db.users().insertUser();
userSession.logIn(userAuthenticated).addPermission(ADMINISTER_QUALITY_PROFILES);
Rules.UpdateResponse result = ws.newRequest().setMethod("POST")
.setParam(PARAM_KEY, rule.getKey().toString())
.setParam(PARAM_MARKDOWN_NOTE, "new data")
.executeProtobuf(Rules.UpdateResponse.class);
Rules.Rule updatedRule = result.getRule();
// check response
assertThat(updatedRule.getMdNote()).isEqualTo("new data");
assertThat(updatedRule.getNoteLogin()).isEqualTo(userAuthenticated.getLogin());
// check database
RuleDto updatedRuleDto = db.getDbClient().ruleDao().selectByKey(db.getSession(), rule.getKey()).get();
assertThat(updatedRuleDto.getNoteData()).isEqualTo("new data");
assertThat(updatedRuleDto.getNoteUserUuid()).isEqualTo(userAuthenticated.getUuid());
}
@Test
public void fail_to_update_custom_when_description_is_empty() {
logInAsQProfileAdministrator();
RuleDto templateRule = db.rules().insert(
r -> r.setRuleKey(RuleKey.of("java", "S001")),
r -> r.setIsTemplate(true),
r -> r.setCreatedAt(PAST),
r -> r.setUpdatedAt(PAST));
RuleDto customRule = db.rules().insert(
newRule(RuleKey.of("java", "MY_CUSTOM"), createRuleDescriptionSectionDto())
.setRuleKey(RuleKey.of("java", "MY_CUSTOM"))
.setName("Old custom")
.setTemplateUuid(templateRule.getUuid())
.setCreatedAt(PAST)
.setUpdatedAt(PAST));
assertThatThrownBy(() -> {
ws.newRequest().setMethod("POST")
.setParam("key", customRule.getKey().toString())
.setParam("name", "My custom rule")
.setParam("markdown_description", "")
.execute();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The description is missing");
}
@Test
public void throw_IllegalArgumentException_if_trying_to_update_builtin_rule_description() {
logInAsQProfileAdministrator();
RuleDto rule = db.rules().insert();
assertThatThrownBy(() -> {
ws.newRequest().setMethod("POST")
.setParam("key", rule.getKey().toString())
.setParam("name", rule.getName())
.setParam("markdown_description", "New description")
.execute();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Not a custom rule");
}
@Test
public void throw_ForbiddenException_if_not_profile_administrator() {
userSession.logIn();
assertThatThrownBy(() -> {
ws.newRequest().setMethod("POST").execute();
})
.isInstanceOf(ForbiddenException.class);
}
@Test
public void throw_UnauthorizedException_if_not_logged_in() {
assertThatThrownBy(() -> {
ws.newRequest().setMethod("POST").execute();
})
.isInstanceOf(UnauthorizedException.class);
}
private void logInAsQProfileAdministrator() {
userSession
.logIn()
.addPermission(ADMINISTER_QUALITY_PROFILES);
}
private RuleDescriptionSectionDto createRuleDescriptionSectionDto() {
return createDefaultRuleDescriptionSection(uuidFactory.create(), "Old description");
}
private static MacroInterpreter createMacroInterpreter() {
MacroInterpreter macroInterpreter = mock(MacroInterpreter.class);
doAnswer(returnsFirstArg()).when(macroInterpreter).interpret(anyString());
return macroInterpreter;
}
}
| 13,034 | 39.734375 | 148 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/scannercache/ws/ClearActionIT.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.scannercache.ws;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.db.DbInputStream;
import org.sonar.db.DbTester;
import org.sonar.db.audit.NoOpAuditPersister;
import org.sonar.db.component.BranchDao;
import org.sonar.db.component.BranchDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.project.ProjectDao;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.scannercache.ScannerAnalysisCacheDao;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.scannercache.ScannerCache;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.web.UserRole.SCAN;
public class ClearActionIT {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private final ScannerAnalysisCacheDao dao = new ScannerAnalysisCacheDao();
private final ProjectDao projectDao = new ProjectDao(System2.INSTANCE, new NoOpAuditPersister());
private final BranchDao branchDao = new BranchDao(System2.INSTANCE);
private final ScannerCache cache = new ScannerCache(dbTester.getDbClient(), dao, projectDao, branchDao);
private final ClearAction ws = new ClearAction(userSession, cache);
private final WsActionTester wsTester = new WsActionTester(ws);
@Test
public void should_clear_all_entries() throws IOException {
ProjectDto project1 = dbTester.components().insertPrivateProject().getProjectDto();
ProjectDto project2 = dbTester.components().insertPrivateProject().getProjectDto();
dao.insert(dbTester.getSession(), project1.getUuid(), stringToInputStream("test data"));
dao.insert(dbTester.getSession(), project2.getUuid(), stringToInputStream("test data"));
assertThat(dataStreamToString(dao.selectData(dbTester.getSession(), project1.getUuid()))).isEqualTo("test data");
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
TestResponse response = wsTester.newRequest().execute();
response.assertNoContent();
assertThat(dbTester.countRowsOfTable("scanner_analysis_cache")).isZero();
}
@Test
public void should_clear_project_cache() {
ProjectDto project1 = dbTester.components().insertPrivateProject(cDto -> cDto.setKey("p1")).getProjectDto();
BranchDto branch11 = dbTester.components().insertProjectBranch(project1, cdto -> cdto.setKey("b11"));
BranchDto branch12 = dbTester.components().insertProjectBranch(project1, cdto -> cdto.setKey("b12"));
ProjectDto project2 = dbTester.components().insertPrivateProject(cDto -> cDto.setKey("p2")).getProjectDto();
BranchDto branch21 = dbTester.components().insertProjectBranch(project2, cdto -> cdto.setKey("b21"));
dao.insert(dbTester.getSession(), branch11.getUuid(), stringToInputStream("test data"));
dao.insert(dbTester.getSession(), branch12.getUuid(), stringToInputStream("test data"));
dao.insert(dbTester.getSession(), branch21.getUuid(), stringToInputStream("test data"));
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
TestResponse response = wsTester.newRequest()
.setParam(ClearAction.PARAM_PROJECT_KEY, "p1")
.execute();
response.assertNoContent();
assertThat(cache.get(branch11.getUuid())).isNull();
assertThat(cache.get(branch12.getUuid())).isNull();
assertThat(cache.get(branch21.getUuid())).isNotNull();
}
@Test
public void should_clear_branch_cache() {
ProjectDto project1 = dbTester.components().insertPrivateProject(cDto -> cDto.setKey("p1")).getProjectDto();
BranchDto branch11 = dbTester.components().insertProjectBranch(project1, cdto -> cdto.setKey("b11"));
BranchDto branch12 = dbTester.components().insertProjectBranch(project1, cdto -> cdto.setKey("b12"));
ProjectDto project2 = dbTester.components().insertPrivateProject(cDto -> cDto.setKey("p2")).getProjectDto();
BranchDto branch21 = dbTester.components().insertProjectBranch(project2, cdto -> cdto.setKey("b21"));
dao.insert(dbTester.getSession(), branch11.getUuid(), stringToInputStream("test data"));
dao.insert(dbTester.getSession(), branch12.getUuid(), stringToInputStream("test data"));
dao.insert(dbTester.getSession(), branch21.getUuid(), stringToInputStream("test data"));
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
TestResponse response = wsTester.newRequest()
.setParam(ClearAction.PARAM_PROJECT_KEY, "p1")
.setParam(ClearAction.PARAM_BRANCH_KEY, "b11")
.execute();
response.assertNoContent();
assertThat(cache.get(branch11.getUuid())).isNull();
assertThat(cache.get(branch12.getUuid())).isNotNull();
assertThat(cache.get(branch21.getUuid())).isNotNull();
}
@Test
public void should_fail_on_missing_project_key() {
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
TestRequest failingRequest = wsTester.newRequest().setParam(ClearAction.PARAM_BRANCH_KEY, "b11");
assertThatThrownBy(failingRequest::execute, "missing project key param with branch present should throw exception")
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void fail_if_not_global_admin() throws IOException {
ProjectDto project = dbTester.components().insertPrivateProject().getProjectDto();
dao.insert(dbTester.getSession(), "branch1", stringToInputStream("test data"));
DbInputStream branchDataIs = dao.selectData(dbTester.getSession(), "branch1");
assertThat(branchDataIs).isNotNull();
assertThat(dataStreamToString(branchDataIs)).isEqualTo("test data");
userSession.logIn().addProjectPermission(SCAN, project);
TestRequest request = wsTester.newRequest();
assertThatThrownBy(request::execute).isInstanceOf(ForbiddenException.class);
}
private static String dataStreamToString(DbInputStream dbInputStream) throws IOException {
try (DbInputStream ds = dbInputStream) {
return IOUtils.toString(ds, StandardCharsets.UTF_8);
}
}
private static InputStream stringToInputStream(String str) {
return new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
}
}
| 7,445 | 46.126582 | 119 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/scannercache/ws/GetActionIT.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.scannercache.ws;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.io.IOUtils;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbTester;
import org.sonar.db.audit.NoOpAuditPersister;
import org.sonar.db.component.BranchDao;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ProjectData;
import org.sonar.db.project.ProjectDao;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.scannercache.ScannerAnalysisCacheDao;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.scannercache.ScannerCache;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.web.UserRole.SCAN;
public class GetActionIT {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private final ScannerAnalysisCacheDao dao = new ScannerAnalysisCacheDao();
private final ProjectDao projectDao = new ProjectDao(System2.INSTANCE, new NoOpAuditPersister());
private final BranchDao branchDao = new BranchDao(System2.INSTANCE);
private final ScannerCache cache = new ScannerCache(dbTester.getDbClient(), dao, projectDao, branchDao);
private final ComponentFinder finder = new ComponentFinder(dbTester.getDbClient(), null);
private final GetAction ws = new GetAction(dbTester.getDbClient(), userSession, finder, cache);
private final WsActionTester wsTester = new WsActionTester(ws);
@Test
public void get_data_for_project() throws IOException {
ProjectData projectData = dbTester.components().insertPrivateProject();
BranchDto branch = dbTester.components().insertProjectBranch(projectData.getProjectDto());
ProjectData projectData2 = dbTester.components().insertPrivateProject();
dao.insert(dbTester.getSession(), projectData.getMainBranchDto().getUuid(), stringToCompressedInputStream("test data1"));
dao.insert(dbTester.getSession(), branch.getUuid(), stringToCompressedInputStream("test data2"));
dao.insert(dbTester.getSession(), projectData2.getMainBranchComponent().uuid(), stringToCompressedInputStream("test data3"));
userSession.logIn().addProjectPermission(SCAN, projectData.getProjectDto());
TestResponse response = wsTester.newRequest()
.setParam("project", projectData.projectKey())
.setHeader("Accept-Encoding", "gzip")
.execute();
assertThat(compressedInputStreamToString(response.getInputStream())).isEqualTo("test data1");
assertThat(response.getHeader("Content-Encoding")).isEqualTo("gzip");
}
@Test
public void get_uncompressed_data_for_project() throws IOException {
ProjectData projectData = dbTester.components().insertPrivateProject();
ProjectDto project1 = projectData.getProjectDto();
dao.insert(dbTester.getSession(), projectData.getMainBranchDto().getUuid(), stringToCompressedInputStream("test data1"));
userSession.logIn().addProjectPermission(SCAN, project1);
TestResponse response = wsTester.newRequest()
.setParam("project", project1.getKey())
.execute();
assertThat(response.getHeader("Content-Encoding")).isNull();
assertThat(response.getInput()).isEqualTo("test data1");
}
@Test
public void get_data_for_branch() throws IOException {
ProjectDto project1 = dbTester.components().insertPrivateProject().getProjectDto();
BranchDto branch = dbTester.components().insertProjectBranch(project1);
dao.insert(dbTester.getSession(), project1.getUuid(), stringToCompressedInputStream("test data1"));
dao.insert(dbTester.getSession(), branch.getUuid(), stringToCompressedInputStream("test data2"));
userSession.logIn().addProjectPermission(SCAN, project1)
.registerBranches(branch);
TestResponse response = wsTester.newRequest()
.setParam("project", project1.getKey())
.setParam("branch", branch.getKey())
.setHeader("Accept-Encoding", "gzip")
.execute();
assertThat(compressedInputStreamToString(response.getInputStream())).isEqualTo("test data2");
}
@Test
public void return_not_found_if_project_not_found() {
TestRequest request = wsTester
.newRequest()
.setParam("project", "project1");
assertThatThrownBy(request::execute).isInstanceOf(NotFoundException.class);
}
@Test
public void return_not_found_if_branch_mixed_with_pr() {
ProjectDto project1 = dbTester.components().insertPrivateProject().getProjectDto();
BranchDto branch = dbTester.components().insertProjectBranch(project1);
userSession.logIn().addProjectPermission(SCAN, project1);
TestRequest request = wsTester.newRequest()
.setParam("project", project1.getKey())
.setParam("pullRequest", branch.getKey());
assertThatThrownBy(request::execute).isInstanceOf(NotFoundException.class);
}
@Test
public void return_not_found_if_cache_not_found() {
ProjectDto project1 = dbTester.components().insertPrivateProject().getProjectDto();
userSession.logIn().addProjectPermission(SCAN, project1);
TestRequest request = wsTester
.newRequest()
.setParam("project", "project1");
assertThatThrownBy(request::execute).isInstanceOf(NotFoundException.class);
}
@Test
public void fail_if_no_permissions() {
ProjectDto project = dbTester.components().insertPrivateProject().getProjectDto();
userSession.logIn().addProjectPermission(UserRole.CODEVIEWER, project);
TestRequest request = wsTester
.newRequest()
.setParam("project", project.getKey());
assertThatThrownBy(request::execute).isInstanceOf(ForbiddenException.class);
}
private static String compressedInputStreamToString(InputStream inputStream) throws IOException {
return IOUtils.toString(new GZIPInputStream(inputStream), UTF_8);
}
private static InputStream stringToCompressedInputStream(String str) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream)) {
IOUtils.write(str.getBytes(UTF_8), gzipOutputStream);
}
return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
}
}
| 7,713 | 41.855556 | 129 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/CheckSecretKeyActionIT.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.setting.ws;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.config.internal.Encryption;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.server.ws.WebService;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Settings.CheckSecretKeyWsResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.test.JsonAssert.assertJson;
public class CheckSecretKeyActionIT {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private MapSettings settings = new MapSettings();
private Encryption encryption = settings.getEncryption();
private CheckSecretKeyAction underTest = new CheckSecretKeyAction(settings, userSession);
private WsActionTester ws = new WsActionTester(underTest);
@Test
public void json_example() throws IOException {
logInAsSystemAdministrator();
File secretKeyFile = temporaryFolder.newFile();
FileUtils.writeStringToFile(secretKeyFile, "fCVFf/JHRi8Qwu5KLNva7g==");
encryption.setPathToSecretKey(secretKeyFile.getAbsolutePath());
String result = ws.newRequest().execute().getInput();
assertJson(result).isSimilarTo(ws.getDef().responseExampleAsString());
}
@Test
public void false_when_no_secret_key() {
logInAsSystemAdministrator();
encryption.setPathToSecretKey("unknown/path/to_secret_key.txt");
CheckSecretKeyWsResponse result = call();
assertThat(result.getSecretKeyAvailable()).isFalse();
}
@Test
public void definition() {
WebService.Action definition = ws.getDef();
assertThat(definition.key()).isEqualTo("check_secret_key");
assertThat(definition.isPost()).isFalse();
assertThat(definition.isInternal()).isTrue();
assertThat(definition.since()).isEqualTo("6.1");
assertThat(definition.responseExampleAsString()).isNotEmpty();
assertThat(definition.params()).isEmpty();
}
@Test
public void throw_ForbiddenException_if_not_system_administrator() {
userSession.logIn().setNonSystemAdministrator();
assertThatThrownBy(() -> call())
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
private CheckSecretKeyWsResponse call() {
return ws.newRequest()
.setMethod("GET")
.executeProtobuf(CheckSecretKeyWsResponse.class);
}
private void logInAsSystemAdministrator() {
userSession.logIn().setSystemAdministrator();
}
}
| 3,676 | 33.688679 | 91 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/EncryptActionIT.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.setting.ws;
import java.io.File;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nullable;
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.api.config.internal.Encryption;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.server.ws.WebService;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Settings.EncryptWsResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_VALUE;
public class EncryptActionIT {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public TemporaryFolder folder = new TemporaryFolder();
private MapSettings settings = new MapSettings();
private Encryption encryption = settings.getEncryption();
private EncryptAction underTest = new EncryptAction(userSession, settings);
private WsActionTester ws = new WsActionTester(underTest);
@Before
public void setUpSecretKey() throws Exception {
logInAsSystemAdministrator();
File secretKeyFile = folder.newFile();
FileUtils.writeStringToFile(secretKeyFile, "fCVFf/JHRi8Qwu5KLNva7g==", StandardCharsets.UTF_8);
encryption.setPathToSecretKey(secretKeyFile.getAbsolutePath());
}
@Test
public void encrypt() {
logInAsSystemAdministrator();
EncryptWsResponse result = call("my value!");
assertThat(result.getEncryptedValue()).matches("^\\{aes-gcm\\}.+");
}
@Test
public void definition() {
WebService.Action definition = ws.getDef();
assertThat(definition.key()).isEqualTo("encrypt");
assertThat(definition.isPost()).isFalse();
assertThat(definition.isInternal()).isTrue();
assertThat(definition.responseExampleAsString()).isNotEmpty();
assertThat(definition.params()).hasSize(1);
}
@Test
public void throw_ForbiddenException_if_not_system_administrator() {
userSession.logIn().setNonSystemAdministrator();
assertThatThrownBy(() -> call("my value"))
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void fail_if_value_is_not_provided() {
logInAsSystemAdministrator();
assertThatThrownBy(() -> call(null))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void fail_if_value_is_empty() {
logInAsSystemAdministrator();
assertThatThrownBy(() -> call(" "))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The 'value' parameter is missing");
}
@Test
public void fail_if_no_secret_key_available() {
logInAsSystemAdministrator();
encryption.setPathToSecretKey("unknown/path/to/secret/key");
assertThatThrownBy(() -> call("my value"))
.isInstanceOf(BadRequestException.class)
.hasMessage("No secret key available");
}
private EncryptWsResponse call(@Nullable String value) {
TestRequest request = ws.newRequest()
.setMethod("POST");
if (value != null) {
request.setParam(PARAM_VALUE, value);
}
return request.executeProtobuf(EncryptWsResponse.class);
}
private void logInAsSystemAdministrator() {
userSession.logIn().setSystemAdministrator();
}
}
| 4,442 | 31.430657 | 99 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/GenerateSecretKeyActionIT.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.setting.ws;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.config.internal.Encryption;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.audit.NoOpAuditPersister;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Settings.GenerateSecretKeyWsResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class GenerateSecretKeyActionIT {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone().logIn().setSystemAdministrator();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private DbClient dbClient = db.getDbClient();
private MapSettings settings = new MapSettings();
private Encryption encryption = settings.getEncryption();
private GenerateSecretKeyAction underTest = new GenerateSecretKeyAction(dbClient, settings, userSession, new NoOpAuditPersister());
private WsActionTester ws = new WsActionTester(underTest);
@Test
public void generate_valid_secret_key() throws IOException {
GenerateSecretKeyWsResponse result = call();
String secretKey = result.getSecretKey();
File file = temporaryFolder.newFile();
FileUtils.writeStringToFile(file, secretKey, StandardCharsets.UTF_8);
encryption.setPathToSecretKey(file.getAbsolutePath());
String encryptedValue = encryption.encrypt("my value");
String decryptedValue = encryption.decrypt(encryptedValue);
assertThat(decryptedValue).isEqualTo("my value");
}
@Test
public void definition() {
WebService.Action definition = ws.getDef();
assertThat(definition.key()).isEqualTo("generate_secret_key");
assertThat(definition.isPost()).isFalse();
assertThat(definition.isInternal()).isTrue();
assertThat(definition.responseExampleAsString()).isNotEmpty();
assertThat(definition.params()).isEmpty();
}
@Test
public void throw_ForbiddenException_if_not_system_administrator() {
userSession.logIn().setNonSystemAdministrator();
assertThatThrownBy(() -> call())
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
private GenerateSecretKeyWsResponse call() {
return ws.newRequest()
.setMethod("GET")
.executeProtobuf(GenerateSecretKeyWsResponse.class);
}
}
| 3,691 | 36.292929 | 133 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/GenerateSecretKeyActionWithPersisterIT.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.setting.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.audit.AuditPersister;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Settings.GenerateSecretKeyWsResponse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class GenerateSecretKeyActionWithPersisterIT {
private final AuditPersister auditPersister = mock(AuditPersister.class);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone().logIn().setSystemAdministrator();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE, auditPersister);
private DbClient dbClient = db.getDbClient();
private MapSettings settings = new MapSettings();
private GenerateSecretKeyAction underTest = new GenerateSecretKeyAction(dbClient, settings, userSession, auditPersister);
private WsActionTester ws = new WsActionTester(underTest);
@Test
public void generateValidSecretKeyIsPersisted() {
call();
verify(auditPersister).generateSecretKey(any());
}
private GenerateSecretKeyWsResponse call() {
return ws.newRequest()
.setMethod("GET")
.executeProtobuf(GenerateSecretKeyWsResponse.class);
}
}
| 2,305 | 35.03125 | 123 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/ListDefinitionsActionIT.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.setting.ws;
import javax.annotation.Nullable;
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.PropertyFieldDefinition;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonar.test.JsonAssert;
import org.sonarqube.ws.Settings;
import org.sonarqube.ws.Settings.Definition;
import org.sonarqube.ws.Settings.ListDefinitionsWsResponse;
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.assertj.core.groups.Tuple.tuple;
import static org.sonar.api.resources.Qualifiers.PROJECT;
import static org.sonarqube.ws.MediaTypes.JSON;
import static org.sonarqube.ws.Settings.Definition.CategoryOneOfCase.CATEGORYONEOF_NOT_SET;
import static org.sonarqube.ws.Settings.Definition.DefaultValueOneOfCase.DEFAULTVALUEONEOF_NOT_SET;
import static org.sonarqube.ws.Settings.Definition.DeprecatedKeyOneOfCase.DEPRECATEDKEYONEOF_NOT_SET;
import static org.sonarqube.ws.Settings.Definition.NameOneOfCase.NAMEONEOF_NOT_SET;
import static org.sonarqube.ws.Settings.Definition.SubCategoryOneOfCase.SUBCATEGORYONEOF_NOT_SET;
import static org.sonarqube.ws.Settings.Type.BOOLEAN;
import static org.sonarqube.ws.Settings.Type.LICENSE;
import static org.sonarqube.ws.Settings.Type.PROPERTY_SET;
import static org.sonarqube.ws.Settings.Type.SINGLE_SELECT_LIST;
import static org.sonarqube.ws.Settings.Type.STRING;
import static org.sonarqube.ws.Settings.Type.TEXT;
public class ListDefinitionsActionIT {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private final DbClient dbClient = db.getDbClient();
private ProjectDto project;
private final PropertyDefinitions propertyDefinitions = new PropertyDefinitions(System2.INSTANCE);
private final SettingsWsSupport support = new SettingsWsSupport(userSession);
private final WsActionTester ws = new WsActionTester(new ListDefinitionsAction(dbClient, userSession, propertyDefinitions, support));
@Before
public void setUp() {
project = db.components().insertPrivateProject().getProjectDto();
}
@Test
public void return_settings_definitions() {
logIn();
propertyDefinitions.addComponent(PropertyDefinition
.builder("foo")
.name("Foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.TEXT)
.defaultValue("default")
.multiValues(true)
.build());
ListDefinitionsWsResponse result = executeRequest();
assertThat(result.getDefinitionsList()).hasSize(1);
Definition definition = result.getDefinitions(0);
assertThat(definition.getKey()).isEqualTo("foo");
assertThat(definition.getName()).isEqualTo("Foo");
assertThat(definition.getDescription()).isEqualTo("desc");
assertThat(definition.getCategory()).isEqualTo("cat");
assertThat(definition.getSubCategory()).isEqualTo("subCat");
assertThat(definition.getType()).isEqualTo(TEXT);
assertThat(definition.getDefaultValue()).isEqualTo("default");
assertThat(definition.getMultiValues()).isTrue();
}
@Test
public void return_settings_definitions_with_minimum_fields() {
logIn();
propertyDefinitions.addComponent(PropertyDefinition
.builder("foo")
.build());
ListDefinitionsWsResponse result = executeRequest();
assertThat(result.getDefinitionsList()).hasSize(1);
Definition definition = result.getDefinitions(0);
assertThat(definition.getKey()).isEqualTo("foo");
assertThat(definition.getType()).isEqualTo(STRING);
assertThat(definition.getNameOneOfCase()).isEqualTo(NAMEONEOF_NOT_SET);
assertThat(definition.getCategoryOneOfCase()).isEqualTo(CATEGORYONEOF_NOT_SET);
assertThat(definition.getSubCategoryOneOfCase()).isEqualTo(SUBCATEGORYONEOF_NOT_SET);
assertThat(definition.getDefaultValueOneOfCase()).isEqualTo(DEFAULTVALUEONEOF_NOT_SET);
assertThat(definition.getMultiValues()).isFalse();
assertThat(definition.getOptionsCount()).isZero();
assertThat(definition.getFieldsCount()).isZero();
assertThat(definition.getDeprecatedKeyOneOfCase()).isEqualTo(DEPRECATEDKEYONEOF_NOT_SET);
}
@Test
public void return_settings_definitions_with_deprecated_key() {
logIn();
propertyDefinitions.addComponent(PropertyDefinition
.builder("foo")
.name("Foo")
.deprecatedKey("deprecated")
.build());
ListDefinitionsWsResponse result = executeRequest();
assertThat(result.getDefinitionsList()).hasSize(1);
Definition definition = result.getDefinitions(0);
assertThat(definition.getKey()).isEqualTo("foo");
assertThat(definition.getName()).isEqualTo("Foo");
assertThat(definition.getDeprecatedKey()).isEqualTo("deprecated");
}
@Test
public void return_default_category() {
logIn();
propertyDefinitions.addComponent(PropertyDefinition.builder("foo").build(), "default");
propertyDefinitions.addComponent(PropertyDefinition.builder("foo").category("").build(), "default");
ListDefinitionsWsResponse result = executeRequest();
assertThat(result.getDefinitionsList()).hasSize(1);
assertThat(result.getDefinitions(0).getCategory()).isEqualTo("default");
assertThat(result.getDefinitions(0).getSubCategory()).isEqualTo("default");
}
@Test
public void return_single_select_list_property() {
logIn();
propertyDefinitions.addComponent(PropertyDefinition
.builder("foo")
.type(PropertyType.SINGLE_SELECT_LIST)
.options("one", "two")
.build());
ListDefinitionsWsResponse result = executeRequest();
assertThat(result.getDefinitionsList()).hasSize(1);
Definition definition = result.getDefinitions(0);
assertThat(definition.getType()).isEqualTo(SINGLE_SELECT_LIST);
assertThat(definition.getOptionsList()).containsExactly("one", "two");
}
@Test
public void return_JSON_property() {
logIn();
propertyDefinitions.addComponent(PropertyDefinition
.builder("foo")
.type(PropertyType.JSON)
.build());
ListDefinitionsWsResponse result = executeRequest();
assertThat(result.getDefinitionsList()).hasSize(1);
Definition definition = result.getDefinitions(0);
assertThat(definition.getType()).isEqualTo(Settings.Type.JSON);
}
@Test
public void return_property_set() {
logIn();
propertyDefinitions.addComponent(PropertyDefinition
.builder("foo")
.type(PropertyType.PROPERTY_SET)
.fields(
PropertyFieldDefinition.build("boolean").name("Boolean").description("boolean desc").type(PropertyType.BOOLEAN).build(),
PropertyFieldDefinition.build("list").name("List").description("list desc").type(PropertyType.SINGLE_SELECT_LIST).options("one", "two").build())
.build());
ListDefinitionsWsResponse result = executeRequest();
assertThat(result.getDefinitionsList()).hasSize(1);
Definition definition = result.getDefinitions(0);
assertThat(definition.getType()).isEqualTo(PROPERTY_SET);
assertThat(definition.getFieldsList()).hasSize(2);
assertThat(definition.getFields(0).getKey()).isEqualTo("boolean");
assertThat(definition.getFields(0).getName()).isEqualTo("Boolean");
assertThat(definition.getFields(0).getDescription()).isEqualTo("boolean desc");
assertThat(definition.getFields(0).getType()).isEqualTo(BOOLEAN);
assertThat(definition.getFields(0).getOptionsCount()).isZero();
assertThat(definition.getFields(1).getKey()).isEqualTo("list");
assertThat(definition.getFields(1).getName()).isEqualTo("List");
assertThat(definition.getFields(1).getDescription()).isEqualTo("list desc");
assertThat(definition.getFields(1).getType()).isEqualTo(SINGLE_SELECT_LIST);
assertThat(definition.getFields(1).getOptionsList()).containsExactly("one", "two");
}
@Test
public void return_license_type_in_property_set() {
logIn();
propertyDefinitions.addComponent(PropertyDefinition
.builder("foo")
.type(PropertyType.PROPERTY_SET)
.fields(PropertyFieldDefinition.build("license").name("License").type(PropertyType.LICENSE).build())
.build());
ListDefinitionsWsResponse result = executeRequest();
assertThat(result.getDefinitionsList()).hasSize(1);
assertThat(result.getDefinitions(0).getFieldsList()).extracting(Settings.Field::getKey, Settings.Field::getType).containsOnly(tuple("license", LICENSE));
}
@Test
public void return_global_settings_definitions() {
logIn();
propertyDefinitions.addComponent(PropertyDefinition.builder("foo").build());
ListDefinitionsWsResponse result = executeRequest();
assertThat(result.getDefinitionsList()).hasSize(1);
}
@Test
public void definitions_are_ordered_by_category_then_index_then_name_case_insensitive() {
logIn();
propertyDefinitions.addComponent(PropertyDefinition.builder("sonar.prop.11").category("cat-1").index(1).name("prop 1").build());
propertyDefinitions.addComponent(PropertyDefinition.builder("sonar.prop.12").category("cat-1").index(2).name("prop 2").build());
propertyDefinitions.addComponent(PropertyDefinition.builder("sonar.prop.13").category("CAT-1").index(1).name("prop 3").build());
propertyDefinitions.addComponent(PropertyDefinition.builder("sonar.prop.41").category("cat-0").index(25).name("prop 1").build());
ListDefinitionsWsResponse result = executeRequest();
assertThat(result.getDefinitionsList()).extracting(Definition::getKey)
.containsExactly("sonar.prop.41", "sonar.prop.11", "sonar.prop.13", "sonar.prop.12");
}
@Test
public void return_project_settings_def_by_project_key() {
logInAsProjectUser();
propertyDefinitions.addComponent(PropertyDefinition
.builder("foo")
.onQualifiers(PROJECT)
.build());
ListDefinitionsWsResponse result = executeRequest(project.getKey());
assertThat(result.getDefinitionsList()).hasSize(1);
}
@Test
public void return_only_global_properties_when_no_component_parameter() {
logInAsProjectUser();
propertyDefinitions.addComponents(asList(
PropertyDefinition.builder("global").build(),
PropertyDefinition.builder("global-and-project").onQualifiers(PROJECT).build(),
PropertyDefinition.builder("only-on-project").onlyOnQualifiers(PROJECT).build()));
ListDefinitionsWsResponse result = executeRequest();
assertThat(result.getDefinitionsList()).extracting("key").containsOnly("global", "global-and-project");
}
@Test
public void return_only_properties_available_for_component_qualifier() {
logInAsProjectUser();
propertyDefinitions.addComponents(asList(
PropertyDefinition.builder("global").build(),
PropertyDefinition.builder("global-and-project").onQualifiers(PROJECT).build(),
PropertyDefinition.builder("only-on-project").onlyOnQualifiers(PROJECT).build()));
ListDefinitionsWsResponse result = executeRequest(project.getKey());
assertThat(result.getDefinitionsList()).extracting("key").containsOnly("global-and-project", "only-on-project");
}
@Test
public void does_not_return_hidden_properties() {
logInAsAdmin();
propertyDefinitions.addComponent(PropertyDefinition.builder("foo").hidden().build());
ListDefinitionsWsResponse result = executeRequest();
assertThat(result.getDefinitionsList()).isEmpty();
}
@Test
public void return_license_type() {
logInAsAdmin();
propertyDefinitions.addComponents(asList(
PropertyDefinition.builder("plugin.license.secured").type(PropertyType.LICENSE).build(),
PropertyDefinition.builder("commercial.plugin").type(PropertyType.LICENSE).build()));
ListDefinitionsWsResponse result = executeRequest();
assertThat(result.getDefinitionsList()).extracting(Definition::getKey, Definition::getType)
.containsOnly(tuple("plugin.license.secured", LICENSE), tuple("commercial.plugin", LICENSE));
}
@Test
public void does_not_returned_secured_and_license_settings_when_not_authenticated() {
propertyDefinitions.addComponents(asList(
PropertyDefinition.builder("foo").build(),
PropertyDefinition.builder("secret.secured").build()));
ListDefinitionsWsResponse result = executeRequest();
assertThat(result.getDefinitionsList()).extracting(Definition::getKey).containsOnly("foo");
}
@Test
public void return_secured_settings_when_not_authenticated_but_with_scan_permission() {
userSession.anonymous().addPermission(GlobalPermission.SCAN);
propertyDefinitions.addComponents(asList(
PropertyDefinition.builder("foo").build(),
PropertyDefinition.builder("secret.secured").build()));
ListDefinitionsWsResponse result = executeRequest();
assertThat(result.getDefinitionsList()).extracting(Definition::getKey).containsOnly("foo", "secret.secured");
}
@Test
public void return_secured_settings_when_system_admin() {
logInAsAdmin();
propertyDefinitions.addComponents(asList(
PropertyDefinition.builder("foo").build(),
PropertyDefinition.builder("secret.secured").build()));
ListDefinitionsWsResponse result = executeRequest();
assertThat(result.getDefinitionsList()).extracting(Definition::getKey).containsOnly("foo", "secret.secured");
}
@Test
public void return_secured_settings_when_project_admin() {
logInAsProjectAdmin();
propertyDefinitions.addComponents(asList(
PropertyDefinition.builder("foo").onQualifiers(PROJECT).build(),
PropertyDefinition.builder("secret.secured").onQualifiers(PROJECT).build()));
ListDefinitionsWsResponse result = executeRequest(project.getKey());
assertThat(result.getDefinitionsList()).extracting(Definition::getKey).containsOnly("foo", "secret.secured");
}
@Test
public void fail_when_user_has_not_project_browse_permission() {
userSession.logIn("project-admin").addProjectPermission(UserRole.CODEVIEWER, project);
propertyDefinitions.addComponent(PropertyDefinition.builder("foo").build());
assertThatThrownBy(() -> executeRequest(project.getKey()))
.isInstanceOf(ForbiddenException.class);
}
@Test
public void fail_when_component_not_found() {
assertThatThrownBy(() -> {
ws.newRequest()
.setParam("component", "unknown")
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Component key 'unknown' not found");
}
@Test
public void test_ws_definition() {
WebService.Action action = ws.getDef();
assertThat(action).isNotNull();
assertThat(action.isInternal()).isFalse();
assertThat(action.isPost()).isFalse();
assertThat(action.responseExampleAsString()).isNotEmpty();
assertThat(action.params()).extracting(Param::key).containsExactlyInAnyOrder("component");
}
@Test
public void test_example_json_response() {
logInAsProjectAdmin();
propertyDefinitions.addComponents(asList(
PropertyDefinition.builder("sonar.string")
.name("String")
.description("String property")
.type(PropertyType.STRING)
.category("general")
.subCategory("test")
.defaultValue("123")
.build(),
PropertyDefinition.builder("sonar.list")
.name("List")
.description("List property")
.type(PropertyType.SINGLE_SELECT_LIST)
.category("general")
.options("a", "b")
.build(),
PropertyDefinition.builder("sonar.multiValues")
.name("Multi values")
.description("Multi values property")
.type(PropertyType.STRING)
.category("general")
.multiValues(true)
.build(),
PropertyDefinition.builder("sonar.propertySet")
.name("Property Set")
.description("Property Set property")
.type(PropertyType.PROPERTY_SET)
.category("property")
.subCategory("set")
.fields(
PropertyFieldDefinition.build("text")
.name("Text")
.description("Text field description")
.type(PropertyType.TEXT)
.build(),
PropertyFieldDefinition.build("list")
.name("List")
.description("List field description")
.type(PropertyType.SINGLE_SELECT_LIST)
.options("value1", "value2")
.build())
.build()));
String result = ws.newRequest().setMediaType(JSON).execute().getInput();
JsonAssert.assertJson(ws.getDef().responseExampleAsString()).isSimilarTo(result);
}
private ListDefinitionsWsResponse executeRequest() {
return executeRequest(null);
}
private ListDefinitionsWsResponse executeRequest(@Nullable String key) {
TestRequest request = ws.newRequest();
if (key != null) {
request.setParam("component", key);
}
return request.executeProtobuf(ListDefinitionsWsResponse.class);
}
private void logIn() {
userSession.logIn();
}
private void logInAsProjectUser() {
userSession.logIn().addProjectPermission(UserRole.USER, project);
}
private void logInAsAdmin() {
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
}
private void logInAsProjectAdmin() {
userSession.logIn()
.addProjectPermission(UserRole.ADMIN, project)
.addProjectPermission(UserRole.USER, project);
}
}
| 18,877 | 37.605317 | 157 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/ResetActionIT.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.setting.ws;
import java.util.Random;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.portfolio.PortfolioDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.property.PropertyDbTester;
import org.sonar.db.property.PropertyQuery;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserTesting;
import org.sonar.process.ProcessProperties;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.l18n.I18nRule;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.MediaTypes;
import static java.lang.String.format;
import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.resources.Qualifiers.PROJECT;
import static org.sonar.api.resources.Qualifiers.VIEW;
import static org.sonar.api.web.UserRole.ADMIN;
import static org.sonar.api.web.UserRole.USER;
import static org.sonar.db.property.PropertyTesting.newComponentPropertyDto;
import static org.sonar.db.property.PropertyTesting.newGlobalPropertyDto;
import static org.sonar.db.property.PropertyTesting.newUserPropertyDto;
public class ResetActionIT {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private final I18nRule i18n = new I18nRule();
private final PropertyDbTester propertyDb = new PropertyDbTester(db);
private final DbClient dbClient = db.getDbClient();
private final DbSession dbSession = db.getSession();
private final PropertyDefinitions definitions = new PropertyDefinitions(System2.INSTANCE);
private final SettingsUpdater settingsUpdater = new SettingsUpdater(dbClient, definitions);
private final SettingValidations settingValidations = new SettingValidations(definitions, dbClient, i18n);
private ProjectDto project;
private final ResetAction underTest = new ResetAction(dbClient, settingsUpdater, userSession, definitions, settingValidations);
private final WsActionTester ws = new WsActionTester(underTest);
@Before
public void setUp() {
project = db.components().insertPrivateProject().getProjectDto();
}
@Test
public void remove_global_setting() {
logInAsSystemAdministrator();
definitions.addComponent(PropertyDefinition.builder("foo").build());
propertyDb.insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("one"));
executeRequestOnGlobalSetting("foo");
assertGlobalPropertyDoesNotExist("foo");
}
@Test
public void remove_global_setting_even_if_not_defined() {
logInAsSystemAdministrator();
propertyDb.insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("one"));
executeRequestOnGlobalSetting("foo");
assertGlobalPropertyDoesNotExist("foo");
}
@Test
public void remove_component_setting() {
logInAsProjectAdmin();
definitions.addComponent(PropertyDefinition.builder("foo").onQualifiers(PROJECT).build());
propertyDb.insertProperties(null, null, null, null, newComponentPropertyDto(project).setKey("foo").setValue("value"));
executeRequestOnProjectSetting("foo");
assertProjectPropertyDoesNotExist("foo");
}
@Test
public void remove_component_setting_even_if_not_defined() {
logInAsProjectAdmin();
propertyDb.insertProperties(null, null, null, null, newComponentPropertyDto(project).setKey("foo").setValue("value"));
executeRequestOnProjectSetting("foo");
assertProjectPropertyDoesNotExist("foo");
}
@Test
public void remove_hidden_setting() {
logInAsSystemAdministrator();
definitions.addComponent(PropertyDefinition.builder("foo").hidden().build());
propertyDb.insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("one"));
executeRequestOnGlobalSetting("foo");
assertGlobalPropertyDoesNotExist("foo");
}
@Test
public void ignore_project_setting_when_removing_global_setting() {
logInAsSystemAdministrator();
propertyDb.insertProperties(null, null, null, null,
newGlobalPropertyDto().setKey("foo").setValue("one"));
propertyDb.insertProperties(null, project.getKey(), project.getName(), project.getQualifier(),
newComponentPropertyDto(project).setKey("foo").setValue("value"));
executeRequestOnGlobalSetting("foo");
assertGlobalPropertyDoesNotExist("foo");
assertProjectPropertyExists("foo");
}
@Test
public void ignore_global_setting_when_removing_project_setting() {
logInAsProjectAdmin();
propertyDb.insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("one"));
propertyDb.insertProperties(null, project.getKey(), project.getName(), project.getQualifier(),
newComponentPropertyDto(project).setKey("foo").setValue("value"));
executeRequestOnProjectSetting("foo");
assertGlobalPropertyExists("foo");
assertProjectPropertyDoesNotExist("foo");
}
@Test
public void ignore_user_setting_when_removing_global_setting() {
logInAsSystemAdministrator();
UserDto user = dbClient.userDao().insert(dbSession, UserTesting.newUserDto());
propertyDb.insertProperties(user.getLogin(), null, null, null, newUserPropertyDto("foo", "one", user));
executeRequestOnGlobalSetting("foo");
assertUserPropertyExists("foo", user);
}
@Test
public void ignore_user_setting_when_removing_project_setting() {
logInAsProjectAdmin();
UserDto user = dbClient.userDao().insert(dbSession, UserTesting.newUserDto());
propertyDb.insertProperties(user.getLogin(), null, null, null, newUserPropertyDto("foo", "one", user));
executeRequestOnProjectSetting("foo");
assertUserPropertyExists("foo", user);
}
@Test
public void ignore_unknown_setting_key() {
logInAsSystemAdministrator();
executeRequestOnGlobalSetting("unknown");
}
@Test
public void remove_setting_by_deprecated_key() {
logInAsSystemAdministrator();
definitions.addComponent(PropertyDefinition.builder("foo").deprecatedKey("old").build());
propertyDb.insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("one"));
executeRequestOnGlobalSetting("old");
assertGlobalPropertyDoesNotExist("foo");
}
@Test
public void empty_204_response() {
logInAsSystemAdministrator();
TestResponse result = ws.newRequest()
.setParam("keys", "my.key")
.execute();
assertThat(result.getStatus()).isEqualTo(HTTP_NO_CONTENT);
assertThat(result.getInput()).isEmpty();
}
@Test
public void test_ws_definition() {
WebService.Action action = ws.getDef();
assertThat(action).isNotNull();
assertThat(action.isInternal()).isFalse();
assertThat(action.isPost()).isTrue();
assertThat(action.responseExampleAsString()).isNull();
assertThat(action.params()).extracting(Param::key).containsExactlyInAnyOrder("keys", "component");
}
@Test
public void throw_ForbiddenException_if_global_setting_and_not_system_administrator() {
userSession.logIn().setNonSystemAdministrator();
definitions.addComponent(PropertyDefinition.builder("foo").build());
assertThatThrownBy(() -> executeRequestOnGlobalSetting("foo"))
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void throw_ForbiddenException_if_project_setting_and_not_project_administrator() {
userSession.logIn().addProjectPermission(USER, project);
definitions.addComponent(PropertyDefinition.builder("foo").build());
assertThatThrownBy(() -> executeRequestOnComponentSetting("foo", project))
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void throw_ForbiddenException_if_project_setting_and_system_administrator() {
logInAsSystemAdministrator();
definitions.addComponent(PropertyDefinition.builder("foo").build());
assertThatThrownBy(() -> executeRequestOnComponentSetting("foo", project))
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void fail_when_not_global_and_no_component() {
logInAsSystemAdministrator();
definitions.addComponent(PropertyDefinition.builder("foo")
.onlyOnQualifiers(VIEW)
.build());
assertThatThrownBy(() -> executeRequestOnGlobalSetting("foo"))
.isInstanceOf(BadRequestException.class)
.hasMessage("Setting 'foo' cannot be global");
}
@Test
public void fail_when_qualifier_not_included() {
userSession.logIn().addProjectPermission(ADMIN, project);
definitions.addComponent(PropertyDefinition.builder("foo")
.onQualifiers(VIEW)
.build());
i18n.put("qualifier." + PROJECT, "project");
assertThatThrownBy(() -> executeRequestOnComponentSetting("foo", project))
.isInstanceOf(BadRequestException.class)
.hasMessage("Setting 'foo' cannot be set on a project");
}
@Test
public void fail_to_reset_setting_component_when_setting_is_global() {
userSession.logIn().addProjectPermission(ADMIN, project);
definitions.addComponent(PropertyDefinition.builder("foo").build());
i18n.put("qualifier." + PROJECT, "project");
assertThatThrownBy(() -> executeRequestOnComponentSetting("foo", project))
.isInstanceOf(BadRequestException.class)
.hasMessage("Setting 'foo' cannot be set on a project");
}
@Test
public void succeed_for_property_without_definition_when_set_on_project_component() {
ProjectDto project = randomPublicOrPrivateProject();
succeedForPropertyWithoutDefinitionAndValidComponent(project);
}
@Test
public void succeed_for_property_without_definition_when_set_on_view_component() {
PortfolioDto view = db.components().insertPublicPortfolioDto();
succeedForPropertyWithoutDefinitionAndValidComponent(view);
}
@Test
public void fail_when_component_not_found() {
TestRequest request = ws.newRequest()
.setParam("keys", "foo")
.setParam("component", "unknown");
assertThatThrownBy(() -> request.execute())
.isInstanceOf(NotFoundException.class)
.hasMessage("Component key 'unknown' not found");
}
@Test
public void fail_when_setting_key_is_defined_in_sonar_properties() {
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
logInAsProjectAdmin(project);
String settingKey = ProcessProperties.Property.JDBC_URL.getKey();
TestRequest request = ws.newRequest()
.setParam("keys", settingKey)
.setParam("component", project.getKey());
assertThatThrownBy(() -> request.execute())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(format("Setting '%s' can only be used in sonar.properties", settingKey));
}
private void succeedForPropertyWithoutDefinitionAndValidComponent(ProjectDto project) {
logInAsProjectAdmin(project);
executeRequestOnComponentSetting("foo", project);
}
private void succeedForPropertyWithoutDefinitionAndValidComponent(PortfolioDto project) {
logInAsProjectAdmin(project);
executeRequestOnComponentSetting("foo", project);
}
private void executeRequestOnGlobalSetting(String key) {
executeRequest(key, null);
}
private void executeRequestOnProjectSetting(String key) {
executeRequest(key, project.getKey());
}
private void executeRequestOnComponentSetting(String key, EntityDto entity) {
executeRequest(key, entity.getKey());
}
private void executeRequest(String key, @Nullable String componentKey) {
TestRequest request = ws.newRequest()
.setMediaType(MediaTypes.PROTOBUF)
.setParam("keys", key);
if (componentKey != null) {
request.setParam("component", componentKey);
}
request.execute();
}
private void logInAsSystemAdministrator() {
userSession.logIn().setSystemAdministrator();
}
private void logInAsProjectAdmin() {
userSession.logIn().addProjectPermission(ADMIN, project);
}
private void logInAsProjectAdmin(ProjectDto root) {
userSession.logIn().addProjectPermission(ADMIN, root);
}
private void logInAsProjectAdmin(PortfolioDto root) {
userSession.logIn().addPortfolioPermission(ADMIN, root);
}
private void assertGlobalPropertyDoesNotExist(String key) {
assertThat(dbClient.propertiesDao().selectGlobalProperty(dbSession, key)).isNull();
}
private void assertGlobalPropertyExists(String key) {
assertThat(dbClient.propertiesDao().selectGlobalProperty(dbSession, key)).isNotNull();
}
private void assertProjectPropertyDoesNotExist(EntityDto entity, String key) {
assertThat(dbClient.propertiesDao().selectByQuery(PropertyQuery.builder().setEntityUuid(entity.getUuid()).setKey(key).build(), dbSession)).isEmpty();
}
private void assertProjectPropertyDoesNotExist(String key) {
assertProjectPropertyDoesNotExist(project, key);
}
private void assertProjectPropertyExists(String key) {
assertThat(dbClient.propertiesDao().selectByQuery(PropertyQuery.builder().setEntityUuid(project.getUuid()).setKey(key).build(), dbSession)).isNotEmpty();
}
private void assertUserPropertyExists(String key, UserDto user) {
assertThat(dbClient.propertiesDao().selectByQuery(PropertyQuery.builder()
.setKey(key)
.setUserUuid(user.getUuid())
.build(),
dbSession)).isNotEmpty();
}
private ProjectDto randomPublicOrPrivateProject() {
return new Random().nextBoolean() ? db.components().insertPrivateProject().getProjectDto() : db.components().insertPublicProject().getProjectDto();
}
}
| 15,201 | 36.44335 | 157 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/SetActionIT.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.setting.ws;
import com.google.gson.Gson;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.PropertyType;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.PropertyFieldDefinition;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.component.ProjectData;
import org.sonar.db.portfolio.PortfolioDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.property.PropertyDbTester;
import org.sonar.db.property.PropertyDto;
import org.sonar.db.property.PropertyQuery;
import org.sonar.process.ProcessProperties;
import org.sonar.scanner.protocol.GsonHelper;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.l18n.I18nRule;
import org.sonar.server.setting.SettingsChangeNotifier;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static java.lang.String.format;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.groups.Tuple.tuple;
import static org.sonar.db.metric.MetricTesting.newMetricDto;
import static org.sonar.db.property.PropertyTesting.newComponentPropertyDto;
import static org.sonar.db.property.PropertyTesting.newGlobalPropertyDto;
import static org.sonar.db.user.UserTesting.newUserDto;
@RunWith(DataProviderRunner.class)
public class SetActionIT {
private static final Gson GSON = GsonHelper.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone().logIn();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private final PropertyDbTester propertyDb = new PropertyDbTester(db);
private final DbClient dbClient = db.getDbClient();
private final DbSession dbSession = db.getSession();
private final I18nRule i18n = new I18nRule();
private final PropertyDefinitions definitions = new PropertyDefinitions(System2.INSTANCE);
private final FakeSettingsNotifier settingsChangeNotifier = new FakeSettingsNotifier(dbClient);
private final SettingsUpdater settingsUpdater = new SettingsUpdater(dbClient, definitions);
private final SettingValidations validations = new SettingValidations(definitions, dbClient, i18n);
private final SetAction underTest = new SetAction(definitions, dbClient, userSession, settingsUpdater, settingsChangeNotifier, validations);
private final WsActionTester ws = new WsActionTester(underTest);
@Before
public void setUp() {
// by default test doesn't care about permissions
userSession.logIn().setSystemAdministrator();
}
@DataProvider
public static Object[][] securityJsonProperties() {
return new Object[][] {
{"sonar.security.config.javasecurity"},
{"sonar.security.config.phpsecurity"},
{"sonar.security.config.pythonsecurity"},
{"sonar.security.config.roslyn.sonaranalyzer.security.cs"}
};
}
@Test
public void empty_204_response() {
TestResponse result = ws.newRequest()
.setParam("key", "my.key")
.setParam("value", "my value")
.execute();
assertThat(result.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
assertThat(result.getInput()).isEmpty();
}
@Test
public void persist_new_global_setting() {
callForGlobalSetting("my.key", "my,value");
assertGlobalSetting("my.key", "my,value");
assertThat(settingsChangeNotifier.wasCalled).isTrue();
}
@Test
public void update_existing_global_setting() {
propertyDb.insertProperty(newGlobalPropertyDto("my.key", "my value"), null, null, null, null);
assertGlobalSetting("my.key", "my value");
callForGlobalSetting("my.key", "my new value");
assertGlobalSetting("my.key", "my new value");
assertThat(settingsChangeNotifier.wasCalled).isTrue();
}
@Test
public void persist_new_project_setting() {
propertyDb.insertProperty(newGlobalPropertyDto("my.key", "my global value"), null, null, null, null);
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
logInAsProjectAdministrator(project);
callForProjectSettingByKey("my.key", "my project value", project.getKey());
assertGlobalSetting("my.key", "my global value");
assertComponentSetting("my.key", "my project value", project.getUuid());
assertThat(settingsChangeNotifier.wasCalled).isFalse();
}
@Test
public void persist_new_subportfolio_setting() {
propertyDb.insertProperty(newGlobalPropertyDto("my.key", "my global value"), null, null, null, null);
ComponentDto portfolio = db.components().insertPrivatePortfolio();
ComponentDto subportfolio = db.components().insertSubportfolio(portfolio);
logInAsPortfolioAdministrator(db.components().getPortfolioDto(portfolio));
callForProjectSettingByKey("my.key", "my project value", subportfolio.getKey());
assertGlobalSetting("my.key", "my global value");
assertComponentSetting("my.key", "my project value", subportfolio.uuid());
assertThat(settingsChangeNotifier.wasCalled).isFalse();
}
@Test
public void persist_project_property_with_project_admin_permission() {
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
logInAsProjectAdministrator(project);
callForProjectSettingByKey("my.key", "my value", project.getKey());
assertComponentSetting("my.key", "my value", project.getUuid());
}
@Test
public void update_existing_project_setting() {
propertyDb.insertProperty(newGlobalPropertyDto("my.key", "my global value"), null, null,
null, null);
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
propertyDb.insertProperty(newComponentPropertyDto("my.key", "my project value", project), project.getKey(),
project.getName(), null, null);
assertComponentSetting("my.key", "my project value", project.getUuid());
logInAsProjectAdministrator(project);
callForProjectSettingByKey("my.key", "my new project value", project.getKey());
assertComponentSetting("my.key", "my new project value", project.getUuid());
}
@Test
public void persist_several_multi_value_setting() {
callForMultiValueGlobalSetting("my.key", List.of("first,Value", "second,Value", "third,Value"));
String expectedValue = "first%2CValue,second%2CValue,third%2CValue";
assertGlobalSetting("my.key", expectedValue);
assertThat(settingsChangeNotifier.wasCalled).isTrue();
}
@Test
public void persist_one_multi_value_setting() {
callForMultiValueGlobalSetting("my.key", List.of("first,Value"));
assertGlobalSetting("my.key", "first%2CValue");
}
@Test
public void persist_property_set_setting() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.PROPERTY_SET)
.defaultValue("default")
.fields(List.of(
PropertyFieldDefinition.build("firstField")
.name("First Field")
.type(PropertyType.STRING)
.build(),
PropertyFieldDefinition.build("secondField")
.name("Second Field")
.type(PropertyType.STRING)
.build()))
.build());
callForGlobalPropertySet("my.key", List.of(
GSON.toJson(Map.of("firstField", "firstValue", "secondField", "secondValue")),
GSON.toJson(Map.of("firstField", "anotherFirstValue", "secondField", "anotherSecondValue")),
GSON.toJson(Map.of("firstField", "yetFirstValue", "secondField", "yetSecondValue"))));
assertThat(dbClient.propertiesDao().selectGlobalProperties(dbSession)).hasSize(7);
assertGlobalSetting("my.key", "1,2,3");
assertGlobalSetting("my.key.1.firstField", "firstValue");
assertGlobalSetting("my.key.1.secondField", "secondValue");
assertGlobalSetting("my.key.2.firstField", "anotherFirstValue");
assertGlobalSetting("my.key.2.secondField", "anotherSecondValue");
assertGlobalSetting("my.key.3.firstField", "yetFirstValue");
assertGlobalSetting("my.key.3.secondField", "yetSecondValue");
assertThat(settingsChangeNotifier.wasCalled).isTrue();
}
@Test
public void update_property_set_setting() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.PROPERTY_SET)
.defaultValue("default")
.fields(List.of(
PropertyFieldDefinition.build("firstField")
.name("First Field")
.type(PropertyType.STRING)
.build(),
PropertyFieldDefinition.build("secondField")
.name("Second Field")
.type(PropertyType.STRING)
.build()))
.build());
propertyDb.insertProperties(null, null, null, null,
newGlobalPropertyDto("my.key", "1,2,3,4"),
newGlobalPropertyDto("my.key.1.firstField", "oldFirstValue"),
newGlobalPropertyDto("my.key.1.secondField", "oldSecondValue"),
newGlobalPropertyDto("my.key.2.firstField", "anotherOldFirstValue"),
newGlobalPropertyDto("my.key.2.secondField", "anotherOldSecondValue"),
newGlobalPropertyDto("my.key.3.firstField", "oldFirstValue"),
newGlobalPropertyDto("my.key.3.secondField", "oldSecondValue"),
newGlobalPropertyDto("my.key.4.firstField", "anotherOldFirstValue"),
newGlobalPropertyDto("my.key.4.secondField", "anotherOldSecondValue"));
callForGlobalPropertySet("my.key", List.of(
GSON.toJson(Map.of("firstField", "firstValue", "secondField", "secondValue")),
GSON.toJson(Map.of("firstField", "anotherFirstValue", "secondField", "anotherSecondValue")),
GSON.toJson(Map.of("firstField", "yetFirstValue", "secondField", "yetSecondValue"))));
assertThat(dbClient.propertiesDao().selectGlobalProperties(dbSession)).hasSize(7);
assertGlobalSetting("my.key", "1,2,3");
assertGlobalSetting("my.key.1.firstField", "firstValue");
assertGlobalSetting("my.key.1.secondField", "secondValue");
assertGlobalSetting("my.key.2.firstField", "anotherFirstValue");
assertGlobalSetting("my.key.2.secondField", "anotherSecondValue");
assertGlobalSetting("my.key.3.firstField", "yetFirstValue");
assertGlobalSetting("my.key.3.secondField", "yetSecondValue");
assertThat(settingsChangeNotifier.wasCalled).isTrue();
}
@Test
public void update_property_set_on_component_setting() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.PROPERTY_SET)
.defaultValue("default")
.onQualifiers(Qualifiers.PROJECT)
.fields(List.of(
PropertyFieldDefinition.build("firstField")
.name("First Field")
.type(PropertyType.STRING)
.build(),
PropertyFieldDefinition.build("secondField")
.name("Second Field")
.type(PropertyType.STRING)
.build()))
.build());
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
propertyDb.insertProperties(null, null, null, null,
newGlobalPropertyDto("my.key", "1"),
newGlobalPropertyDto("my.key.1.firstField", "oldFirstValue"),
newGlobalPropertyDto("my.key.1.secondField", "oldSecondValue"));
propertyDb.insertProperties(null, project.getKey(), project.getName(), project.getQualifier(),
newComponentPropertyDto("my.key", "1", project),
newComponentPropertyDto("my.key.1.firstField", "componentFirstValue", project),
newComponentPropertyDto("my.key.1.firstField", "componentSecondValue", project));
logInAsProjectAdministrator(project);
callForComponentPropertySet("my.key", List.of(
GSON.toJson(Map.of("firstField", "firstValue", "secondField", "secondValue")),
GSON.toJson(Map.of("firstField", "anotherFirstValue", "secondField", "anotherSecondValue"))),
project.getKey());
assertThat(dbClient.propertiesDao().selectGlobalProperties(dbSession)).hasSize(3);
assertThat(dbClient.propertiesDao().selectEntityProperties(dbSession, project.getUuid())).hasSize(5);
assertGlobalSetting("my.key", "1");
assertGlobalSetting("my.key.1.firstField", "oldFirstValue");
assertGlobalSetting("my.key.1.secondField", "oldSecondValue");
String projectUuid = project.getUuid();
assertComponentSetting("my.key", "1,2", projectUuid);
assertComponentSetting("my.key.1.firstField", "firstValue", projectUuid);
assertComponentSetting("my.key.1.secondField", "secondValue", projectUuid);
assertComponentSetting("my.key.2.firstField", "anotherFirstValue", projectUuid);
assertComponentSetting("my.key.2.secondField", "anotherSecondValue", projectUuid);
assertThat(settingsChangeNotifier.wasCalled).isFalse();
}
@Test
public void persist_multi_value_with_type_metric() {
definitions.addComponent(PropertyDefinition
.builder("my_key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.METRIC)
.defaultValue("default")
.multiValues(true)
.build());
dbClient.metricDao().insert(dbSession, newMetricDto().setKey("metric_key_1"));
dbClient.metricDao().insert(dbSession, newMetricDto().setKey("metric_key_2"));
dbSession.commit();
callForMultiValueGlobalSetting("my_key", List.of("metric_key_1", "metric_key_2"));
assertGlobalSetting("my_key", "metric_key_1,metric_key_2");
}
@Test
public void persist_multi_value_with_type_logIn() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.USER_LOGIN)
.defaultValue("default")
.multiValues(true)
.build());
db.users().insertUser(newUserDto().setLogin("login.1"));
db.users().insertUser(newUserDto().setLogin("login.2"));
callForMultiValueGlobalSetting("my.key", List.of("login.1", "login.2"));
assertGlobalSetting("my.key", "login.1,login.2");
}
@Test
public void user_setting_is_not_updated() {
propertyDb.insertProperty(newGlobalPropertyDto("my.key", "my user value").setUserUuid("42"), null, null,
null, "user_login");
propertyDb.insertProperty(newGlobalPropertyDto("my.key", "my global value"), null, null, null, null);
callForGlobalSetting("my.key", "my new global value");
assertGlobalSetting("my.key", "my new global value");
assertUserSetting("my.key", "my user value", "42");
}
@Test
public void persist_global_property_with_deprecated_key() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.deprecatedKey("my.old.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.STRING)
.defaultValue("default")
.build());
callForGlobalSetting("my.old.key", "My Value");
assertGlobalSetting("my.key", "My Value");
}
@Test
public void persist_JSON_property() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.JSON)
.build());
callForGlobalSetting("my.key", "{\"test\":\"value\"}");
assertGlobalSetting("my.key", "{\"test\":\"value\"}");
}
@Test
public void fail_if_JSON_invalid_for_JSON_property() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.JSON)
.build());
assertThatThrownBy(() -> callForGlobalSetting("my.key", "{\"test\":\"value\""))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Provided JSON is invalid");
assertThatThrownBy(() -> callForGlobalSetting("my.key", "{\"test\":\"value\",}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Provided JSON is invalid");
assertThatThrownBy(() -> callForGlobalSetting("my.key", "{\"test\":[\"value\",]}"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Provided JSON is invalid");
}
@Test
@UseDataProvider("securityJsonProperties")
public void successfully_validate_json_schema(String securityPropertyKey) {
String security_custom_config = "{\n" +
" \"S3649\": {\n" +
" \"sources\": [\n" +
" {\n" +
" \"methodId\": \"My\\\\Namespace\\\\ClassName\\\\ServerRequest::getQuery\"\n" +
" }\n" +
" ],\n" +
" \"sanitizers\": [\n" +
" {\n" +
" \"methodId\": \"str_replace\"," +
" \"args\": [\n" +
" 0\n" +
" ]\n" +
" }\n" +
" ],\n" +
" \"validators\": [\n" +
" {\n" +
" \"methodId\": \"is_valid\"," +
" \"args\": [\n" +
" 1\n" +
" ]\n" +
" }\n" +
" ],\n" +
" \"sinks\": [\n" +
" {\n" +
" \"methodId\": \"mysql_query\",\n" +
" \"args\": [1]\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
definitions.addComponent(PropertyDefinition
.builder(securityPropertyKey)
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.JSON)
.build());
callForGlobalSetting(securityPropertyKey, security_custom_config);
assertGlobalSetting(securityPropertyKey, security_custom_config);
}
@Test
@UseDataProvider("securityJsonProperties")
public void fail_json_schema_validation_when_property_has_incorrect_type(String securityPropertyKey) {
String security_custom_config = "{\n" +
" \"S3649\": {\n" +
" \"sources\": [\n" +
" {\n" +
" \"methodId\": \"My\\\\Namespace\\\\ClassName\\\\ServerRequest::getQuery\"\n" +
" }\n" +
" ],\n" +
" \"sinks\": [\n" +
" {\n" +
" \"methodId\": 12345,\n" +
" \"args\": [1]\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
definitions.addComponent(PropertyDefinition
.builder(securityPropertyKey)
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.JSON)
.build());
assertThatThrownBy(() -> callForGlobalSetting(securityPropertyKey, security_custom_config))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("S3649/sinks/0/methodId: expected type: String, found: Integer");
}
@Test
@UseDataProvider("securityJsonProperties")
public void fail_json_schema_validation_when_sanitizers_have_no_args(String securityPropertyKey) {
String security_custom_config = "{\n" +
" \"S3649\": {\n" +
" \"sources\": [\n" +
" {\n" +
" \"methodId\": \"My\\\\Namespace\\\\ClassName\\\\ServerRequest::getQuery\"\n" +
" }\n" +
" ],\n" +
" \"sanitizers\": [\n" +
" {\n" +
" \"methodId\": \"SomeSanitizer\"\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
definitions.addComponent(PropertyDefinition
.builder(securityPropertyKey)
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.JSON)
.build());
assertThatThrownBy(() -> callForGlobalSetting(securityPropertyKey, security_custom_config))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Provided JSON is invalid [#/S3649/sanitizers/0: #: only 1 subschema matches out of 2]");
}
@Test
@UseDataProvider("securityJsonProperties")
public void fail_json_schema_validation_when_validators_have_empty_args_array(String securityPropertyKey) {
String security_custom_config = "{\n" +
" \"S3649\": {\n" +
" \"sources\": [\n" +
" {\n" +
" \"methodId\": \"My\\\\Namespace\\\\ClassName\\\\ServerRequest::getQuery\"\n" +
" }\n" +
" ],\n" +
" \"validators\": [\n" +
" {\n" +
" \"methodId\": \"SomeValidator\",\n" +
" \"args\": []\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
definitions.addComponent(PropertyDefinition
.builder(securityPropertyKey)
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.JSON)
.build());
assertThatThrownBy(() -> callForGlobalSetting(securityPropertyKey, security_custom_config))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Provided JSON is invalid [#/S3649/validators/0: #: only 1 subschema matches out of 2]");
}
@Test
@UseDataProvider("securityJsonProperties")
public void fail_json_schema_validation_when_property_has_unknown_attribute(String securityPropertyKey) {
String security_custom_config = "{\n" +
" \"S3649\": {\n" +
" \"sources\": [\n" +
" {\n" +
" \"methodId\": \"My\\\\Namespace\\\\ClassName\\\\ServerRequest::getQuery\"\n" +
" }\n" +
" ],\n" +
" \"unknown\": [\n" +
" {\n" +
" \"methodId\": 12345,\n" +
" \"args\": [1]\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
definitions.addComponent(PropertyDefinition
.builder(securityPropertyKey)
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.JSON)
.build());
assertThatThrownBy(() -> callForGlobalSetting(securityPropertyKey, security_custom_config))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("extraneous key [unknown] is not permitted");
}
@Test
public void persist_global_setting_with_non_ascii_characters() {
callForGlobalSetting("my.key", "fi±∞…");
assertGlobalSetting("my.key", "fi±∞…");
assertThat(settingsChangeNotifier.wasCalled).isTrue();
}
@Test
public void fail_when_no_key() {
assertThatThrownBy(() -> callForGlobalSetting(null, "my value"))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void fail_when_empty_key_value() {
assertThatThrownBy(() -> callForGlobalSetting(" ", "my value"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The 'key' parameter is missing");
}
@Test
public void fail_when_no_value() {
assertThatThrownBy(() -> callForGlobalSetting("my.key", null))
.isInstanceOf(BadRequestException.class)
.hasMessage("Either 'value', 'values' or 'fieldValues' must be provided");
}
@Test
public void fail_when_empty_value() {
assertThatThrownBy(() -> callForGlobalSetting("my.key", ""))
.isInstanceOf(BadRequestException.class)
.hasMessage("A non empty value must be provided");
}
@Test
public void fail_when_one_empty_value_on_multi_value() {
List<String> values = List.of("oneValue", " ", "anotherValue");
assertThatThrownBy(() -> callForMultiValueGlobalSetting("my.key", values))
.isInstanceOf(BadRequestException.class)
.hasMessage("A non empty value must be provided");
}
@Test
public void throw_ForbiddenException_if_not_system_administrator() {
userSession.logIn().setNonSystemAdministrator();
assertThatThrownBy(() -> callForGlobalSetting("my.key", "my value"))
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void fail_when_data_and_type_do_not_match() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.INTEGER)
.defaultValue("default")
.build());
i18n.put("property.error.notInteger", "Not an integer error message");
assertThatThrownBy(() -> callForGlobalSetting("my.key", "My Value"))
.isInstanceOf(BadRequestException.class)
.hasMessage("Not an integer error message");
}
@Test
public void fail_when_data_and_metric_type_with_invalid_key() {
definitions.addComponent(PropertyDefinition
.builder("my_key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.METRIC)
.defaultValue("default")
.multiValues(true)
.build());
dbClient.metricDao().insert(dbSession, newMetricDto().setKey("metric_key"));
dbClient.metricDao().insert(dbSession, newMetricDto().setKey("metric_disabled_key").setEnabled(false));
dbSession.commit();
List<String> values = List.of("metric_key", "metric_disabled_key");
assertThatThrownBy(() -> callForMultiValueGlobalSetting("my_key", values))
.isInstanceOf(BadRequestException.class)
.hasMessage("Error when validating metric setting with key 'my_key' and values [metric_key, metric_disabled_key]. A value is not a valid metric key.");
}
@Test
public void fail_when_data_and_login_type_with_invalid_logIn() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.USER_LOGIN)
.defaultValue("default")
.multiValues(true)
.build());
db.users().insertUser(newUserDto().setLogin("login.1"));
db.users().insertUser(newUserDto().setLogin("login.2").setActive(false));
List<String> values = List.of("login.1", "login.2");
assertThatThrownBy(() -> callForMultiValueGlobalSetting("my.key", values))
.isInstanceOf(BadRequestException.class)
.hasMessage("Error when validating login setting with key 'my.key' and values [login.1, login.2]. A value is not a valid login.");
}
@Test
public void fail_when_data_and_type_do_not_match_with_unknown_error_key() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.INTEGER)
.defaultValue("default")
.build());
List<String> values = List.of("My Value", "My Other Value");
assertThatThrownBy(() -> callForMultiValueGlobalSetting("my.key", values))
.isInstanceOf(BadRequestException.class)
.hasMessage("Error when validating setting with key 'my.key' and value [My Value, My Other Value]");
}
@Test
public void fail_when_global_with_property_only_on_projects() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.INTEGER)
.defaultValue("default")
.onlyOnQualifiers(Qualifiers.PROJECT)
.build());
assertThatThrownBy(() -> callForGlobalSetting("my.key", "42"))
.isInstanceOf(BadRequestException.class)
.hasMessage("Setting 'my.key' cannot be global");
}
@Test
public void fail_when_view_property_when_on_projects_only() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.STRING)
.defaultValue("default")
.onQualifiers(Qualifiers.PROJECT)
.build());
ComponentDto view = db.components().insertPublicPortfolio();
i18n.put("qualifier." + Qualifiers.VIEW, "View");
assertThatThrownBy(() -> {
logInAsPortfolioAdministrator(db.components().getPortfolioDto(view));
callForProjectSettingByKey("my.key", "My Value", view.getKey());
})
.isInstanceOf(BadRequestException.class)
.hasMessage("Setting 'my.key' cannot be set on a View");
}
@Test
public void fail_when_property_with_definition_when_component_qualifier_does_not_match() {
PortfolioDto portfolio = db.components().insertPrivatePortfolioDto();
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.STRING)
.defaultValue("default")
.onQualifiers(Qualifiers.PROJECT)
.build());
i18n.put("qualifier." + portfolio.getQualifier(), "CptLabel");
logInAsPortfolioAdministrator(portfolio);
assertThatThrownBy(() -> callForProjectSettingByKey("my.key", "My Value", portfolio.getKey()))
.isInstanceOf(BadRequestException.class)
.hasMessage("Setting 'my.key' cannot be set on a CptLabel");
}
@Test
public void succeed_for_property_without_definition_when_set_on_project_component() {
ProjectDto project = randomPublicOrPrivateProject().getProjectDto();
succeedForPropertyWithoutDefinitionAndValidComponent(project);
}
@Test
public void fail_for_property_without_definition_when_set_on_directory_component() {
ProjectData projectData = randomPublicOrPrivateProject();
ComponentDto directory = db.components().insertComponent(ComponentTesting.newDirectory(projectData.getMainBranchComponent(), "A/B"));
failForPropertyWithoutDefinitionOnUnsupportedComponent(projectData.getProjectDto(), directory);
}
@Test
public void fail_for_property_without_definition_when_set_on_file_component() {
ProjectData projectData = randomPublicOrPrivateProject();
ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(projectData.getMainBranchComponent()));
failForPropertyWithoutDefinitionOnUnsupportedComponent(projectData.getProjectDto(), file);
}
@Test
public void succeed_for_property_without_definition_when_set_on_view_component() {
PortfolioDto view = db.components().insertPrivatePortfolioDto();
succeedForPropertyWithoutDefinitionAndValidComponent(view);
}
@Test
public void succeed_for_property_without_definition_when_set_on_subview_component() {
ComponentDto view = db.components().insertPrivatePortfolio();
ComponentDto subview = db.components().insertComponent(ComponentTesting.newSubPortfolio(view));
failForPropertyWithoutDefinitionOnUnsupportedComponent(db.components().getPortfolioDto(view), subview);
}
@Test
public void fail_for_property_without_definition_when_set_on_projectCopy_component() {
ComponentDto view = db.components().insertPrivatePortfolio();
ComponentDto projectCopy = db.components().insertComponent(ComponentTesting.newProjectCopy("a", db.components().insertPrivateProject().getMainBranchComponent(), view));
failForPropertyWithoutDefinitionOnUnsupportedComponent(db.components().getPortfolioDto(view), projectCopy);
}
private void succeedForPropertyWithoutDefinitionAndValidComponent(ProjectDto project) {
logInAsProjectAdministrator(project);
callForProjectSettingByKey("my.key", "My Value", project.getKey());
assertComponentSetting("my.key", "My Value", project.getUuid());
}
private void succeedForPropertyWithoutDefinitionAndValidComponent(PortfolioDto portfolioDto) {
logInAsPortfolioAdministrator(portfolioDto);
callForProjectSettingByKey("my.key", "My Value", portfolioDto.getKey());
assertComponentSetting("my.key", "My Value", portfolioDto.getUuid());
}
private void failForPropertyWithoutDefinitionOnUnsupportedComponent(ProjectDto project, ComponentDto component) {
i18n.put("qualifier." + component.qualifier(), "QualifierLabel");
logInAsProjectAdministrator(project);
assertThatThrownBy(() -> callForProjectSettingByKey("my.key", "My Value", component.getKey()))
.isInstanceOf(NotFoundException.class)
.hasMessage(String.format("Component key '%s' not found", component.getKey()));
}
private void failForPropertyWithoutDefinitionOnUnsupportedComponent(PortfolioDto portfolio, ComponentDto component) {
i18n.put("qualifier." + component.qualifier(), "QualifierLabel");
logInAsPortfolioAdministrator(portfolio);
assertThatThrownBy(() -> callForProjectSettingByKey("my.key", "My Value", component.getKey()))
.isInstanceOf(NotFoundException.class)
.hasMessage(String.format("Component key '%s' not found", component.getKey()));
}
@Test
public void fail_when_single_and_multi_value_provided() {
List<String> value = List.of("Another Value");
assertThatThrownBy(() -> call("my.key", "My Value", value, null, null))
.isInstanceOf(BadRequestException.class)
.hasMessage("Either 'value', 'values' or 'fieldValues' must be provided");
}
@Test
public void fail_when_multi_definition_and_single_value_provided() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.type(PropertyType.STRING)
.multiValues(true)
.build());
assertThatThrownBy(() -> callForGlobalSetting("my.key", "My Value"))
.isInstanceOf(BadRequestException.class)
.hasMessage("Parameter 'value' must be used for single value setting. Parameter 'values' must be used for multi value setting.");
}
@Test
public void fail_when_single_definition_and_multi_value_provided() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.type(PropertyType.STRING)
.multiValues(false)
.build());
assertThatThrownBy(() -> callForMultiValueGlobalSetting("my.key", List.of("My Value")))
.isInstanceOf(BadRequestException.class)
.hasMessage("Parameter 'value' must be used for single value setting. Parameter 'values' must be used for multi value setting.");
}
@Test
public void fail_when_empty_values_on_one_property_set() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.PROPERTY_SET)
.defaultValue("default")
.fields(List.of(
PropertyFieldDefinition.build("firstField")
.name("First Field")
.type(PropertyType.STRING)
.build(),
PropertyFieldDefinition.build("secondField")
.name("Second Field")
.type(PropertyType.STRING)
.build()))
.build());
assertThatThrownBy(() -> callForGlobalPropertySet("my.key", List.of(
GSON.toJson(Map.of("firstField", "firstValue", "secondField", "secondValue")),
GSON.toJson(Map.of("firstField", "", "secondField", "")),
GSON.toJson(Map.of("firstField", "yetFirstValue", "secondField", "yetSecondValue")))))
.isInstanceOf(BadRequestException.class)
.hasMessage("A non empty value must be provided");
}
@Test
public void do_not_fail_when_only_one_empty_value_on_one_property_set() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.PROPERTY_SET)
.defaultValue("default")
.fields(List.of(
PropertyFieldDefinition.build("firstField")
.name("First Field")
.type(PropertyType.STRING)
.build(),
PropertyFieldDefinition.build("secondField")
.name("Second Field")
.type(PropertyType.STRING)
.build()))
.build());
callForGlobalPropertySet("my.key", List.of(
GSON.toJson(Map.of("firstField", "firstValue", "secondField", "secondValue")),
GSON.toJson(Map.of("firstField", "anotherFirstValue", "secondField", "")),
GSON.toJson(Map.of("firstField", "yetFirstValue", "secondField", "yetSecondValue"))));
assertGlobalSetting("my.key", "1,2,3");
}
@Test
public void fail_when_property_set_setting_is_not_defined() {
assertThatThrownBy(() -> callForGlobalPropertySet("my.key", singletonList("{\"field\":\"value\"}")))
.isInstanceOf(BadRequestException.class)
.hasMessage("Setting 'my.key' is undefined");
}
@Test
public void fail_when_property_set_with_unknown_field() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.PROPERTY_SET)
.defaultValue("default")
.fields(List.of(
PropertyFieldDefinition.build("field")
.name("Field")
.type(PropertyType.STRING)
.build()))
.build());
List<String> values = List.of(GSON.toJson(Map.of("field", "value", "unknownField", "anotherValue")));
assertThatThrownBy(() -> callForGlobalPropertySet("my.key", values))
.isInstanceOf(BadRequestException.class)
.hasMessage("Unknown field key 'unknownField' for setting 'my.key'");
}
@Test
public void fail_when_property_set_has_field_with_incorrect_type() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.PROPERTY_SET)
.defaultValue("default")
.fields(List.of(
PropertyFieldDefinition.build("field")
.name("Field")
.type(PropertyType.INTEGER)
.build()))
.build());
List<String> values = List.of(GSON.toJson(Map.of("field", "notAnInt")));
assertThatThrownBy(() -> callForGlobalPropertySet("my.key", values))
.isInstanceOf(BadRequestException.class)
.hasMessage("Error when validating setting with key 'my.key'. Field 'field' has incorrect value 'notAnInt'.");
}
@Test
public void fail_when_property_set_has_a_null_field_value() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.PROPERTY_SET)
.defaultValue("default")
.fields(List.of(
PropertyFieldDefinition.build("field")
.name("Field")
.type(PropertyType.STRING)
.build()))
.build());
List<String> values = List.of("{\"field\": null}");
assertThatThrownBy(() -> callForGlobalPropertySet("my.key", values))
.isInstanceOf(BadRequestException.class)
.hasMessage("A non empty value must be provided");
}
@Test
public void fail_when_property_set_with_invalid_json() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.PROPERTY_SET)
.defaultValue("default")
.fields(List.of(
PropertyFieldDefinition.build("field")
.name("Field")
.type(PropertyType.STRING)
.build()))
.build());
List<String> values = List.of("incorrectJson:incorrectJson");
assertThatThrownBy(() -> callForGlobalPropertySet("my.key", values))
.isInstanceOf(BadRequestException.class)
.hasMessage("JSON 'incorrectJson:incorrectJson' does not respect expected format for setting 'my.key'. " +
"Ex: {\"field1\":\"value1\", \"field2\":\"value2\"}");
}
@Test
public void fail_when_property_set_with_json_of_the_wrong_format() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.PROPERTY_SET)
.defaultValue("default")
.fields(List.of(
PropertyFieldDefinition.build("field")
.name("Field")
.type(PropertyType.STRING)
.build()))
.build());
List<String> values = List.of("[{\"field\":\"v1\"}, {\"field\":\"v2\"}]");
assertThatThrownBy(() -> callForGlobalPropertySet("my.key", values))
.isInstanceOf(BadRequestException.class)
.hasMessage("JSON '[{\"field\":\"v1\"}, {\"field\":\"v2\"}]' does not respect expected format for setting 'my.key'. " +
"Ex: {\"field1\":\"value1\", \"field2\":\"value2\"}");
}
@Test
public void fail_when_property_set_on_component_of_global_setting() {
definitions.addComponent(PropertyDefinition
.builder("my.key")
.name("foo")
.description("desc")
.category("cat")
.subCategory("subCat")
.type(PropertyType.PROPERTY_SET)
.defaultValue("default")
.fields(List.of(PropertyFieldDefinition.build("firstField").name("First Field").type(PropertyType.STRING).build()))
.build());
i18n.put("qualifier." + Qualifiers.PROJECT, "Project");
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
logInAsProjectAdministrator(project);
List<String> values = List.of(GSON.toJson(Map.of("firstField", "firstValue")));
assertThatThrownBy(() -> callForComponentPropertySet("my.key", values, project.getKey()))
.isInstanceOf(BadRequestException.class)
.hasMessage("Setting 'my.key' cannot be set on a Project");
}
@Test
public void fail_when_component_not_found() {
assertThatThrownBy(() -> ws.newRequest()
.setParam("key", "foo")
.setParam("value", "2")
.setParam("component", "unknown")
.execute())
.isInstanceOf(NotFoundException.class)
.hasMessage("Component key 'unknown' not found");
}
@Test
public void fail_when_setting_key_is_defined_in_sonar_properties() {
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
logInAsProjectAdministrator(project);
String settingKey = ProcessProperties.Property.JDBC_URL.getKey();
assertThatThrownBy(() -> ws.newRequest()
.setParam("key", settingKey)
.setParam("value", "any value")
.setParam("component", project.getKey())
.execute())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(format("Setting '%s' can only be used in sonar.properties", settingKey));
}
@Test
public void definition() {
WebService.Action definition = ws.getDef();
assertThat(definition.key()).isEqualTo("set");
assertThat(definition.isPost()).isTrue();
assertThat(definition.isInternal()).isFalse();
assertThat(definition.since()).isEqualTo("6.1");
assertThat(definition.params()).extracting(Param::key)
.containsOnly("key", "value", "values", "fieldValues", "component");
}
private void assertGlobalSetting(String key, String value) {
PropertyDto result = dbClient.propertiesDao().selectGlobalProperty(key);
assertThat(result)
.extracting(PropertyDto::getKey, PropertyDto::getValue, PropertyDto::getEntityUuid)
.containsExactly(key, value, null);
}
private void assertUserSetting(String key, String value, String userUuid) {
List<PropertyDto> result = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder().setKey(key).setUserUuid(userUuid).build(), dbSession);
assertThat(result).hasSize(1)
.extracting(PropertyDto::getKey, PropertyDto::getValue, PropertyDto::getUserUuid)
.containsExactly(tuple(key, value, userUuid));
}
private void assertComponentSetting(String key, String value, String entityUuid) {
PropertyDto result = dbClient.propertiesDao().selectProjectProperty(db.getSession(), entityUuid, key);
assertThat(result)
.isNotNull()
.extracting(PropertyDto::getKey, PropertyDto::getValue, PropertyDto::getEntityUuid)
.containsExactly(key, value, entityUuid);
}
private void callForGlobalSetting(@Nullable String key, @Nullable String value) {
call(key, value, null, null, null);
}
private void callForMultiValueGlobalSetting(@Nullable String key, @Nullable List<String> values) {
call(key, null, values, null, null);
}
private void callForGlobalPropertySet(@Nullable String key, @Nullable List<String> fieldValues) {
call(key, null, null, fieldValues, null);
}
private void callForComponentPropertySet(@Nullable String key, @Nullable List<String> fieldValues, @Nullable String componentKey) {
call(key, null, null, fieldValues, componentKey);
}
private void callForProjectSettingByKey(@Nullable String key, @Nullable String value, @Nullable String componentKey) {
call(key, value, null, null, componentKey);
}
private void call(@Nullable String key, @Nullable String value, @Nullable List<String> values, @Nullable List<String> fieldValues, @Nullable String componentKey) {
TestRequest request = ws.newRequest();
if (key != null) {
request.setParam("key", key);
}
if (value != null) {
request.setParam("value", value);
}
if (values != null) {
request.setMultiParam("values", values);
}
if (fieldValues != null) {
request.setMultiParam("fieldValues", fieldValues);
}
if (componentKey != null) {
request.setParam("component", componentKey);
}
request.execute();
}
private static class FakeSettingsNotifier extends SettingsChangeNotifier {
private final DbClient dbClient;
private boolean wasCalled = false;
private FakeSettingsNotifier(DbClient dbClient) {
this.dbClient = dbClient;
}
@Override
public void onGlobalPropertyChange(String key, @Nullable String value) {
wasCalled = true;
PropertyDto property = dbClient.propertiesDao().selectGlobalProperty(key);
assertThat(property.getValue()).isEqualTo(value);
}
}
private void logInAsPortfolioAdministrator(PortfolioDto portfolio) {
userSession.logIn().addPortfolioPermission(UserRole.ADMIN, portfolio);
}
private void logInAsProjectAdministrator(ProjectDto project) {
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
}
private ProjectData randomPublicOrPrivateProject() {
return new Random().nextBoolean() ? db.components().insertPrivateProject() : db.components().insertPublicProject();
}
}
| 48,043 | 36.563722 | 172 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/SettingsUpdaterIT.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.setting.ws;
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.PropertyFieldDefinition;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.property.PropertyDbTester;
import org.sonar.db.property.PropertyQuery;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserTesting;
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.sonar.db.property.PropertyTesting.newComponentPropertyDto;
import static org.sonar.db.property.PropertyTesting.newGlobalPropertyDto;
import static org.sonar.db.property.PropertyTesting.newUserPropertyDto;
public class SettingsUpdaterIT {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
DbClient dbClient = db.getDbClient();
DbSession dbSession = db.getSession();
PropertyDbTester propertyDb = new PropertyDbTester(db);
PropertyDefinitions definitions = new PropertyDefinitions(System2.INSTANCE);
ProjectDto project;
SettingsUpdater underTest = new SettingsUpdater(dbClient, definitions);
@Before
public void setUp() {
project = db.components().insertPrivateProject().getProjectDto();
}
@Test
public void delete_global_settings() {
definitions.addComponent(PropertyDefinition.builder("foo").build());
propertyDb.insertProperties(null, project.getKey(), project.getName(), project.getQualifier(),
newComponentPropertyDto(project).setKey("foo").setValue("value"));
propertyDb.insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("one"));
propertyDb.insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("bar").setValue("two"));
underTest.deleteGlobalSettings(dbSession, "foo", "bar");
assertGlobalPropertyDoesNotExist("foo");
assertGlobalPropertyDoesNotExist("bar");
assertProjectPropertyExists("foo");
}
@Test
public void delete_component_settings() {
definitions.addComponent(PropertyDefinition.builder("foo").build());
propertyDb.insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("value"));
propertyDb.insertProperties(null, project.getKey(), project.getName(), project.getQualifier(),
newComponentPropertyDto(project).setKey("foo").setValue("one"));
propertyDb.insertProperties(null, project.getKey(), project.getName(), project.getQualifier(),
newComponentPropertyDto(project).setKey("bar").setValue("two"));
underTest.deleteComponentSettings(dbSession, project, "foo", "bar");
assertProjectPropertyDoesNotExist("foo");
assertProjectPropertyDoesNotExist("bar");
assertGlobalPropertyExists("foo");
}
@Test
public void does_not_fail_when_deleting_unknown_setting() {
propertyDb.insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("one"));
underTest.deleteGlobalSettings(dbSession, "unknown");
assertGlobalPropertyExists("foo");
}
@Test
public void does_not_delete_user_settings() {
UserDto user = dbClient.userDao().insert(dbSession, UserTesting.newUserDto());
propertyDb.insertProperties(user.getLogin(), null, null, null, newUserPropertyDto("foo", "one", user));
propertyDb.insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("one"));
underTest.deleteGlobalSettings(dbSession, "foo");
assertUserPropertyExists("foo", user);
}
@Test
public void delete_global_property_set() {
definitions.addComponent(PropertyDefinition
.builder("foo")
.type(PropertyType.PROPERTY_SET)
.fields(asList(
PropertyFieldDefinition.build("key").name("Key").build(),
PropertyFieldDefinition.build("size").name("Size").build()))
.build());
propertyDb.insertProperties(null, null, null, null,
newGlobalPropertyDto().setKey("foo").setValue("1,2"),
newGlobalPropertyDto().setKey("foo.1.key").setValue("key1"),
newGlobalPropertyDto().setKey("foo.1.size").setValue("size1"),
newGlobalPropertyDto().setKey("foo.2.key").setValue("key2"));
underTest.deleteGlobalSettings(dbSession, "foo");
assertGlobalPropertyDoesNotExist("foo");
assertGlobalPropertyDoesNotExist("foo.1.key");
assertGlobalPropertyDoesNotExist("foo.1.size");
assertGlobalPropertyDoesNotExist("foo.2.key");
}
@Test
public void delete_component_property_set() {
definitions.addComponent(PropertyDefinition
.builder("foo")
.type(PropertyType.PROPERTY_SET)
.fields(asList(
PropertyFieldDefinition.build("key").name("Key").build(),
PropertyFieldDefinition.build("size").name("Size").build()))
.build());
propertyDb.insertProperties(null, project.getKey(), project.getName(), project.getQualifier(),
newComponentPropertyDto(project).setKey("foo").setValue("1,2"),
newComponentPropertyDto(project).setKey("foo.1.key").setValue("key1"),
newComponentPropertyDto(project).setKey("foo.1.size").setValue("size1"),
newComponentPropertyDto(project).setKey("foo.2.key").setValue("key2"));
underTest.deleteComponentSettings(dbSession, project, "foo");
assertProjectPropertyDoesNotExist("foo");
assertProjectPropertyDoesNotExist("foo.1.key");
assertProjectPropertyDoesNotExist("foo.1.size");
assertProjectPropertyDoesNotExist("foo.2.key");
}
@Test
public void does_not_fail_when_deleting_unknown_property_set() {
definitions.addComponent(PropertyDefinition
.builder("foo")
.type(PropertyType.PROPERTY_SET)
.fields(asList(
PropertyFieldDefinition.build("key").name("Key").build(),
PropertyFieldDefinition.build("size").name("Size").build()))
.build());
propertyDb.insertProperties(null, project.getKey(), project.getName(), project.getQualifier(),
newComponentPropertyDto(project).setKey("other").setValue("1,2"),
newComponentPropertyDto(project).setKey("other.1.key").setValue("key1"));
underTest.deleteComponentSettings(dbSession, project, "foo");
assertProjectPropertyExists("other");
}
@Test
public void fail_to_delete_global_setting_when_no_setting_key() {
assertThatThrownBy(() -> {
underTest.deleteGlobalSettings(dbSession);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("At least one setting key is required");
}
@Test
public void fail_to_delete_component_setting_when_no_setting_key() {
assertThatThrownBy(() -> {
underTest.deleteComponentSettings(dbSession, project);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("At least one setting key is required");
}
private void assertGlobalPropertyDoesNotExist(String key) {
assertThat(dbClient.propertiesDao().selectGlobalProperty(dbSession, key)).isNull();
}
private void assertGlobalPropertyExists(String key) {
assertThat(dbClient.propertiesDao().selectGlobalProperty(dbSession, key)).isNotNull();
}
private void assertProjectPropertyDoesNotExist(String key) {
assertThat(dbClient.propertiesDao().selectByQuery(PropertyQuery.builder().setEntityUuid(project.getUuid()).setKey(key).build(), dbSession)).isEmpty();
}
private void assertProjectPropertyExists(String key) {
assertThat(dbClient.propertiesDao().selectByQuery(PropertyQuery.builder().setEntityUuid(project.getUuid()).setKey(key).build(), dbSession)).isNotEmpty();
}
private void assertUserPropertyExists(String key, UserDto user) {
assertThat(dbClient.propertiesDao().selectByQuery(PropertyQuery.builder()
.setKey(key)
.setUserUuid(user.getUuid())
.build(),
dbSession)).isNotEmpty();
}
}
| 8,875 | 38.625 | 157 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/setting/ws/ValuesActionIT.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.setting.ws;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
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.PropertyFieldDefinition;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ProjectData;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.project.ProjectDto;
import org.sonar.process.ProcessProperties;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonar.test.JsonAssert;
import org.sonarqube.ws.Settings;
import org.sonarqube.ws.Settings.ValuesWsResponse;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.Comparator.comparing;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.groups.Tuple.tuple;
import static org.sonar.api.resources.Qualifiers.PROJECT;
import static org.sonar.api.web.UserRole.ADMIN;
import static org.sonar.api.web.UserRole.CODEVIEWER;
import static org.sonar.api.web.UserRole.USER;
import static org.sonar.db.permission.GlobalPermission.SCAN;
import static org.sonar.db.property.PropertyTesting.newComponentPropertyDto;
import static org.sonar.db.property.PropertyTesting.newGlobalPropertyDto;
import static org.sonarqube.ws.MediaTypes.JSON;
import static org.sonarqube.ws.Settings.Setting.ParentValueOneOfCase.PARENTVALUEONEOF_NOT_SET;
public class ValuesActionIT {
private static final Joiner COMMA_JOINER = Joiner.on(",");
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private final DbClient dbClient = db.getDbClient();
private final PropertyDefinitions definitions = new PropertyDefinitions(System2.INSTANCE);
private final SettingsWsSupport support = new SettingsWsSupport(userSession);
private final WsActionTester wsActionTester = new WsActionTester(new ValuesAction(dbClient, userSession, definitions, support));
private ProjectDto project;
@Before
public void setUp() {
ProjectData projectData = db.components().insertPrivateProject();
project = projectData.getProjectDto();
}
@Test
public void return_simple_value() {
logIn();
definitions.addComponent(PropertyDefinition
.builder("foo")
.build());
db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("one"));
ValuesWsResponse result = executeRequestForGlobalProperties("foo");
assertThat(result.getSettingsList()).hasSize(1);
Settings.Setting value = result.getSettings(0);
assertThat(value.getKey()).isEqualTo("foo");
assertThat(value.getValue()).isEqualTo("one");
assertThat(value.getInherited()).isFalse();
}
@Test
public void return_formatted_values() {
logIn();
String propertyKey = "sonar.login.message";
definitions.addComponent(PropertyDefinition
.builder(propertyKey)
.type(PropertyType.FORMATTED_TEXT)
.build());
db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey(propertyKey).setValue("[link](https://link.com)"));
ValuesWsResponse result = executeRequestForGlobalProperties(propertyKey);
assertThat(result.getSettingsList()).hasSize(1);
Settings.Setting value = result.getSettings(0);
assertThat(value.getKey()).isEqualTo(propertyKey);
assertThat(value.getValues().getValuesList())
.hasSize(2)
.containsExactly("[link](https://link.com)", "<a href=\"https://link.com\" target=\"_blank\" rel=\"noopener noreferrer\">link</a>");
}
@Test
public void return_multi_values() {
logIn();
// Property never defined, default value is returned
definitions.addComponent(PropertyDefinition.builder("default")
.multiValues(true)
.defaultValue("one,two")
.build());
// Property defined at global level
definitions.addComponent(PropertyDefinition.builder("global")
.multiValues(true)
.build());
db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("global").setValue("three,four"));
ValuesWsResponse result = executeRequestForGlobalProperties("default", "global");
assertThat(result.getSettingsList()).hasSize(2);
Settings.Setting foo = result.getSettings(0);
assertThat(foo.getKey()).isEqualTo("default");
assertThat(foo.getValues().getValuesList()).containsOnly("one", "two");
Settings.Setting bar = result.getSettings(1);
assertThat(bar.getKey()).isEqualTo("global");
assertThat(bar.getValues().getValuesList()).containsOnly("three", "four");
}
@Test
public void return_multi_value_with_coma() {
logIn();
definitions.addComponent(PropertyDefinition.builder("global").multiValues(true).build());
db.properties().insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("global").setValue("three,four%2Cfive"));
ValuesWsResponse result = executeRequestForGlobalProperties("global");
assertThat(result.getSettingsList()).hasSize(1);
Settings.Setting setting = result.getSettings(0);
assertThat(setting.getKey()).isEqualTo("global");
assertThat(setting.getValues().getValuesList()).containsOnly("three", "four,five");
}
@Test
public void return_property_set() {
logIn();
definitions.addComponent(PropertyDefinition
.builder("foo")
.type(PropertyType.PROPERTY_SET)
.fields(asList(
PropertyFieldDefinition.build("key").name("Key").build(),
PropertyFieldDefinition.build("size").name("Size").build()))
.build());
db.properties().insertPropertySet("foo", null, ImmutableMap.of("key", "key1", "size", "size1"), ImmutableMap.of("key", "key2"));
ValuesWsResponse result = executeRequestForGlobalProperties("foo");
assertThat(result.getSettingsList()).hasSize(1);
Settings.Setting value = result.getSettings(0);
assertThat(value.getKey()).isEqualTo("foo");
assertFieldValues(value, ImmutableMap.of("key", "key1", "size", "size1"), ImmutableMap.of("key", "key2"));
}
@Test
public void return_property_set_for_component() {
logInAsProjectUser();
definitions.addComponent(PropertyDefinition
.builder("foo")
.type(PropertyType.PROPERTY_SET)
.onQualifiers(PROJECT)
.fields(asList(
PropertyFieldDefinition.build("key").name("Key").build(),
PropertyFieldDefinition.build("size").name("Size").build()))
.build());
db.properties().insertPropertySet("foo", project, ImmutableMap.of("key", "key1", "size", "size1"), ImmutableMap.of("key", "key2"));
ValuesWsResponse result = executeRequestForProjectProperties("foo");
assertThat(result.getSettingsList()).hasSize(1);
Settings.Setting value = result.getSettings(0);
assertThat(value.getKey()).isEqualTo("foo");
assertFieldValues(value, ImmutableMap.of("key", "key1", "size", "size1"), ImmutableMap.of("key", "key2"));
}
@Test
public void return_default_values() {
logIn();
definitions.addComponent(PropertyDefinition
.builder("foo")
.defaultValue("default")
.build());
ValuesWsResponse result = executeRequestForGlobalProperties("foo");
assertThat(result.getSettingsList()).hasSize(1);
assertSetting(result.getSettings(0), "foo", "default", true);
}
@Test
public void return_global_values() {
logIn();
definitions.addComponent(PropertyDefinition.builder("property").defaultValue("default").build());
db.properties().insertProperties(null, null, null,
// The property is overriding default value
null, newGlobalPropertyDto().setKey("property").setValue("one"));
ValuesWsResponse result = executeRequestForGlobalProperties("property");
assertThat(result.getSettingsList()).hasSize(1);
assertSetting(result.getSettings(0), "property", "one", false);
}
@Test
public void return_project_values() {
logInAsProjectUser();
definitions.addComponent(
PropertyDefinition.builder("property").defaultValue("default").onQualifiers(PROJECT).build());
db.properties().insertProperties(null, null, null,
null, newGlobalPropertyDto().setKey("property").setValue("one"));
db.properties().insertProperties(null, project.getKey(), project.getName(), project.getQualifier(),
// The property is overriding global value
newComponentPropertyDto(project).setKey("property").setValue("two"));
ValuesWsResponse result = executeRequestForProjectProperties("property");
assertThat(result.getSettingsList()).hasSize(1);
assertSetting(result.getSettings(0), "property", "two", false);
}
@Test
public void return_settings_defined_only_at_global_level_when_loading_project_settings() {
logInAsProjectUser();
definitions.addComponents(asList(
PropertyDefinition.builder("global").build(),
PropertyDefinition.builder("global.default").defaultValue("default").build(),
PropertyDefinition.builder("project").onQualifiers(PROJECT).build()));
db.properties().insertProperties(null, null, null,
null, newGlobalPropertyDto().setKey("global").setValue("one"));
db.properties().insertProperties(null, project.getKey(), project.getName(), project.getQualifier(),
newComponentPropertyDto(project).setKey("project").setValue("two"));
ValuesWsResponse result = executeRequestForProjectProperties();
assertThat(result.getSettingsList()).extracting(Settings.Setting::getKey, Settings.Setting::getValue)
.containsOnly(tuple("project", "two"), tuple("global.default", "default"), tuple("global", "one"));
}
@Test
public void return_is_inherited_to_true_when_property_is_defined_only_at_global_level() {
logInAsProjectUser();
definitions.addComponent(PropertyDefinition.builder("property").defaultValue("default").onQualifiers(PROJECT).build());
// The property is not defined on project
db.properties().insertProperties(null, null, null, null,
newGlobalPropertyDto().setKey("property").setValue("one"));
ValuesWsResponse result = executeRequestForProjectProperties("property");
assertThat(result.getSettingsList()).hasSize(1);
assertSetting(result.getSettings(0), "property", "one", true);
}
@Test
public void return_values_even_if_no_property_definition() {
logIn();
db.properties().insertProperties(null, null, null, null,
newGlobalPropertyDto().setKey("globalPropertyWithoutDefinition").setValue("value"));
ValuesWsResponse result = executeRequestForGlobalProperties("globalPropertyWithoutDefinition");
Settings.Setting globalPropertyWithoutDefinitionValue = result.getSettings(0);
assertThat(globalPropertyWithoutDefinitionValue.getKey()).isEqualTo("globalPropertyWithoutDefinition");
assertThat(globalPropertyWithoutDefinitionValue.getValue()).isEqualTo("value");
assertThat(globalPropertyWithoutDefinitionValue.getInherited()).isFalse();
}
@Test
public void return_values_of_component_even_if_no_property_definition() {
logInAsProjectUser();
db.properties().insertProperties(null, project.getKey(), project.getName(), project.getQualifier(),
newComponentPropertyDto(project).setKey("property").setValue("foo"));
ValuesWsResponse response = executeRequestForComponentProperties(project, "property");
assertThat(response.getSettingsCount()).isOne();
assertSetting(response.getSettings(0), "property", "foo", false);
}
@Test
public void return_empty_when_property_def_exists_but_no_value() {
logIn();
definitions.addComponent(PropertyDefinition
.builder("foo")
.build());
ValuesWsResponse result = executeRequestForGlobalProperties("foo");
assertThat(result.getSettingsList()).isEmpty();
}
@Test
public void return_nothing_when_unknown_keys() {
logIn();
definitions.addComponent(PropertyDefinition
.builder("foo")
.defaultValue("default")
.build());
db.properties().insertProperties(null, null, null, null,
newGlobalPropertyDto().setKey("bar").setValue(""));
ValuesWsResponse result = executeRequestForGlobalProperties("unknown");
assertThat(result.getSettingsList()).isEmpty();
}
@Test
public void return_inherited_values_on_global_setting() {
logIn();
definitions.addComponents(asList(
PropertyDefinition.builder("defaultProperty").defaultValue("default").build(),
PropertyDefinition.builder("globalProperty").build()));
db.properties().insertProperties(null, null, null, null,
newGlobalPropertyDto().setKey("globalProperty").setValue("global"));
ValuesWsResponse result = executeRequestForGlobalProperties("defaultProperty", "globalProperty");
assertThat(result.getSettingsList()).hasSize(2);
assertSetting(result.getSettings(0), "defaultProperty", "default", true);
assertSetting(result.getSettings(1), "globalProperty", "global", false);
}
@Test
public void return_value_of_deprecated_key() {
logIn();
definitions.addComponent(PropertyDefinition
.builder("foo")
.deprecatedKey("deprecated")
.build());
db.properties().insertProperties(null, null, null, null,
newGlobalPropertyDto().setKey("foo").setValue("one"));
ValuesWsResponse result = executeRequestForGlobalProperties("deprecated");
assertThat(result.getSettingsList()).hasSize(1);
Settings.Setting value = result.getSettings(0);
assertThat(value.getKey()).isEqualTo("deprecated");
assertThat(value.getValue()).isEqualTo("one");
}
@Test
public void do_not_return_secured_settings_when_not_authenticated() {
definitions.addComponents(asList(
PropertyDefinition.builder("foo").build(),
PropertyDefinition.builder("secret.secured").build()));
db.properties().insertProperties(null, null, null, null,
newGlobalPropertyDto().setKey("foo").setValue("one"),
newGlobalPropertyDto().setKey("secret.secured").setValue("password"));
ValuesWsResponse result = executeRequestForGlobalProperties();
assertThat(result.getSettingsList()).extracting(Settings.Setting::getKey).containsOnly("foo");
}
@Test
public void do_not_return_secured_settings_in_property_set_when_not_authenticated() {
definitions.addComponent(PropertyDefinition
.builder("foo")
.type(PropertyType.PROPERTY_SET)
.fields(asList(
PropertyFieldDefinition.build("key").name("Key").build(),
PropertyFieldDefinition.build("secret.secured").name("Secured").build()))
.build());
db.properties().insertPropertySet("foo", null, ImmutableMap.of("key", "key1", "secret.secured", "123456"));
ValuesWsResponse result = executeRequestForGlobalProperties();
assertFieldValues(result.getSettings(0), ImmutableMap.of("key", "key1"));
}
@Test
public void return_global_secured_settings_when_not_authenticated_but_with_scan_permission() {
userSession.anonymous().addPermission(SCAN);
definitions.addComponents(asList(
PropertyDefinition.builder("foo").build(),
PropertyDefinition.builder("secret.secured").build()));
db.properties().insertProperties(null, null, null, null,
newGlobalPropertyDto().setKey("foo").setValue("one"),
newGlobalPropertyDto().setKey("secret.secured").setValue("password"));
ValuesWsResponse result = executeRequestForGlobalProperties();
assertThat(result.getSettingsList()).extracting(Settings.Setting::getKey).containsOnly("foo");
assertThat(result.getSetSecuredSettingsList()).containsOnly("secret.secured");
}
@Test
public void return_component_secured_settings_when_not_authenticated_but_with_project_scan_permission() {
userSession
.addProjectPermission(USER, project)
.addProjectPermission(SCAN.getKey(), project);
definitions.addComponents(asList(
PropertyDefinition.builder("foo").onQualifiers(PROJECT).build(),
PropertyDefinition.builder("global.secret.secured").build(),
PropertyDefinition.builder("secret.secured").onQualifiers(PROJECT).build()));
db.properties().insertProperties(null, null, null, null,
newGlobalPropertyDto().setKey("global.secret.secured").setValue("very secret"));
db.properties().insertProperties(null, project.getKey(), project.getName(), project.getQualifier(),
newComponentPropertyDto(project).setKey("foo").setValue("one"),
newComponentPropertyDto(project).setKey("secret.secured").setValue("password"));
ValuesWsResponse result = executeRequestForProjectProperties();
assertThat(result.getSettingsList()).extracting(Settings.Setting::getKey).containsOnly("foo");
assertThat(result.getSetSecuredSettingsList()).contains("global.secret.secured", "secret.secured");
}
@Test
public void return_component_secured_settings_even_if_not_defined_when_not_authenticated_but_with_scan_permission() {
userSession
.addProjectPermission(USER, project)
.addProjectPermission(SCAN.getKey(), project);
db.properties().insertProperties(null, project.getKey(), project.getName(), project.getQualifier(),
newComponentPropertyDto(project).setKey("not-defined.secured").setValue("123"));
ValuesWsResponse result = executeRequestForProjectProperties("not-defined.secured");
assertThat(result.getSetSecuredSettingsList()).containsOnly("not-defined.secured");
}
@Test
public void return_secured_settings_when_system_admin() {
logInAsAdmin();
definitions.addComponents(asList(
PropertyDefinition.builder("foo").build(),
PropertyDefinition.builder("secret.secured").build()));
db.properties().insertProperties(null, null, null, null,
newGlobalPropertyDto().setKey("foo").setValue("one"),
newGlobalPropertyDto().setKey("secret.secured").setValue("password"));
ValuesWsResponse result = executeRequestForGlobalProperties();
assertThat(result.getSettingsList()).extracting(Settings.Setting::getKey).containsOnly("foo");
assertThat(result.getSetSecuredSettingsList()).containsOnly("secret.secured");
}
@Test
public void return_secured_settings_when_project_admin() {
logInAsProjectAdmin();
definitions.addComponents(asList(
PropertyDefinition.builder("foo").onQualifiers(PROJECT).build(),
PropertyDefinition.builder("global.secret.secured").build(),
PropertyDefinition.builder("secret.secured").onQualifiers(PROJECT).build()));
db.properties().insertProperties(null, null, null, null,
newGlobalPropertyDto().setKey("global.secret.secured").setValue("very secret"));
db.properties().insertProperties(null, project.getKey(), project.getName(), project.getQualifier(),
newComponentPropertyDto(project).setKey("foo").setValue("one"),
newComponentPropertyDto(project).setKey("secret.secured").setValue("password"));
ValuesWsResponse result = executeRequestForProjectProperties();
List<Settings.Setting> settingsList = result.getSettingsList().stream().sorted(comparing(Settings.Setting::getKey)).toList();
assertThat(settingsList).extracting(Settings.Setting::getKey).containsExactly("foo");
assertThat(settingsList).extracting(Settings.Setting::hasValue).containsExactly(true);
assertThat(result.getSetSecuredSettingsList()).containsOnly("global.secret.secured", "secret.secured");
}
@Test
public void return_secured_settings_even_if_not_defined_when_project_admin() {
logInAsProjectAdmin();
db.properties().insertProperties(null, project.getKey(), project.getName(), project.getQualifier(),
newComponentPropertyDto(project).setKey("not-defined.secured").setValue("123"));
ValuesWsResponse result = executeRequestForProjectProperties("not-defined.secured");
assertThat(result.getSettingsList()).extracting(Settings.Setting::getKey).isEmpty();
assertThat(result.getSetSecuredSettingsList()).containsOnly("not-defined.secured");
}
@Test
public void return_secured_settings_in_property_set_when_system_admin() {
logInAsAdmin();
definitions.addComponent(PropertyDefinition
.builder("foo")
.type(PropertyType.PROPERTY_SET)
.fields(asList(
PropertyFieldDefinition.build("key").name("Key").build(),
PropertyFieldDefinition.build("secret.secured").name("Secured").build()))
.build());
db.properties().insertPropertySet("foo", null, ImmutableMap.of("key", "key1", "secret.secured", "123456"));
ValuesWsResponse result = executeRequestForGlobalProperties();
assertFieldValues(result.getSettings(0), ImmutableMap.of("key", "key1", "secret.secured", "123456"));
}
@Test
public void return_admin_only_settings_in_property_set_when_system_admin() {
String anyAdminOnlySettingKey = SettingsWsSupport.ADMIN_ONLY_SETTINGS.iterator().next();
logInAsAdmin();
definitions.addComponent(PropertyDefinition
.builder(anyAdminOnlySettingKey)
.type(PropertyType.PROPERTY_SET)
.fields(asList(
PropertyFieldDefinition.build(anyAdminOnlySettingKey).name("Key admnin only").build(),
PropertyFieldDefinition.build(anyAdminOnlySettingKey).name("Value admin only").build()))
.build());
ImmutableMap<String, String> keyValuePairs = ImmutableMap.of(anyAdminOnlySettingKey, "test_val");
db.properties().insertPropertySet(anyAdminOnlySettingKey, null, keyValuePairs);
ValuesWsResponse result = executeRequestForGlobalProperties();
assertFieldValues(result.getSettings(0), keyValuePairs);
}
@Test
public void return_admin_only_settings_in_property_not_set_when_simple_user() {
String anyAdminOnlySettingKey = SettingsWsSupport.ADMIN_ONLY_SETTINGS.iterator().next();
logIn();
definitions.addComponent(PropertyDefinition
.builder(anyAdminOnlySettingKey)
.type(PropertyType.PROPERTY_SET)
.fields(asList(
PropertyFieldDefinition.build(anyAdminOnlySettingKey).name("Key admnin only").build(),
PropertyFieldDefinition.build(anyAdminOnlySettingKey).name("Value admin only").build()))
.build());
ImmutableMap<String, String> keyValuePairs = ImmutableMap.of(anyAdminOnlySettingKey, "test_val");
db.properties().insertPropertySet(anyAdminOnlySettingKey, null, keyValuePairs);
ValuesWsResponse result = executeRequestForGlobalProperties();
assertThat(result.getSettingsList()).isEmpty();
}
@Test
public void return_global_settings_from_definitions_when_no_component_and_no_keys() {
logInAsAdmin();
definitions.addComponents(asList(
PropertyDefinition.builder("foo").build(),
PropertyDefinition.builder("secret.secured").build()));
db.properties().insertProperties(null, null, null, null,
newGlobalPropertyDto().setKey("foo").setValue("one"),
newGlobalPropertyDto().setKey("secret.secured").setValue("password"));
ValuesWsResponse result = executeRequestForGlobalProperties();
assertThat(result.getSettingsList()).extracting(Settings.Setting::getKey).containsOnly("foo");
assertThat(result.getSetSecuredSettingsList()).containsOnly("secret.secured");
}
@Test
public void return_project_settings_from_definitions_when_component_and_no_keys() {
logInAsProjectAdmin();
definitions.addComponents(asList(
PropertyDefinition.builder("foo").onQualifiers(PROJECT).build(),
PropertyDefinition.builder("secret.secured").onQualifiers(PROJECT).build()));
db.properties().insertProperties(null, project.getKey(), project.getName(), project.getQualifier(),
newComponentPropertyDto(project).setKey("foo").setValue("one"),
newComponentPropertyDto(project).setKey("secret.secured").setValue("password"));
ValuesWsResponse result = executeRequestForProjectProperties();
assertThat(result.getSettingsList()).extracting(Settings.Setting::getKey).containsOnly("foo");
assertThat(result.getSetSecuredSettingsList()).containsOnly("secret.secured");
}
@Test
public void return_additional_settings_specific_for_scanner_when_no_keys() {
logInAsAdmin();
definitions.addComponent(PropertyDefinition.builder("secret.secured").build());
db.properties().insertProperties(null, null, null, null,
newGlobalPropertyDto().setKey("sonar.core.id").setValue("ID"),
newGlobalPropertyDto().setKey("sonar.core.startTime").setValue("2017-01-01"));
ValuesWsResponse result = executeRequestForGlobalProperties();
assertThat(result.getSettingsList()).extracting(Settings.Setting::getKey).containsOnly("sonar.core.id", "sonar.core.startTime");
}
@Test
public void return_simple_value_with_non_ascii_characters() {
logIn();
definitions.addComponent(PropertyDefinition
.builder("foo")
.build());
db.properties().insertProperties(null, null, null, null,
newGlobalPropertyDto().setKey("foo").setValue("fi±∞…"));
ValuesWsResponse result = executeRequestForGlobalProperties("foo");
assertThat(result.getSettings(0).getValue()).isEqualTo("fi±∞…");
}
@Test
public void fail_when_user_has_not_project_browse_permission() {
userSession.logIn("project-admin").addProjectPermission(CODEVIEWER, project);
definitions.addComponent(PropertyDefinition.builder("foo").build());
assertThatThrownBy(() -> {
executeRequest(project.getKey(), "foo");
})
.isInstanceOf(ForbiddenException.class);
}
@Test
public void fail_when_deprecated_key_and_new_key_are_used() {
logIn();
definitions.addComponent(PropertyDefinition
.builder("foo")
.deprecatedKey("deprecated")
.build());
db.properties().insertProperties(null, null, null, null,
newGlobalPropertyDto().setKey("foo").setValue("one"));
assertThatThrownBy(() -> {
executeRequestForGlobalProperties("foo", "deprecated");
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("'foo' and 'deprecated' cannot be used at the same time as they refer to the same setting");
}
@Test
public void fail_when_component_not_found() {
assertThatThrownBy(() -> {
wsActionTester.newRequest()
.setParam("keys", "foo")
.setParam("component", "unknown")
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Component key 'unknown' not found");
}
@Test
public void test_example_json_response() {
logInAsAdmin();
definitions.addComponent(PropertyDefinition
.builder("sonar.test.jira")
.defaultValue("abc")
.build());
definitions.addComponent(PropertyDefinition
.builder("sonar.autogenerated")
.multiValues(true)
.build());
db.properties().insertProperties(null, null, null, null,
newGlobalPropertyDto().setKey("sonar.autogenerated").setValue("val1,val2,val3"));
definitions.addComponent(PropertyDefinition
.builder("sonar.demo")
.type(PropertyType.PROPERTY_SET)
.fields(PropertyFieldDefinition.build("text").name("Text").build(),
PropertyFieldDefinition.build("boolean").name("Boolean").build())
.build());
db.properties().insertPropertySet("sonar.demo", null, ImmutableMap.of("text", "foo", "boolean", "true"), ImmutableMap.of("text", "bar", "boolean", "false"));
definitions.addComponent(PropertyDefinition
.builder("email.smtp_port.secured")
.defaultValue("25")
.build());
db.properties().insertProperties(null, null, null, null,
newGlobalPropertyDto().setKey("email.smtp_port.secured").setValue("25"));
String result = wsActionTester.newRequest()
.setParam("keys", "sonar.test.jira,sonar.autogenerated,sonar.demo,email.smtp_port.secured")
.setMediaType(JSON)
.execute()
.getInput();
JsonAssert.assertJson(wsActionTester.getDef().responseExampleAsString()).isSimilarTo(result);
}
@Test
public void fail_when_setting_key_is_defined_in_sonar_properties() {
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
userSession.logIn().addProjectPermission(UserRole.USER, project);
String settingKey = ProcessProperties.Property.JDBC_URL.getKey();
assertThatThrownBy(() -> {
wsActionTester.newRequest()
.setParam("keys", settingKey)
.setParam("component", project.getKey())
.execute();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(format("Setting '%s' can only be used in sonar.properties", settingKey));
}
@Test
public void test_ws_definition() {
WebService.Action action = wsActionTester.getDef();
assertThat(action).isNotNull();
assertThat(action.isInternal()).isFalse();
assertThat(action.isPost()).isFalse();
assertThat(action.responseExampleAsString()).isNotEmpty();
assertThat(action.params()).extracting(WebService.Param::key).containsExactlyInAnyOrder("keys", "component");
}
@Test
public void global_secured_properties_require_system_admin_permission() {
PropertyDefinition securedDef = PropertyDefinition.builder("my.password.secured").build();
PropertyDefinition standardDef = PropertyDefinition.builder("my.property").build();
definitions.addComponents(asList(securedDef, standardDef));
db.properties().insertProperties(null, null, null, null,
newGlobalPropertyDto().setKey(securedDef.key()).setValue("securedValue"),
newGlobalPropertyDto().setKey(standardDef.key()).setValue("standardValue"));
// anonymous
ValuesWsResponse response = executeRequest(null, securedDef.key(), standardDef.key());
assertThat(response.getSettingsList()).extracting(Settings.Setting::getKey).containsExactly("my.property");
// only scan global permission
userSession.logIn()
.addPermission(GlobalPermission.SCAN);
response = executeRequest(null, securedDef.key(), standardDef.key());
assertThat(response.getSetSecuredSettingsList()).contains("my.password.secured");
// global administrator
userSession.logIn()
.addPermission(GlobalPermission.ADMINISTER);
response = executeRequest(null, securedDef.key(), standardDef.key());
assertThat(response.getSetSecuredSettingsList()).contains("my.password.secured");
// system administrator
userSession.logIn().setSystemAdministrator();
response = executeRequest(null, securedDef.key(), standardDef.key());
assertThat(response.getSetSecuredSettingsList()).contains("my.password.secured");
}
private ValuesWsResponse executeRequestForComponentProperties(EntityDto entity, String... keys) {
return executeRequest(entity.getKey(), keys);
}
private ValuesWsResponse executeRequestForProjectProperties(String... keys) {
return executeRequest(project.getKey(), keys);
}
private ValuesWsResponse executeRequestForGlobalProperties(String... keys) {
return executeRequest(null, keys);
}
private ValuesWsResponse executeRequest(@Nullable String componentKey, String... keys) {
TestRequest request = wsActionTester.newRequest();
if (keys.length > 0) {
request.setParam("keys", COMMA_JOINER.join(keys));
}
if (componentKey != null) {
request.setParam("component", componentKey);
}
return request.executeProtobuf(ValuesWsResponse.class);
}
private void logIn() {
userSession.logIn();
}
private void logInAsProjectUser() {
userSession.logIn().addProjectPermission(USER, project);
}
private void logInAsAdmin() {
userSession.logIn().setSystemAdministrator();
}
private void logInAsProjectAdmin() {
userSession.logIn()
.addProjectPermission(ADMIN, project)
.addProjectPermission(USER, project);
}
private void assertSetting(Settings.Setting setting, String expectedKey, String expectedValue, boolean expectedInherited) {
assertThat(setting.getKey()).isEqualTo(expectedKey);
assertThat(setting.getValue()).isEqualTo(expectedValue);
assertThat(setting.getInherited()).isEqualTo(expectedInherited);
}
private void assertFieldValues(Settings.Setting setting, Map<String, String>... fieldsValues) {
assertThat(setting.getFieldValues().getFieldValuesList()).hasSize(fieldsValues.length);
int index = 0;
for (Settings.FieldValues.Value fieldsValue : setting.getFieldValues().getFieldValuesList()) {
assertThat(fieldsValue.getValue()).isEqualTo(fieldsValues[index]);
index++;
}
}
private void assertParentValue(Settings.Setting setting, @Nullable String parentValue) {
if (parentValue == null) {
assertThat(setting.getParentValueOneOfCase()).isEqualTo(PARENTVALUEONEOF_NOT_SET);
} else {
assertThat(setting.getParentValue()).isEqualTo(parentValue);
}
}
private void assertParentValues(Settings.Setting setting, String... parentValues) {
if (parentValues.length == 0) {
assertThat(setting.getParentValueOneOfCase()).isEqualTo(PARENTVALUEONEOF_NOT_SET);
} else {
assertThat(setting.getParentValues().getValuesList()).containsOnly(parentValues);
}
}
private void assertParentFieldValues(Settings.Setting setting, Map<String, String>... fieldsValues) {
if (fieldsValues.length == 0) {
assertThat(setting.getParentValueOneOfCase()).isEqualTo(PARENTVALUEONEOF_NOT_SET);
} else {
assertThat(setting.getParentFieldValues().getFieldValuesList()).hasSize(fieldsValues.length);
int index = 0;
for (Settings.FieldValues.Value fieldsValue : setting.getParentFieldValues().getFieldValuesList()) {
assertThat(fieldsValue.getValue()).isEqualTo(fieldsValues[index]);
index++;
}
}
}
}
| 34,957 | 40.966387 | 161 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/SourceServiceIT.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.source;
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbTester;
import org.sonar.db.protobuf.DbFileSources;
import org.sonar.db.source.FileSourceDto;
import org.sonar.server.source.index.FileSourceTesting;
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 SourceServiceIT {
public static final String FILE_UUID = "FILE_UUID";
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
HtmlSourceDecorator htmlDecorator = mock(HtmlSourceDecorator.class);
SourceService underTest = new SourceService(dbTester.getDbClient(), htmlDecorator);
@Before
public void injectFakeLines() {
FileSourceDto dto = new FileSourceDto();
dto.setFileUuid(FILE_UUID).setUuid(Uuids.createFast()).setProjectUuid("PROJECT_UUID");
dto.setSourceData(FileSourceTesting.newFakeData(10).build());
dbTester.getDbClient().fileSourceDao().insert(dbTester.getSession(), dto);
dbTester.commit();
}
@Test
public void get_range_of_lines() {
Set<Integer> lineNumbers = new HashSet<>(Arrays.asList(1, 5, 6));
Optional<Iterable<DbFileSources.Line>> linesOpt = underTest.getLines(dbTester.getSession(), FILE_UUID, lineNumbers);
assertThat(linesOpt).isPresent();
List<DbFileSources.Line> lines = Lists.newArrayList(linesOpt.get());
assertThat(lines).hasSize(3);
assertThat(lines.get(0).getLine()).isOne();
assertThat(lines.get(1).getLine()).isEqualTo(5);
assertThat(lines.get(2).getLine()).isEqualTo(6);
}
@Test
public void get_set_of_lines() {
Optional<Iterable<DbFileSources.Line>> linesOpt = underTest.getLines(dbTester.getSession(), FILE_UUID, 5, 7);
assertThat(linesOpt).isPresent();
List<DbFileSources.Line> lines = Lists.newArrayList(linesOpt.get());
assertThat(lines).hasSize(3);
assertThat(lines.get(0).getLine()).isEqualTo(5);
assertThat(lines.get(1).getLine()).isEqualTo(6);
assertThat(lines.get(2).getLine()).isEqualTo(7);
}
@Test
public void get_range_of_lines_as_raw_text() {
Optional<Iterable<String>> linesOpt = underTest.getLinesAsRawText(dbTester.getSession(), FILE_UUID, 5, 7);
assertThat(linesOpt).isPresent();
List<String> lines = Lists.newArrayList(linesOpt.get());
assertThat(lines).containsExactly("SOURCE_5", "SOURCE_6", "SOURCE_7");
}
@Test
public void get_range_of_lines_as_html() {
when(htmlDecorator.getDecoratedSourceAsHtml("SOURCE_5", "HIGHLIGHTING_5", "SYMBOLS_5")).thenReturn("HTML_5");
when(htmlDecorator.getDecoratedSourceAsHtml("SOURCE_6", "HIGHLIGHTING_6", "SYMBOLS_6")).thenReturn("HTML_6");
when(htmlDecorator.getDecoratedSourceAsHtml("SOURCE_7", "HIGHLIGHTING_7", "SYMBOLS_7")).thenReturn("HTML_7");
Optional<Iterable<String>> linesOpt = underTest.getLinesAsHtml(dbTester.getSession(), FILE_UUID, 5, 7);
assertThat(linesOpt).isPresent();
List<String> lines = Lists.newArrayList(linesOpt.get());
assertThat(lines).containsExactly("HTML_5", "HTML_6", "HTML_7");
}
@Test
public void getLines_fails_if_range_starts_at_zero() {
assertThatThrownBy(() -> underTest.getLines(dbTester.getSession(), FILE_UUID, 0, 2))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Line number must start at 1, got 0");
}
@Test
public void getLines_fails_if_range_upper_bound_less_than_lower_bound() {
assertThatThrownBy(() -> underTest.getLines(dbTester.getSession(), FILE_UUID, 5, 4))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Line number must greater than or equal to 5, got 4");
}
@Test
public void getLines_returns_empty_iterable_if_range_is_out_of_scope() {
Optional<Iterable<DbFileSources.Line>> lines = underTest.getLines(dbTester.getSession(), FILE_UUID, 500, 510);
assertThat(lines).isPresent();
assertThat(lines.get()).isEmpty();
}
@Test
public void getLines_file_does_not_exist() {
Optional<Iterable<DbFileSources.Line>> lines = underTest.getLines(dbTester.getSession(), "FILE_DOES_NOT_EXIST", 1, 10);
assertThat(lines).isEmpty();
}
}
| 5,349 | 38.62963 | 123 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/IndexActionIT.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.source.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.protobuf.DbFileSources;
import org.sonar.db.source.FileSourceDto;
import org.sonar.server.component.TestComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.source.HtmlSourceDecorator;
import org.sonar.server.source.SourceService;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.web.UserRole.CODEVIEWER;
import static org.sonar.api.web.UserRole.USER;
import static org.sonar.db.component.ComponentTesting.newFileDto;
import static org.sonar.test.JsonAssert.assertJson;
public class IndexActionIT {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
WsActionTester tester = new WsActionTester(
new IndexAction(db.getDbClient(), new SourceService(db.getDbClient(), new HtmlSourceDecorator()), userSession, TestComponentFinder.from(db)));
@Test
public void get_json() throws Exception {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
userSession.addProjectPermission(CODEVIEWER, project);
ComponentDto file = db.components().insertComponent(newFileDto(project));
insertFileWithData(file, newData("public class HelloWorld {", "}"));
TestResponse request = tester.newRequest()
.setParam("resource", file.getKey())
.execute();
assertJson(request.getInput()).isSimilarTo("[\n" +
" {\n" +
" \"1\": \"public class HelloWorld {\",\n" +
" \"2\": \"}\"\n" +
" }\n" +
"]");
}
@Test
public void limit_range() throws Exception {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
userSession.addProjectPermission(CODEVIEWER, project);
ComponentDto file = db.components().insertComponent(newFileDto(project));
insertFileWithData(file, newData("/**", " */", "public class HelloWorld {", "}", "", "foo"));
TestResponse request = tester.newRequest()
.setParam("resource", file.getKey())
.setParam("from", "3")
.setParam("to", "5")
.execute();
assertJson(request.getInput()).isSimilarTo("[\n" +
" {\n" +
" \"3\": \"public class HelloWorld {\",\n" +
" \"4\": \"}\"\n" +
" }\n" +
"]");
}
@Test
public void fail_when_missing_code_viewer_permission() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
userSession.addProjectPermission(USER, project);
ComponentDto file = db.components().insertComponent(newFileDto(project));
assertThatThrownBy(() -> tester.newRequest()
.setParam("resource", file.getKey())
.execute())
.isInstanceOf(ForbiddenException.class);
}
@Test
public void fail_when_component_does_not_exist() {
assertThatThrownBy(() -> tester.newRequest()
.setParam("resource", "unknown")
.execute())
.isInstanceOf(NotFoundException.class);
}
private static DbFileSources.Data newData(String... lines) {
DbFileSources.Data.Builder dataBuilder = DbFileSources.Data.newBuilder();
for (int i = 1; i <= lines.length; i++) {
dataBuilder.addLinesBuilder()
.setLine(i)
.setSource(lines[i - 1])
.build();
}
return dataBuilder.build();
}
private void insertFileWithData(ComponentDto file, DbFileSources.Data fileData) {
db.getDbClient().fileSourceDao().insert(db.getSession(), new FileSourceDto()
.setUuid(Uuids.createFast())
.setProjectUuid(file.branchUuid())
.setFileUuid(file.uuid())
.setSourceData(fileData));
db.commit();
}
}
| 4,928 | 35.242647 | 146 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/IssueSnippetsActionIT.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.source.ws;
import java.net.URL;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.stubbing.Answer;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ProjectData;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.protobuf.DbCommons;
import org.sonar.db.protobuf.DbFileSources;
import org.sonar.db.protobuf.DbIssues;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.source.FileSourceTester;
import org.sonar.server.component.ws.ComponentViewerJsonWriter;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.source.HtmlSourceDecorator;
import org.sonar.server.source.SourceService;
import org.sonar.server.source.index.FileSourceTesting;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import org.sonar.test.JsonAssert;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.api.measures.CoreMetrics.COVERAGE_KEY;
import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_DENSITY_KEY;
import static org.sonar.api.measures.CoreMetrics.LINES_KEY;
import static org.sonar.api.measures.CoreMetrics.TECHNICAL_DEBT_KEY;
import static org.sonar.api.measures.CoreMetrics.TESTS_KEY;
import static org.sonar.api.measures.CoreMetrics.VIOLATIONS_KEY;
import static org.sonar.api.web.UserRole.CODEVIEWER;
import static org.sonar.api.web.UserRole.USER;
import static org.sonar.db.component.ComponentTesting.newFileDto;
public class IssueSnippetsActionIT {
@Rule
public final DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public final UserSessionRule userSession = UserSessionRule.standalone();
private final DbClient dbClient = db.getDbClient();
private final FileSourceTester fileSourceTester = new FileSourceTester(db);
private ProjectData project;
private WsActionTester actionTester;
private ComponentDto mainBranchComponent;
@Before
public void setUp() {
project = db.components().insertPrivateProject("projectUuid", c -> c.setKey("KEY_projectUuid").setName("NAME_projectUuid"));
mainBranchComponent = project.getMainBranchComponent();
HtmlSourceDecorator htmlSourceDecorator = mock(HtmlSourceDecorator.class);
when(htmlSourceDecorator.getDecoratedSourceAsHtml(anyString(), anyString(), anyString()))
.then((Answer<String>) invocationOnMock -> "<p>" + invocationOnMock.getArguments()[0] + "</p>");
LinesJsonWriter linesJsonWriter = new LinesJsonWriter(htmlSourceDecorator);
ComponentViewerJsonWriter componentViewerJsonWriter = new ComponentViewerJsonWriter(dbClient);
SourceService sourceService = new SourceService(dbClient, htmlSourceDecorator);
actionTester = new WsActionTester(new IssueSnippetsAction(dbClient, userSession, sourceService, linesJsonWriter, componentViewerJsonWriter));
}
@Test
public void verify_definition() {
var def = actionTester.getDef();
assertThat(def.isInternal()).isTrue();
assertThat(def.since()).isEqualTo("7.8");
assertThat(def.param("issueKey")).extracting(Param::isRequired, Param::description)
.containsExactly(true, "Issue or hotspot key");
}
@Test
public void should_display_single_location_single_file() {
ComponentDto file = insertFile(mainBranchComponent, "file");
DbFileSources.Data fileSources = FileSourceTesting.newFakeData(10).build();
fileSourceTester.insertFileSource(file, 10, dto -> dto.setSourceData(fileSources));
userSession.logIn().addProjectPermission(CODEVIEWER, project.getProjectDto());
String issueKey = insertIssue(file, newLocation(file.uuid(), 5, 5));
TestResponse response = actionTester.newRequest().setParam("issueKey", issueKey).execute();
response.assertJson(getClass(), "issue_snippets_single_location.json");
}
@Test
public void should_add_measures_to_components() {
ComponentDto file = insertFile(mainBranchComponent, "file");
MetricDto lines = db.measures().insertMetric(m -> m.setKey(LINES_KEY));
db.measures().insertLiveMeasure(file, lines, m -> m.setValue(200d));
MetricDto duplicatedLines = db.measures().insertMetric(m -> m.setKey(DUPLICATED_LINES_DENSITY_KEY));
db.measures().insertLiveMeasure(file, duplicatedLines, m -> m.setValue(7.4));
MetricDto tests = db.measures().insertMetric(m -> m.setKey(TESTS_KEY));
db.measures().insertLiveMeasure(file, tests, m -> m.setValue(3d));
MetricDto technicalDebt = db.measures().insertMetric(m -> m.setKey(TECHNICAL_DEBT_KEY));
db.measures().insertLiveMeasure(file, technicalDebt, m -> m.setValue(182d));
MetricDto issues = db.measures().insertMetric(m -> m.setKey(VIOLATIONS_KEY));
db.measures().insertLiveMeasure(file, issues, m -> m.setValue(231d));
MetricDto coverage = db.measures().insertMetric(m -> m.setKey(COVERAGE_KEY));
db.measures().insertLiveMeasure(file, coverage, m -> m.setValue(95.4d));
DbFileSources.Data fileSources = FileSourceTesting.newFakeData(10).build();
fileSourceTester.insertFileSource(file, 10, dto -> dto.setSourceData(fileSources));
userSession.logIn().addProjectPermission(CODEVIEWER, project.getProjectDto());
String issueKey = insertIssue(file, newLocation(file.uuid(), 5, 5));
TestResponse response = actionTester.newRequest().setParam("issueKey", issueKey).execute();
response.assertJson(getClass(), "issue_snippets_with_measures.json");
}
@Test
public void issue_references_a_non_existing_component() {
ComponentDto file = insertFile(mainBranchComponent, "file");
ComponentDto file2 = newFileDto(mainBranchComponent, null, "nonexisting");
DbFileSources.Data fileSources = FileSourceTesting.newFakeData(10).build();
fileSourceTester.insertFileSource(file, 10, dto -> dto.setSourceData(fileSources));
userSession.logIn().addProjectPermission(CODEVIEWER, project.getProjectDto());
String issueKey = insertIssue(file, newLocation(file2.uuid(), 5, 5));
TestResponse response = actionTester.newRequest().setParam("issueKey", issueKey).execute();
response.assertJson("{}");
}
@Test
public void no_code_to_display() {
ComponentDto file = insertFile(mainBranchComponent, "file");
userSession.logIn().addProjectPermission(CODEVIEWER, project.getProjectDto());
String issueKey = insertIssue(file, newLocation(file.uuid(), 5, 5));
TestResponse response = actionTester.newRequest().setParam("issueKey", issueKey).execute();
response.assertJson("{}");
}
@Test
public void fail_if_no_project_permission() {
ComponentDto file = insertFile(mainBranchComponent, "file");
userSession.logIn().addProjectPermission(USER, project.getProjectDto());
String issueKey = insertIssue(file, newLocation(file.uuid(), 5, 5));
var request = actionTester.newRequest().setParam("issueKey", issueKey);
assertThatThrownBy(request::execute)
.isInstanceOf(ForbiddenException.class);
}
@Test
public void fail_if_issue_not_found() {
ComponentDto file = insertFile(mainBranchComponent, "file");
insertIssue(file, newLocation(file.uuid(), 5, 5));
userSession.logIn().addProjectPermission(CODEVIEWER, project.getProjectDto());
var request = actionTester.newRequest().setParam("issueKey", "invalid");
assertThatThrownBy(request::execute)
.isInstanceOf(NotFoundException.class)
.hasMessageContaining("Issue with key 'invalid' does not exist");
}
@Test
public void fail_if_parameter_missing() {
ComponentDto file = insertFile(mainBranchComponent, "file");
userSession.logIn().addProjectPermission(CODEVIEWER, project.getProjectDto());
var request = actionTester.newRequest();
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("The 'issueKey' parameter is missing");
}
@Test
public void should_display_multiple_locations_multiple_files() {
ComponentDto file1 = insertFile(mainBranchComponent, "file1");
ComponentDto file2 = insertFile(mainBranchComponent, "file2");
DbFileSources.Data fileSources = FileSourceTesting.newFakeData(10).build();
fileSourceTester.insertFileSource(file1, 10, dto -> dto.setSourceData(fileSources));
fileSourceTester.insertFileSource(file2, 10, dto -> dto.setSourceData(fileSources));
userSession.logIn().addProjectPermission(CODEVIEWER, project.getProjectDto());
String issueKey1 = insertIssue(file1, newLocation(file1.uuid(), 5, 5),
newLocation(file1.uuid(), 9, 9), newLocation(file2.uuid(), 1, 5));
TestResponse response = actionTester.newRequest().setParam("issueKey", issueKey1).execute();
JsonAssert.assertJson(response.getInput())
.isSimilarTo(toUrl("issue_snippets_multiple_locations.json"));
}
@Test
public void should_connect_snippets_close_to_each_other() {
ComponentDto file1 = insertFile(mainBranchComponent, "file1");
DbFileSources.Data fileSources = FileSourceTesting.newFakeData(20).build();
fileSourceTester.insertFileSource(file1, 20, dto -> dto.setSourceData(fileSources));
userSession.logIn().addProjectPermission(CODEVIEWER, project.getProjectDto());
// these two locations should get connected, making a single range 3-14
String issueKey1 = insertIssue(file1, newLocation(file1.uuid(), 5, 5),
newLocation(file1.uuid(), 12, 12));
TestResponse response = actionTester.newRequest().setParam("issueKey", issueKey1).execute();
JsonAssert.assertJson(response.getInput())
.isSimilarTo(toUrl("issue_snippets_close_to_each_other.json"));
}
private DbIssues.Location newLocation(String fileUuid, int startLine, int endLine) {
return DbIssues.Location.newBuilder()
.setTextRange(DbCommons.TextRange.newBuilder().setStartLine(startLine).setEndLine(endLine).build())
.setComponentId(fileUuid)
.build();
}
private ComponentDto insertFile(ComponentDto project, String name) {
ComponentDto file = newFileDto(project, null, name);
db.components().insertComponents(file);
return file;
}
private String insertIssue(ComponentDto file, DbIssues.Location... locations) {
RuleDto rule = db.rules().insert();
DbIssues.Flow flow = DbIssues.Flow.newBuilder().addAllLocation(Arrays.asList(locations)).build();
IssueDto issue = db.issues().insert(rule, project.getMainBranchComponent(), file, i -> {
i.setLocations(DbIssues.Locations.newBuilder().addFlow(flow).build());
i.setProjectUuid(mainBranchComponent.uuid());
i.setLine(locations[0].getTextRange().getStartLine());
});
db.commit();
return issue.getKey();
}
private URL toUrl(String fileName) {
Class<?> clazz = getClass();
String path = clazz.getSimpleName() + "/" + fileName;
URL url = clazz.getResource(path);
if (url == null) {
throw new IllegalStateException("Cannot find " + path);
}
return url;
}
}
| 12,241 | 42.878136 | 145 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/LinesActionIT.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.source.ws;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.stubbing.Answer;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbTester;
import org.sonar.db.audit.NoOpAuditPersister;
import org.sonar.db.component.ComponentDao;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ProjectData;
import org.sonar.db.component.SnapshotDao;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.protobuf.DbFileSources;
import org.sonar.db.source.FileSourceDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.component.TestComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.source.HtmlSourceDecorator;
import org.sonar.server.source.SourceService;
import org.sonar.server.source.index.FileSourceTesting;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static java.lang.String.format;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.db.component.BranchType.PULL_REQUEST;
import static org.sonar.db.component.ComponentTesting.newFileDto;
public class LinesActionIT {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final ComponentDao componentDao = new ComponentDao(new NoOpAuditPersister());
private final SnapshotDao snapshotDao = new SnapshotDao();
private final HtmlSourceDecorator htmlSourceDecorator = mock(HtmlSourceDecorator.class);
private final SourceService sourceService = new SourceService(db.getDbClient(), htmlSourceDecorator);
private final LinesJsonWriter linesJsonWriter = new LinesJsonWriter(htmlSourceDecorator);
private final LinesAction underTest = new LinesAction(TestComponentFinder.from(db), db.getDbClient(), sourceService, linesJsonWriter, userSession);
private final WsActionTester tester = new WsActionTester(underTest);
@Before
public void setUp() {
when(htmlSourceDecorator.getDecoratedSourceAsHtml(anyString(), anyString(), anyString()))
.then((Answer<String>) invocationOnMock -> "<p>" + invocationOnMock.getArguments()[0] + "</p>");
}
@Test
public void show_source() {
ComponentDto privateProject = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = insertFileWithData(FileSourceTesting.newFakeData(3).build(), privateProject);
setUserWithValidPermission(file, privateProject);
TestResponse response = tester.newRequest()
.setParam("uuid", file.uuid())
.execute();
response.assertJson(getClass(), "show_source.json");
}
@Test
public void fail_to_show_source_if_no_source_found() {
ComponentDto privateProject = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = insertFile(privateProject);
setUserWithValidPermission(file, privateProject);
TestRequest request = tester.newRequest()
.setParam("uuid", file.uuid());
assertThatThrownBy(() -> request.execute())
.isInstanceOf(NotFoundException.class);
}
@Test
public void show_paginated_lines() {
ComponentDto privateProject = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = insertFileWithData(FileSourceTesting.newFakeData(3).build(), privateProject);
setUserWithValidPermission(file, privateProject);
tester
.newRequest()
.setParam("uuid", file.uuid())
.setParam("from", "3")
.setParam("to", "3")
.execute()
.assertJson(getClass(), "show_paginated_lines.json");
}
@Test
public void branch() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
String branchName = randomAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
db.getDbClient().fileSourceDao().insert(db.getSession(), new FileSourceDto()
.setUuid(Uuids.createFast())
.setProjectUuid(branch.uuid())
.setFileUuid(file.uuid())
.setSourceData(FileSourceTesting.newFakeData(3).build()));
db.commit();
userSession.logIn("login")
.addProjectPermission(UserRole.USER, project)
.addProjectBranchMapping(project.uuid(), branch)
.addProjectPermission(UserRole.CODEVIEWER, project, file);
tester.newRequest()
.setParam("key", file.getKey())
.setParam("branch", branchName)
.execute()
.assertJson(getClass(), "show_source.json");
}
@Test
public void pull_request() {
ProjectData projectData = db.components().insertPrivateProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
String pullRequestKey = randomAlphanumeric(100);
ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey));
ComponentDto file = db.components().insertComponent(newFileDto(branch, mainBranch.uuid()));
db.getDbClient().fileSourceDao().insert(db.getSession(), new FileSourceDto()
.setUuid(Uuids.createFast())
.setProjectUuid(branch.uuid())
.setFileUuid(file.uuid())
.setSourceData(FileSourceTesting.newFakeData(3).build()));
db.commit();
userSession.logIn("login")
.addProjectPermission(UserRole.USER, projectData.getProjectDto())
.addProjectPermission(UserRole.CODEVIEWER, projectData.getProjectDto())
.addProjectPermission(UserRole.CODEVIEWER, file);
tester.newRequest()
.setParam("key", file.getKey())
.setParam("pullRequest", pullRequestKey)
.execute()
.assertJson(getClass(), "show_source.json");
}
@Test
public void fail_when_no_uuid_or_key_param() {
assertThatThrownBy(() -> tester.newRequest().execute())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Either 'uuid' or 'key' must be provided");
}
@Test
public void fail_when_file_key_does_not_exist() {
assertThatThrownBy(() -> tester.newRequest().setParam("key", "Foo.java").execute())
.isInstanceOf(NotFoundException.class)
.hasMessageContaining("Component key 'Foo.java' not found");
}
@Test
public void fail_when_file_uuid_does_not_exist() {
assertThatThrownBy(() -> tester.newRequest().setParam("uuid", "ABCD").execute())
.isInstanceOf(NotFoundException.class)
.hasMessageContaining("Component id 'ABCD' not found");
}
@Test
public void fail_when_file_is_removed() {
ComponentDto privateProject = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = newFileDto(privateProject).setKey("file-key").setEnabled(false);
db.components().insertComponents(file);
setUserWithValidPermission(file, privateProject);
assertThatThrownBy(() -> tester.newRequest().setParam("key", "file-key").execute())
.isInstanceOf(NotFoundException.class)
.hasMessageContaining("Component key 'file-key' not found");
}
@Test
public void check_permission() {
ComponentDto privateProject = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = insertFileWithData(FileSourceTesting.newFakeData(1).build(), privateProject);
userSession.logIn("login");
assertThatThrownBy(() -> {
tester.newRequest()
.setParam("uuid", file.uuid())
.execute();
})
.isInstanceOf(ForbiddenException.class);
}
@Test
public void display_deprecated_fields() {
ComponentDto privateProject = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = insertFileWithData(FileSourceTesting.newFakeData(1).build(), privateProject);
setUserWithValidPermission(file, privateProject);
tester.newRequest()
.setParam("uuid", file.uuid())
.execute()
.assertJson(getClass(), "display_deprecated_fields.json");
}
@Test
public void use_period_date_if_new_line_not_yet_available_in_db() {
DbFileSources.Data.Builder dataBuilder = DbFileSources.Data.newBuilder();
dataBuilder.addLines(DbFileSources.Line.newBuilder().setLine(1).setScmDate(1000L).build());
dataBuilder.addLines(DbFileSources.Line.newBuilder().setLine(2).setScmDate(2000L).build());
// only this line should be considered as new
dataBuilder.addLines(DbFileSources.Line.newBuilder().setLine(3).setScmDate(3000L).build());
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
insertPeriod(project, 2000L);
ComponentDto file = insertFileWithData(dataBuilder.build(), project);
setUserWithValidPermission(file, project);
tester.newRequest()
.setParam("uuid", file.uuid())
.execute()
.assertJson(getClass(), "generated_isNew.json");
}
@Test
public void use_deprecated_overall_coverage_fields_if_exists() {
ComponentDto privateProject = db.components().insertPrivateProject().getMainBranchComponent();
DbFileSources.Data.Builder dataBuilder = DbFileSources.Data.newBuilder();
ComponentDto file = insertFileWithData(dataBuilder.addLines(newLineBuilder()
.setDeprecatedOverallLineHits(1)
.setDeprecatedOverallConditions(2)
.setDeprecatedOverallCoveredConditions(3)
.setDeprecatedUtLineHits(1)
.setDeprecatedUtConditions(2)
.setDeprecatedUtCoveredConditions(3)
.setDeprecatedItLineHits(1)
.setDeprecatedItConditions(2)
.setDeprecatedItCoveredConditions(3)).build(), privateProject);
setUserWithValidPermission(file, privateProject);
tester.newRequest()
.setParam("uuid", file.uuid())
.execute()
.assertJson(getClass(), "convert_deprecated_data.json");
}
@Test
public void use_deprecated_ut_coverage_fields_if_exists() {
ComponentDto privateProject = db.components().insertPrivateProject().getMainBranchComponent();
DbFileSources.Data.Builder dataBuilder = DbFileSources.Data.newBuilder();
ComponentDto file = insertFileWithData(dataBuilder.addLines(newLineBuilder()
.setDeprecatedUtLineHits(1)
.setDeprecatedUtConditions(2)
.setDeprecatedUtCoveredConditions(3)
.setDeprecatedItLineHits(1)
.setDeprecatedItConditions(2)
.setDeprecatedItCoveredConditions(3)).build(), privateProject);
setUserWithValidPermission(file, privateProject);
tester.newRequest()
.setParam("uuid", file.uuid())
.execute()
.assertJson(getClass(), "convert_deprecated_data.json");
}
@Test
public void use_deprecated_it_coverage_fields_if_exists() {
ComponentDto privateProject = db.components().insertPrivateProject().getMainBranchComponent();
DbFileSources.Data.Builder dataBuilder = DbFileSources.Data.newBuilder();
ComponentDto file = insertFileWithData(dataBuilder.addLines(newLineBuilder()
.setDeprecatedItLineHits(1)
.setDeprecatedItConditions(2)
.setDeprecatedItCoveredConditions(3)).build(), privateProject);
setUserWithValidPermission(file, privateProject);
tester.newRequest()
.setParam("uuid", file.uuid())
.execute()
.assertJson(getClass(), "convert_deprecated_data.json");
}
@Test
public void fail_if_branch_does_not_exist() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
userSession.addProjectPermission(UserRole.USER, project);
db.components().insertProjectBranch(project, b -> b.setKey("my_branch"));
assertThatThrownBy(() -> tester.newRequest()
.setParam("key", file.getKey())
.setParam("branch", "another_branch")
.execute())
.isInstanceOf(NotFoundException.class)
.hasMessageContaining(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch"));
}
@Test
public void fail_when_uuid_and_branch_params_are_used_together() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
userSession.addProjectPermission(UserRole.USER, project);
db.components().insertProjectBranch(project, b -> b.setKey("my_branch"));
assertThatThrownBy(() -> tester.newRequest()
.setParam("uuid", file.uuid())
.setParam("branch", "another_branch")
.execute())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Parameter 'uuid' cannot be used at the same time as 'branch' or 'pullRequest'");
}
@Test
public void fail_when_using_branch_uuid() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto branch = db.components().insertProjectBranch(project);
userSession.addProjectPermission(UserRole.USER, project);
assertThatThrownBy(() -> tester.newRequest()
.setParam("uuid", branch.uuid())
.execute())
.isInstanceOf(NotFoundException.class)
.hasMessageContaining(format("Component id '%s' not found", branch.uuid()));
}
@Test
public void hide_scmAuthors() {
ProjectData projectData = db.components().insertPublicProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
userSession.registerProjects(projectData.getProjectDto());
userSession.addProjectBranchMapping(projectData.projectUuid(), mainBranch);
DbFileSources.Data data = DbFileSources.Data.newBuilder()
.addLines(newLineBuilder().setScmAuthor("isaac@asimov.com"))
.build();
ComponentDto file = insertFileWithData(data, mainBranch);
tester.newRequest()
.setParam("uuid", file.uuid())
.execute()
.assertJson(getClass(), "hide_scmAuthors.json");
}
@Test
public void show_scmAuthors() {
ProjectData projectData = db.components().insertPublicProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
UserDto user = db.users().insertUser();
userSession.logIn(user).registerProjects(projectData.getProjectDto());
userSession.addProjectBranchMapping(projectData.projectUuid(), mainBranch);
DbFileSources.Data data = DbFileSources.Data.newBuilder()
.addLines(newLineBuilder().setScmAuthor("isaac@asimov.com"))
.build();
ComponentDto file = insertFileWithData(data, mainBranch);
tester.newRequest()
.setParam("uuid", file.uuid())
.execute()
.assertJson(getClass(), "show_scmAuthors.json");
}
private ComponentDto insertFileWithData(DbFileSources.Data fileData, ComponentDto project) {
ComponentDto file = insertFile(project);
db.getDbClient().fileSourceDao().insert(db.getSession(), new FileSourceDto()
.setUuid(Uuids.createFast())
.setProjectUuid(project.branchUuid())
.setFileUuid(file.uuid())
.setSourceData(fileData));
db.commit();
return file;
}
private void setUserWithValidPermission(ComponentDto file, ComponentDto privateProject) {
userSession.logIn("login")
.addProjectPermission(UserRole.CODEVIEWER, privateProject, file);
}
private ComponentDto insertFile(ComponentDto project) {
ComponentDto file = newFileDto(project);
componentDao.insertOnMainBranch(db.getSession(), file);
db.getSession().commit();
return file;
}
private DbFileSources.Line.Builder newLineBuilder() {
return DbFileSources.Line.newBuilder()
.setLine(1)
.setScmRevision("REVISION_" + 1)
.setScmAuthor("AUTHOR_" + 1)
.setScmDate(1_500_000_000_00L)
.setSource("SOURCE_" + 1);
}
private void insertPeriod(ComponentDto componentDto, long date) {
SnapshotDto dto = new SnapshotDto();
dto.setUuid("uuid");
dto.setLast(true);
dto.setPeriodDate(date);
dto.setRootComponentUuid(componentDto.uuid());
snapshotDao.insert(db.getSession(), dto);
}
}
| 17,252 | 38.9375 | 149 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/RawActionIT.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.source.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ResourceTypesRule;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.source.SourceService;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsActionTester;
import static java.lang.String.format;
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.sonar.db.component.ComponentTesting.newFileDto;
import static org.sonar.db.protobuf.DbFileSources.Data;
import static org.sonar.db.protobuf.DbFileSources.Line;
public class RawActionIT {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private ResourceTypesRule resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT);
private WsActionTester ws = new WsActionTester(new RawAction(db.getDbClient(),
new SourceService(db.getDbClient(), null), userSession,
new ComponentFinder(db.getDbClient(), resourceTypes)));
@Test
public void raw_from_file() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
userSession.addProjectPermission(UserRole.CODEVIEWER, project);
ComponentDto file = db.components().insertComponent(newFileDto(project));
db.fileSources().insertFileSource(file, s -> s.setSourceData(
Data.newBuilder()
.addLines(Line.newBuilder().setLine(1).setSource("public class HelloWorld {").build())
.addLines(Line.newBuilder().setLine(2).setSource("}").build())
.build()));
String result = ws.newRequest()
.setParam("key", file.getKey())
.execute().getInput();
assertThat(result).isEqualTo("public class HelloWorld {\n}\n");
}
@Test
public void raw_from_branch_file() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
userSession.addProjectPermission(UserRole.CODEVIEWER, project);
String branchName = randomAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
userSession.addProjectBranchMapping(project.uuid(), branch);
ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
db.fileSources().insertFileSource(file, s -> s.setSourceData(
Data.newBuilder()
.addLines(Line.newBuilder().setLine(1).setSource("public class HelloWorld {").build())
.addLines(Line.newBuilder().setLine(2).setSource("}").build())
.build()));
String result = ws.newRequest()
.setParam("key", file.getKey())
.setParam("branch", branchName)
.execute().getInput();
assertThat(result).isEqualTo("public class HelloWorld {\n}\n");
}
@Test
public void fail_on_unknown_file() {
assertThatThrownBy(() -> ws.newRequest()
.setParam("key", "unknown")
.execute())
.isInstanceOf(NotFoundException.class)
.hasMessageContaining("Component key 'unknown' not found");
}
@Test
public void fail_on_unknown_branch() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
userSession.addProjectPermission(UserRole.CODEVIEWER, project);
ComponentDto branch = db.components().insertProjectBranch(project);
ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
db.fileSources().insertFileSource(file);
assertThatThrownBy(() -> ws.newRequest()
.setParam("key", file.getKey())
.setParam("branch", "unknown")
.execute())
.isInstanceOf(NotFoundException.class)
.hasMessageContaining(format("Component '%s' on branch 'unknown' not found", file.getKey()));
}
@Test
public void fail_when_using_branch_db_key() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
userSession.addProjectPermission(UserRole.CODEVIEWER, project);
ComponentDto branch = db.components().insertProjectBranch(project);
ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid()));
db.fileSources().insertFileSource(file);
assertThatThrownBy(() -> ws.newRequest()
.setParam("key", file.getKey())
.execute())
.isInstanceOf(NotFoundException.class)
.hasMessageContaining(format("Component key '%s' not found", file.getKey()));
}
@Test
public void fail_when_wrong_permission() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
userSession.addProjectPermission(UserRole.ISSUE_ADMIN, project);
ComponentDto file = db.components().insertComponent(newFileDto(project));
assertThatThrownBy(() -> ws.newRequest()
.setParam("key", file.getKey())
.execute())
.isInstanceOf(ForbiddenException.class);
}
}
| 6,189 | 40.266667 | 106 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/ScmActionIT.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.source.ws;
import java.util.Date;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.protobuf.DbFileSources;
import org.sonar.db.source.FileSourceDto;
import org.sonar.server.component.TestComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.source.HtmlSourceDecorator;
import org.sonar.server.source.SourceService;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ScmActionIT {
private static final String FILE_KEY = "FILE_KEY";
private static final String FILE_UUID = "FILE_A";
private static final String PROJECT_UUID = "PROJECT_A";
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
private final DbClient dbClient = dbTester.getDbClient();
private final DbSession dbSession = dbTester.getSession();
private final ScmAction underTest = new ScmAction(dbClient, new SourceService(dbTester.getDbClient(), new HtmlSourceDecorator()),
userSessionRule, TestComponentFinder.from(dbTester));
private final WsActionTester tester = new WsActionTester(underTest);
private ComponentDto project;
private ComponentDto file;
@Before
public void setUp() {
project = dbTester.components().insertPrivateProject(PROJECT_UUID).getMainBranchComponent();
file = ComponentTesting.newFileDto(project, null, FILE_UUID).setKey(FILE_KEY);
dbClient.componentDao().insertOnMainBranch(dbTester.getSession(), file);
dbTester.getSession().commit();
}
@Test
public void show_scm() {
userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project, file);
dbTester.getDbClient().fileSourceDao().insert(dbSession, new FileSourceDto()
.setUuid(Uuids.createFast())
.setProjectUuid(PROJECT_UUID)
.setFileUuid(FILE_UUID)
.setSourceData(DbFileSources.Data.newBuilder().addLines(
newSourceLine("julien", "123-456-789", DateUtils.parseDateTime("2015-03-30T12:34:56+0000"), 1)).build()));
dbSession.commit();
tester.newRequest()
.setParam("key", FILE_KEY)
.execute()
.assertJson(getClass(), "show_scm.json");
}
@Test
public void show_scm_from_given_range_lines() {
userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project, file);
dbTester.getDbClient().fileSourceDao().insert(dbSession, new FileSourceDto()
.setUuid(Uuids.createFast())
.setProjectUuid(PROJECT_UUID)
.setFileUuid(FILE_UUID)
.setSourceData(DbFileSources.Data.newBuilder()
.addLines(newSourceLine("julien", "123-456-789", DateUtils.parseDateTime("2015-03-30T12:34:56+0000"), 1))
.addLines(newSourceLine("julien", "123-456-789", DateUtils.parseDateTime("2015-03-30T12:34:56+0000"), 2))
.addLines(newSourceLine("julien", "456-789-101", DateUtils.parseDateTime("2015-03-27T12:34:56+0000"), 3))
.addLines(newSourceLine("simon", "789-101-112", DateUtils.parseDateTime("2015-03-31T12:34:56+0000"), 4))
.build()));
dbSession.commit();
tester.newRequest()
.setParam("key", FILE_KEY)
.setParam("from", "2")
.setParam("to", "3")
.execute()
.assertJson(getClass(), "show_scm_from_given_range_lines.json");
}
@Test
public void not_group_lines_by_commit() {
userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project, file);
// lines 1 and 2 are the same commit, but not 3 (different date)
dbTester.getDbClient().fileSourceDao().insert(dbSession, new FileSourceDto()
.setUuid(Uuids.createFast())
.setProjectUuid(PROJECT_UUID)
.setFileUuid(FILE_UUID)
.setSourceData(DbFileSources.Data.newBuilder()
.addLines(newSourceLine("julien", "123-456-789", DateUtils.parseDateTime("2015-03-30T12:34:56+0000"), 1))
.addLines(newSourceLine("julien", "123-456-789", DateUtils.parseDateTime("2015-03-30T12:34:56+0000"), 2))
.addLines(newSourceLine("julien", "456-789-101", DateUtils.parseDateTime("2015-03-27T12:34:56+0000"), 3))
.addLines(newSourceLine("simon", "789-101-112", DateUtils.parseDateTime("2015-03-31T12:34:56+0000"), 4))
.build()));
dbSession.commit();
tester.newRequest()
.setParam("key", FILE_KEY)
.setParam("commits_by_line", "true")
.execute()
.assertJson(getClass(), "not_group_lines_by_commit.json");
}
@Test
public void group_lines_by_commit() {
userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project, file);
// lines 1 and 2 are the same commit, but not 3 (different date)
dbTester.getDbClient().fileSourceDao().insert(dbSession, new FileSourceDto()
.setUuid(Uuids.createFast())
.setProjectUuid(PROJECT_UUID)
.setFileUuid(FILE_UUID)
.setSourceData(DbFileSources.Data.newBuilder()
.addLines(newSourceLine("julien", "123-456-789", DateUtils.parseDateTime("2015-03-30T12:34:56+0000"), 1))
.addLines(newSourceLine("julien", "123-456-789", DateUtils.parseDateTime("2015-03-30T12:34:56+0000"), 2))
.addLines(newSourceLine("julien", "456-789-101", DateUtils.parseDateTime("2015-03-27T12:34:56+0000"), 3))
.addLines(newSourceLine("simon", "789-101-112", DateUtils.parseDateTime("2015-03-31T12:34:56+0000"), 4))
.build()));
dbSession.commit();
tester.newRequest()
.setParam("key", FILE_KEY)
.setParam("commits_by_line", "false")
.execute()
.assertJson(getClass(), "group_lines_by_commit.json");
}
@Test
public void accept_negative_value_in_from_parameter() {
userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project, file);
dbTester.getDbClient().fileSourceDao().insert(dbSession, new FileSourceDto()
.setUuid(Uuids.createFast())
.setProjectUuid(PROJECT_UUID)
.setFileUuid(FILE_UUID)
.setSourceData(DbFileSources.Data.newBuilder()
.addLines(newSourceLine("julien", "123-456-789", DateUtils.parseDateTime("2015-03-30T12:34:56+0000"), 1))
.addLines(newSourceLine("julien", "123-456-710", DateUtils.parseDateTime("2015-03-29T12:34:56+0000"), 2))
.addLines(newSourceLine("julien", "456-789-101", DateUtils.parseDateTime("2015-03-27T12:34:56+0000"), 3))
.addLines(newSourceLine("simon", "789-101-112", DateUtils.parseDateTime("2015-03-31T12:34:56+0000"), 4))
.build()));
dbSession.commit();
tester.newRequest()
.setParam("key", FILE_KEY)
.setParam("from", "-2")
.setParam("to", "3")
.execute()
.assertJson(getClass(), "accept_negative_value_in_from_parameter.json");
}
@Test
public void return_empty_value_when_no_scm() {
userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project, file);
dbTester.getDbClient().fileSourceDao().insert(dbSession, new FileSourceDto()
.setUuid(Uuids.createFast())
.setProjectUuid(PROJECT_UUID)
.setFileUuid(FILE_UUID)
.setSourceData(DbFileSources.Data.newBuilder().build()));
dbSession.commit();
tester.newRequest()
.setParam("key", FILE_KEY)
.execute()
.assertJson(getClass(), "return_empty_value_when_no_scm.json");
}
@Test
public void fail_without_code_viewer_permission() {
userSessionRule.addProjectPermission(UserRole.USER, project, file);
assertThatThrownBy(() -> {
tester.newRequest()
.setParam("key", FILE_KEY)
.execute();
})
.isInstanceOf(ForbiddenException.class);
}
private DbFileSources.Line newSourceLine(String author, String revision, Date date, int line) {
return DbFileSources.Line.newBuilder()
.setScmAuthor(author)
.setScmRevision(revision)
.setScmDate(date.getTime())
.setLine(line)
.build();
}
}
| 9,051 | 39.231111 | 131 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/source/ws/ShowActionIT.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.source.ws;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDao;
import org.sonar.db.component.ComponentDao;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.component.ResourceTypesRule;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.source.SourceService;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsActionTester;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class ShowActionIT {
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
private SourceService sourceService = mock(SourceService.class);
private DbClient dbClient = mock(DbClient.class);
private DbSession session = mock(DbSession.class);
private ComponentDao componentDao = mock(ComponentDao.class);
private BranchDao branchDao = mock(BranchDao.class);
private ComponentDto project = ComponentTesting.newPrivateProjectDto();
private ComponentDto file = ComponentTesting.newFileDto(project);
private ShowAction underTest = new ShowAction(sourceService, dbClient, userSessionRule,
new ComponentFinder(dbClient, new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT)));
private WsActionTester tester = new WsActionTester(underTest);
@Before
public void setUp() {
when(dbClient.componentDao()).thenReturn(componentDao);
when(dbClient.branchDao()).thenReturn(branchDao);
when(dbClient.openSession(false)).thenReturn(session);
}
@Test
public void show_source() {
String fileKey = "src/Foo.java";
userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project);
when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file));
when(sourceService.getLinesAsHtml(eq(session), eq(file.uuid()), anyInt(), anyInt())).thenReturn(Optional.of(newArrayList(
"/*",
" * Header",
" */",
"",
"public class <span class=\"sym-31 sym\">HelloWorld</span> {",
"}")));
tester.newRequest()
.setParam("key", fileKey)
.execute()
.assertJson(getClass(), "show_source.json");
}
@Test
public void show_source_with_from_and_to_params() {
String fileKey = "src/Foo.java";
userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project);
when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file));
when(sourceService.getLinesAsHtml(session, file.uuid(), 3, 5)).thenReturn(Optional.of(newArrayList(
" */",
"",
"public class <span class=\"sym-31 sym\">HelloWorld</span> {")));
tester.newRequest()
.setParam("key", fileKey)
.setParam("from", "3")
.setParam("to", "5")
.execute()
.assertJson(getClass(), "show_source_with_params_from_and_to.json");
}
@Test
public void show_source_accept_from_less_than_one() {
String fileKey = "src/Foo.java";
userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project);
when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file));
when(sourceService.getLinesAsHtml(session, file.uuid(), 1, 5)).thenReturn(Optional.of(newArrayList(
" */",
"",
"public class <span class=\"sym-31 sym\">HelloWorld</span> {")));
tester.newRequest()
.setParam("key", fileKey)
.setParam("from", "0")
.setParam("to", "5")
.execute();
verify(sourceService).getLinesAsHtml(session, file.uuid(), 1, 5);
}
@Test
public void require_code_viewer() {
String fileKey = "src/Foo.java";
when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file));
assertThatThrownBy(() -> tester.newRequest().setParam("key", fileKey).execute())
.isInstanceOf(ForbiddenException.class);
}
}
| 5,199 | 37.80597 | 125 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ui/ws/ComponentActionIT.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.ui.ws;
import com.google.common.collect.ImmutableSet;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Configuration;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.ResourceType;
import org.sonar.api.resources.ResourceTypes;
import org.sonar.api.resources.Scopes;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.api.web.page.Page;
import org.sonar.api.web.page.Page.Qualifier;
import org.sonar.api.web.page.PageDefinition;
import org.sonar.core.component.DefaultResourceTypes;
import org.sonar.core.extension.CoreExtensionRepository;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginRepository;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ProjectData;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.property.PropertyDbTester;
import org.sonar.db.property.PropertyDto;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.qualitygate.QualityGateFinder;
import org.sonar.server.qualityprofile.QPMeasureData;
import org.sonar.server.qualityprofile.QualityProfile;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ui.PageRepository;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonar.updatecenter.common.Version;
import static java.util.Optional.of;
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.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.api.measures.CoreMetrics.QUALITY_PROFILES_KEY;
import static org.sonar.api.utils.DateUtils.parseDateTime;
import static org.sonar.api.web.page.Page.Scope.COMPONENT;
import static org.sonar.db.component.ComponentTesting.newDirectory;
import static org.sonar.db.component.ComponentTesting.newFileDto;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
import static org.sonar.db.component.ComponentTesting.newSubPortfolio;
import static org.sonar.db.component.SnapshotTesting.newAnalysis;
import static org.sonar.db.measure.MeasureTesting.newLiveMeasure;
import static org.sonar.db.metric.MetricTesting.newMetricDto;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
import static org.sonar.server.ui.ws.ComponentAction.PARAM_COMPONENT;
import static org.sonar.test.JsonAssert.assertJson;
public class ComponentActionIT {
@Rule
public final DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public final UserSessionRule userSession = UserSessionRule.standalone();
private final DbClient dbClient = db.getDbClient();
private final ComponentDbTester componentDbTester = db.components();
private final PropertyDbTester propertyDbTester = new PropertyDbTester(db);
private final ResourceTypes resourceTypes = mock(ResourceTypes.class);
private final Configuration config = mock(Configuration.class);
private WsActionTester ws;
@Before
public void setup() {
ResourceType resourceType = mock(ResourceType.class);
when(resourceType.getBooleanProperty(any())).thenReturn(true);
when(resourceTypes.get(any())).thenReturn(resourceType);
}
@Test
public void return_info_if_user_has_browse_permission_on_project() {
ProjectData project = insertProject();
userSession.logIn().addProjectPermission(UserRole.USER, project.getProjectDto())
.registerBranches(project.getMainBranchDto());
init();
verifySuccess(project.projectKey());
}
@Test
public void return_info_if_user_has_administration_permission_on_project() {
ProjectData project = insertProject();
userSession.logIn().addProjectPermission(UserRole.ADMIN, project.getProjectDto())
.registerBranches(project.getMainBranchDto());
init();
verifySuccess(project.projectKey());
}
@Test
public void return_info_if_user_is_system_administrator() {
ProjectData project = insertProject();
userSession.logIn().setSystemAdministrator();
init();
verifySuccess(project.projectKey());
}
@Test
public void return_component_info_when_anonymous_no_snapshot() {
ProjectData project = insertProject();
userSession.addProjectPermission(UserRole.USER, project.getProjectDto())
.registerBranches(project.getMainBranchDto());
init();
executeAndVerify(project.projectKey(), "return_component_info_when_anonymous_no_snapshot.json");
}
@Test
public void return_component_info_with_favourite() {
ProjectData projectData = insertProject();
UserDto user = db.users().insertUser("obiwan");
propertyDbTester.insertProperty(new PropertyDto().setKey("favourite").setEntityUuid(projectData.getProjectDto().getUuid()).setUserUuid(user.getUuid()),
projectData.getProjectDto().getKey(), projectData.getProjectDto().getName(), projectData.getProjectDto().getQualifier(), user.getLogin());
userSession.logIn(user).addProjectPermission(UserRole.USER, projectData.getProjectDto())
.registerBranches(projectData.getMainBranchDto());
init();
executeAndVerify(projectData.projectKey(), "return_component_info_with_favourite.json");
}
@Test
public void return_favourite_for_branch() {
ProjectData projectData = insertProject();
ProjectDto projectDto = projectData.getProjectDto();
String branchName = "feature1";
BranchDto branch = componentDbTester.insertProjectBranch(projectDto, b -> b.setKey(branchName).setUuid("xyz"));
UserDto user = db.users().insertUser("obiwan");
propertyDbTester.insertProperty(new PropertyDto().setKey("favourite").setEntityUuid(projectData.projectUuid()).setUserUuid(user.getUuid()),
projectDto.getKey(), projectDto.getName(), projectDto.getQualifier(), user.getLogin());
userSession.logIn(user).addProjectPermission(UserRole.USER, projectData.getProjectDto())
.registerBranches(branch);
init();
String json = ws.newRequest()
.setParam("component", projectData.projectKey())
.setParam("branch", branchName)
.execute()
.getInput();
assertJson(json).isSimilarTo("{\n" +
" \"key\": \"polop\",\n" +
" \"isFavorite\": true,\n" +
" \"id\": \"xyz\",\n" +
" \"branch\": \"feature1\"," +
" \"name\": \"Polop\",\n" +
" \"description\": \"test project\"\n" +
"}\n");
}
@Test
public void return_favourite_for_subportfolio() {
db.qualityGates().createDefaultQualityGate();
ComponentDto portfolio = componentDbTester.insertPrivatePortfolio();
ComponentDto subportfolio = componentDbTester.insertComponent(newSubPortfolio(portfolio));
UserDto user = db.users().insertUser("obiwan");
// set favourite for sub portfolio
propertyDbTester.insertProperty(new PropertyDto().setKey("favourite").setEntityUuid(subportfolio.uuid()).setUserUuid(user.getUuid()),
subportfolio.getKey(), subportfolio.name(), subportfolio.qualifier(), user.getLogin());
userSession.logIn(user).addProjectPermission(UserRole.USER, portfolio)
.addProjectPermission(UserRole.USER, subportfolio);
init();
String json = ws.newRequest()
.setParam("component", subportfolio.getKey())
.execute()
.getInput();
assertJson(json).isSimilarTo("{" +
" \"key\": \"" + subportfolio.getKey() + "\"," +
" \"isFavorite\": true," +
" \"id\": \"" + subportfolio.uuid() + "\"," +
" \"name\": \"" + subportfolio.name() + "\"" +
"}");
}
@Test
public void return_favourite_for_portfolio() {
db.qualityGates().createDefaultQualityGate();
ComponentDto portfolio = componentDbTester.insertPrivatePortfolio();
ComponentDto subportfolio = componentDbTester.insertComponent(newSubPortfolio(portfolio));
UserDto user = db.users().insertUser("obiwan");
// set favourite for sub portfolio
propertyDbTester.insertProperty(new PropertyDto().setKey("favourite").setEntityUuid(portfolio.uuid()).setUserUuid(user.getUuid()),
subportfolio.getKey(), portfolio.name(), portfolio.qualifier(), user.getLogin());
userSession.logIn(user).addProjectPermission(UserRole.USER, portfolio);
init();
String json = ws.newRequest()
.setParam("component", portfolio.getKey())
.execute()
.getInput();
assertJson(json).isSimilarTo("{" +
" \"key\": \"" + portfolio.getKey() + "\"," +
" \"isFavorite\": true," +
" \"id\": \"" + portfolio.uuid() + "\"," +
" \"name\": \"" + portfolio.name() + "\"" +
"}");
}
@Test
public void return_canBrowseAllChildProjects_when_component_is_an_application() {
db.qualityGates().createDefaultQualityGate();
ProjectData application1 = db.components().insertPrivateApplication();
ProjectData project11 = db.components().insertPrivateProject();
ProjectData project12 = db.components().insertPrivateProject();
userSession.registerApplication(
application1.getProjectDto(),
project11.getProjectDto(),
project12.getProjectDto());
userSession.addProjectPermission(UserRole.USER, application1.getProjectDto(), project11.getProjectDto(), project12.getProjectDto())
.registerBranches(application1.getMainBranchDto());
ProjectData application2 = db.components().insertPrivateApplication();
ProjectData project21 = db.components().insertPrivateProject();
ProjectData project22 = db.components().insertPrivateProject();
userSession.registerApplication(
application2.getProjectDto(),
project21.getProjectDto(),
project22.getProjectDto());
userSession.addProjectPermission(UserRole.USER, application2.getProjectDto(), project21.getProjectDto())
.registerBranches(application2.getMainBranchDto());
init();
// access to all projects (project11, project12)
String json = execute(application1.projectKey());
assertJson(json).isSimilarTo("{" +
"\"canBrowseAllChildProjects\":true" +
"}");
// access to some projects (project11)
json = execute(application2.projectKey());
assertJson(json).isSimilarTo("{" +
"\"canBrowseAllChildProjects\":false" +
"}");
}
@Test
public void return_component_info_when_snapshot() {
ProjectData project = insertProject();
db.components().insertSnapshot(project, snapshot -> snapshot
.setCreatedAt(parseDateTime("2015-04-22T11:44:00+0200").getTime())
.setProjectVersion("3.14"));
userSession.addProjectPermission(UserRole.USER, project.getProjectDto())
.registerBranches(project.getMainBranchDto());
init();
executeAndVerify(project.projectKey(), "return_component_info_when_snapshot.json");
}
@Test
public void return_component_info_when_file_on_master() {
db.qualityGates().createDefaultQualityGate();
ComponentDto main = componentDbTester.insertPrivateProject(p -> p.setName("Sample").setKey("sample")).getMainBranchComponent();
userSession.addProjectPermission(UserRole.USER, main);
init();
ComponentDto dirDto = componentDbTester.insertComponent(newDirectory(main, "src"));
ComponentDto fileDto = componentDbTester.insertComponent(newFileDto(main, dirDto)
.setUuid("abcd")
.setName("Main.xoo")
.setKey("sample:src/Main.xoo"));
executeAndVerify(fileDto.getKey(), "return_component_info_when_file_on_master.json");
}
@Test
public void return_component_info_when_file_on_branch() {
db.qualityGates().createDefaultQualityGate();
ProjectData project = componentDbTester.insertPrivateProject(p -> p.setName("Sample").setKey("sample"));
String branchName = "feature1";
ComponentDto branch = componentDbTester.insertProjectBranch(project.getMainBranchComponent(), b -> b.setKey(branchName));
userSession.addProjectPermission(UserRole.USER, project.getProjectDto());
userSession.addProjectBranchMapping(project.projectUuid(), branch);
init();
ComponentDto dirDto = componentDbTester.insertComponent(newDirectory(branch, "src"));
ComponentDto fileDto = componentDbTester.insertComponent(newFileDto(project.projectUuid(), branch, dirDto)
.setUuid("abcd")
.setName("Main.xoo"));
String json = ws.newRequest()
.setParam("component", fileDto.getKey())
.setParam("branch", branchName)
.execute()
.getInput();
assertJson(json).isSimilarTo("{\n" +
" \"key\": \"" + fileDto.getKey() + "\",\n" +
" \"branch\": \"feature1\",\n" +
" \"name\": \"Main.xoo\",\n" +
" \"breadcrumbs\": [\n" +
" {\n" +
" \"key\": \"sample\",\n" +
" \"name\": \"Sample\",\n" +
" \"qualifier\": \"TRK\"\n" +
" },\n" +
" {\n" +
" \"key\": \"sample:src\",\n" +
" \"name\": \"src\",\n" +
" \"qualifier\": \"DIR\"\n" +
" },\n" +
" {\n" +
" \"key\": \"" + fileDto.getKey() + "\",\n" +
" \"name\": \"Main.xoo\",\n" +
" \"qualifier\": \"FIL\"\n" +
" }\n" +
" ]\n" +
"}\n");
}
@Test
public void return_quality_profiles_and_supports_deleted_ones() {
ProjectData project = insertProject();
QProfileDto qp1 = db.qualityProfiles().insert(t -> t.setKee("qp1").setName("Sonar Way Java").setLanguage("java"));
QProfileDto qp2 = db.qualityProfiles().insert(t -> t.setKee("qp2").setName("Sonar Way Xoo").setLanguage("xoo"));
addQualityProfiles(project.getMainBranchComponent(),
new QualityProfile(qp1.getKee(), qp1.getName(), qp1.getLanguage(), new Date()),
new QualityProfile(qp2.getKee(), qp2.getName(), qp2.getLanguage(), new Date()));
userSession.addProjectPermission(UserRole.USER, project.getProjectDto())
.registerBranches(project.getMainBranchDto());
init();
executeAndVerify(project.projectKey(), "return_quality_profiles.json");
db.getDbClient().qualityProfileDao().deleteOrgQProfilesByUuids(db.getSession(), ImmutableSet.of(qp1.getKee(), qp2.getKee()));
db.commit();
executeAndVerify(project.projectKey(), "return_deleted_quality_profiles.json");
}
@Test
public void return_empty_quality_profiles_when_no_measure() {
ProjectData project = insertProject();
userSession.addProjectPermission(UserRole.USER, project.getProjectDto())
.registerBranches(project.getMainBranchDto());
init();
executeAndVerify(project.projectKey(), "return_empty_quality_profiles_when_no_measure.json");
}
@Test
public void return_quality_gate_defined_on_project() {
db.qualityGates().createDefaultQualityGate();
ProjectData project = db.components().insertPrivateProject();
QualityGateDto qualityGateDto = db.qualityGates().insertQualityGate(qg -> qg.setName("Sonar way"));
db.qualityGates().associateProjectToQualityGate(project.getProjectDto(), qualityGateDto);
userSession.addProjectPermission(UserRole.USER, project.getProjectDto())
.registerBranches(project.getMainBranchDto());
init();
executeAndVerify(project.projectKey(), "return_quality_gate.json");
}
@Test
public void quality_gate_for_a_branch() {
db.qualityGates().createDefaultQualityGate();
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
BranchDto branch = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH));
QualityGateDto qualityGateDto = db.qualityGates().insertQualityGate(qg -> qg.setName("Sonar way"));
db.qualityGates().associateProjectToQualityGate(project, qualityGateDto);
userSession.addProjectPermission(UserRole.USER, project)
.addProjectBranchMapping(project.getUuid(), db.components().getComponentDto(branch));
init();
String json = ws.newRequest()
.setParam("component", project.getKey())
.setParam("branch", branch.getKey())
.execute()
.getInput();
verify(json, "return_quality_gate.json");
}
@Test
public void return_default_quality_gate() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
db.qualityGates().createDefaultQualityGate(qg -> qg.setName("Sonar way"));
userSession.addProjectPermission(UserRole.USER, project);
init();
executeAndVerify(project.getKey(), "return_default_quality_gate.json");
}
@Test
public void return_extensions() {
ProjectData project = insertProject();
userSession.anonymous().addProjectPermission(UserRole.USER, project.getProjectDto())
.registerBranches(project.getMainBranchDto());
init(createPages());
executeAndVerify(project.projectKey(), "return_extensions.json");
}
@Test
public void return_extensions_for_application() {
db.qualityGates().createDefaultQualityGate();
ProjectDto project = db.components().insertPrivateProject().getProjectDto();
Page page = Page.builder("my_plugin/app_page")
.setName("App Page")
.setScope(COMPONENT)
.setComponentQualifiers(Qualifier.VIEW, Qualifier.APP)
.build();
ProjectData projectData = componentDbTester.insertPublicApplication();
ComponentDto application = projectData.getMainBranchComponent();
QualityGateDto qualityGateDto = db.qualityGates().insertQualityGate(qg -> qg.setName("Sonar way"));
db.qualityGates().associateProjectToQualityGate(project, qualityGateDto);
userSession.registerProjects(projectData.getProjectDto())
.registerBranches(projectData.getMainBranchDto());
init(page);
String result = ws.newRequest()
.setParam(PARAM_COMPONENT, application.getKey())
.execute().getInput();
assertThat(result).contains("my_plugin/app_page");
}
@Test
public void return_extensions_for_admin() {
ProjectData project = insertProject();
userSession.anonymous()
.addProjectPermission(UserRole.USER, project.getProjectDto())
.addProjectPermission(UserRole.ADMIN, project.getProjectDto())
.registerBranches(project.getMainBranchDto());
init(createPages());
executeAndVerify(project.projectKey(), "return_extensions_for_admin.json");
}
@Test
public void return_configuration_for_admin() {
ProjectData project = insertProject();
UserDto user = db.users().insertUser();
userSession.logIn(user)
.addProjectPermission(UserRole.USER, project.getProjectDto())
.addProjectPermission(UserRole.ADMIN, project.getProjectDto())
.registerBranches(project.getMainBranchDto());
Page page1 = Page.builder("my_plugin/first_page")
.setName("First Page")
.setAdmin(true)
.setScope(COMPONENT)
.setComponentQualifiers(Qualifier.PROJECT)
.build();
Page page2 = Page.builder("my_plugin/second_page")
.setName("Second Page")
.setAdmin(true)
.setScope(COMPONENT)
.setComponentQualifiers(Qualifier.PROJECT)
.build();
init(page1, page2);
executeAndVerify(project.projectKey(), "return_configuration_for_admin.json");
}
@Test
public void return_configuration_with_all_properties() {
ProjectData project = insertProject();
userSession.anonymous()
.addProjectPermission(UserRole.USER, project.getProjectDto())
.addProjectPermission(UserRole.ADMIN, project.getProjectDto())
.registerBranches(project.getMainBranchDto());
ResourceType projectResourceType = ResourceType.builder(project.getProjectDto().getQualifier())
.setProperty("comparable", true)
.setProperty("configurable", true)
.setProperty("hasRolePolicy", true)
.setProperty("modifiable_history", true)
.setProperty("updatable_key", true)
.setProperty("deletable", true)
.build();
when(resourceTypes.get(project.getProjectDto().getQualifier()))
.thenReturn(projectResourceType);
init();
executeAndVerify(project.projectKey(), "return_configuration_with_all_properties.json");
}
@Test
public void return_configuration_for_quality_profile_admin() {
ProjectData project = insertProject();
userSession.logIn()
.addProjectPermission(UserRole.USER, project.getProjectDto())
.addPermission(ADMINISTER_QUALITY_PROFILES)
.registerBranches(project.getMainBranchDto());
init();
executeAndVerify(project.projectKey(), "return_configuration_for_quality_profile_admin.json");
}
@Test
public void return_configuration_for_quality_gate_admin() {
ProjectData project = insertProject();
userSession.logIn()
.addProjectPermission(UserRole.USER, project.getProjectDto())
.addPermission(ADMINISTER_QUALITY_GATES)
.registerBranches(project.getMainBranchDto());
init();
executeAndVerify(project.projectKey(), "return_configuration_for_quality_gate_admin.json");
}
@Test
public void return_configuration_for_private_projects_for_user_with_project_administer_permission_when_permission_management_is_enabled_for_project_admins() {
ProjectData project = insertProject();
UserSessionRule userSessionRule = userSession.logIn();
init();
userSessionRule.addProjectPermission(UserRole.USER, project.getProjectDto())
.registerBranches(project.getMainBranchDto())
.addProjectPermission(UserRole.ADMIN, project.getProjectDto());
String json = execute(project.projectKey());
assertJson(json).isSimilarTo("{\n" +
" \"configuration\": {\n" +
" \"showSettings\": true,\n" +
" \"showQualityProfiles\": true,\n" +
" \"showQualityGates\": true,\n" +
" \"showLinks\": true,\n" +
" \"showPermissions\": true,\n" +
" \"showHistory\": true,\n" +
" \"showUpdateKey\": true,\n" +
" \"showBackgroundTasks\": true,\n" +
" \"canApplyPermissionTemplate\": false,\n" +
" \"canBrowseProject\": true,\n" +
" \"canUpdateProjectVisibilityToPrivate\": true\n" +
" }\n" +
"}");
}
@Test
public void return_configuration_for_private_projects_for_user_with_project_administer_permission_when_permission_management_is_disabled_for_project_admins() {
when(config.getBoolean(CoreProperties.CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_PROPERTY)).thenReturn(of(false));
ProjectData project = insertProject();
UserSessionRule userSessionRule = userSession.logIn();
init();
userSessionRule.addProjectPermission(UserRole.USER, project.getProjectDto())
.addProjectPermission(UserRole.ADMIN, project.getProjectDto())
.registerBranches(project.getMainBranchDto());
String json = execute(project.projectKey());
assertJson(json).isSimilarTo("{\n" +
" \"configuration\": {\n" +
" \"showSettings\": true,\n" +
" \"showQualityProfiles\": true,\n" +
" \"showQualityGates\": true,\n" +
" \"showLinks\": true,\n" +
" \"showPermissions\": false,\n" +
" \"showHistory\": true,\n" +
" \"showUpdateKey\": true,\n" +
" \"showBackgroundTasks\": true,\n" +
" \"canApplyPermissionTemplate\": false,\n" +
" \"canBrowseProject\": true,\n" +
" \"canUpdateProjectVisibilityToPrivate\": true\n" +
" }\n" +
"}");
}
@Test
public void do_not_return_configuration_for_private_projects_for_user_with_view_permission_only() {
ProjectData project = insertProject();
UserSessionRule userSessionRule = userSession.logIn();
init();
userSessionRule.addProjectPermission(UserRole.USER, project.getProjectDto())
.registerBranches(project.getMainBranchDto());
String json = execute(project.projectKey());
assertThat(json).doesNotContain("\"configuration\"");
}
@Test
public void return_bread_crumbs_on_several_levels() {
ProjectData project = insertProject();
ComponentDto directory = componentDbTester.insertComponent(newDirectory(project.getMainBranchComponent(), "src/main/xoo"));
ComponentDto file = componentDbTester.insertComponent(newFileDto(directory, directory, "cdef").setName("Source.xoo")
.setKey("polop:src/main/xoo/Source.xoo")
.setPath(directory.path()));
userSession.addProjectPermission(UserRole.USER, project.getProjectDto())
.registerBranches(project.getMainBranchDto());
init();
executeAndVerify(file.getKey(), "return_bread_crumbs_on_several_levels.json");
}
@Test
public void project_administrator_is_allowed_to_get_information() {
ProjectData project = insertProject();
userSession.addProjectPermission(UserRole.ADMIN, project.getProjectDto())
.registerBranches(project.getMainBranchDto());
init(createPages());
execute(project.projectKey());
}
@Test
public void should_return_private_flag_for_project() {
db.qualityGates().createDefaultQualityGate();
ProjectData project = db.components().insertPrivateProject();
init();
userSession.logIn()
.addProjectPermission(UserRole.ADMIN, project.getProjectDto())
.addPermission(GlobalPermission.ADMINISTER)
.registerBranches(project.getMainBranchDto());
assertJson(execute(project.projectKey())).isSimilarTo("{\"visibility\": \"private\"}");
}
@Test
public void should_return_public_flag_for_project() {
db.qualityGates().createDefaultQualityGate();
ProjectData project = db.components().insertPublicProject();
init();
userSession.logIn()
.addProjectPermission(UserRole.ADMIN, project.getProjectDto())
.registerBranches(project.getMainBranchDto())
.addPermission(GlobalPermission.ADMINISTER);
assertJson(execute(project.projectKey())).isSimilarTo("{\"visibility\": \"public\"}");
}
@Test
public void canApplyPermissionTemplate_is_true_if_logged_in_as_administrator() {
db.qualityGates().createDefaultQualityGate();
ProjectData project = db.components().insertPrivateProject();
init(createPages());
userSession.logIn()
.addProjectPermission(UserRole.ADMIN, project.getProjectDto())
.addPermission(GlobalPermission.ADMINISTER)
.registerBranches(project.getMainBranchDto());
assertJson(execute(project.projectKey())).isSimilarTo("{\"configuration\": {\"canApplyPermissionTemplate\": true}}");
userSession.logIn()
.addProjectPermission(UserRole.ADMIN, project.getProjectDto())
.registerBranches(project.getMainBranchDto());
assertJson(execute(project.projectKey())).isSimilarTo("{\"configuration\": {\"canApplyPermissionTemplate\": false}}");
}
@Test
public void canUpdateProjectVisibilityToPrivate_is_true_if_logged_in_as_project_administrator() {
db.qualityGates().createDefaultQualityGate();
ProjectData project = db.components().insertPublicProject();
init(createPages());
userSession.logIn().addProjectPermission(UserRole.ADMIN, project.getProjectDto())
.registerBranches(project.getMainBranchDto());
assertJson(execute(project.projectKey())).isSimilarTo("{\"configuration\": {\"canUpdateProjectVisibilityToPrivate\": true}}");
}
@Test
public void fail_on_missing_parameters() {
insertProject();
init();
TestRequest request = ws.newRequest();
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void fail_on_unknown_component_key() {
insertProject();
init();
assertThatThrownBy(() -> execute("unknoen"))
.isInstanceOf(NotFoundException.class);
}
@Test
public void throw_ForbiddenException_if_required_permission_is_not_granted() {
ProjectData project = insertProject();
init();
userSession.logIn();
String projectDbKey = project.projectKey();
assertThatThrownBy(() -> execute(projectDbKey))
.isInstanceOf(ForbiddenException.class);
}
@Test
public void test_example_response() {
init(createPages());
ComponentDto mainBranch = newPrivateProjectDto("ABCD")
.setKey("org.codehaus.sonar:sonar")
.setName("Sonarqube")
.setDescription("Open source platform for continuous inspection of code quality");
ProjectData projectData = componentDbTester.insertPrivateProject(mainBranch);
ProjectDto projectDto = projectData.getProjectDto();
SnapshotDto analysis = newAnalysis(mainBranch)
.setCreatedAt(parseDateTime("2016-12-06T11:44:00+0200").getTime())
.setProjectVersion("6.3")
.setLast(true);
componentDbTester.insertSnapshot(analysis);
when(resourceTypes.get(projectDto.getQualifier())).thenReturn(DefaultResourceTypes.get().getRootType());
UserDto user = db.users().insertUser("obiwan");
propertyDbTester.insertProperty(new PropertyDto().setKey("favourite").setEntityUuid(projectDto.getUuid()).setUserUuid(user.getUuid()),
projectDto.getKey(), projectDto.getName(), projectDto.getQualifier(), user.getLogin());
addQualityProfiles(mainBranch,
createQProfile("qp1", "Sonar Way Java", "java"),
createQProfile("qp2", "Sonar Way Xoo", "xoo"));
QualityGateDto qualityGateDto = db.qualityGates().insertQualityGate(qg -> qg.setName("Sonar way"));
db.qualityGates().associateProjectToQualityGate(db.components().getProjectDtoByMainBranch(mainBranch), qualityGateDto);
userSession.logIn(user)
.addProjectPermission(UserRole.USER, projectDto)
.addProjectPermission(UserRole.ADMIN, projectDto)
.registerBranches(projectData.getMainBranchDto());
String result = execute(mainBranch.getKey());
assertJson(result).ignoreFields("snapshotDate", "canBrowseAllChildProjects", "key", "qualityGate.key").isSimilarTo(ws.getDef().responseExampleAsString());
}
@Test
public void definition() {
init();
WebService.Action action = ws.getDef();
assertThat(action.since()).isEqualTo("5.2");
assertThat(action.isPost()).isFalse();
assertThat(action.isInternal()).isTrue();
assertThat(action.description()).isNotNull();
assertThat(action.responseExample()).isNotNull();
assertThat(action.changelog()).extracting(Change::getVersion, Change::getDescription).containsExactlyInAnyOrder(
tuple("6.4", "The 'visibility' field is added"),
tuple("7.3", "The 'almRepoUrl' and 'almId' fields are added"),
tuple("7.6", "The use of module keys in parameter 'component' is deprecated"),
tuple("8.8", "Deprecated parameter 'componentKey' has been removed. Please use parameter 'component' instead"),
tuple("10.1", "The use of module keys in parameter 'component' is removed"));
WebService.Param componentId = action.param(PARAM_COMPONENT);
assertThat(componentId.isRequired()).isFalse();
assertThat(componentId.description()).isNotNull();
assertThat(componentId.exampleValue()).isNotNull();
}
@Test
public void fail_on_directory_key_as_param() {
ProjectData project = insertProject();
ComponentDto directory = componentDbTester.insertComponent(newDirectory(project.getMainBranchComponent(), "src/main/xoo"));
userSession.addProjectPermission(UserRole.USER, project.getProjectDto());
init();
String dirKey = directory.getKey();
assertThatThrownBy(() -> execute(dirKey))
.isInstanceOf(BadRequestException.class);
}
private ProjectData insertProject() {
db.qualityGates().createDefaultQualityGate();
return db.components().insertPrivateProject("project_abcd", c -> c.setKey("polop")
.setUuid("abcd")
.setBranchUuid("abcd")
.setName("Polop")
.setDescription("test project")
.setQualifier(Qualifiers.PROJECT)
.setScope(Scopes.PROJECT));
}
private void init(Page... pages) {
PluginRepository pluginRepository = mock(PluginRepository.class);
when(pluginRepository.hasPlugin(any())).thenReturn(true);
when(pluginRepository.getPluginInfo(any())).thenReturn(new PluginInfo("unused").setVersion(Version.create("1.0")));
CoreExtensionRepository coreExtensionRepository = mock(CoreExtensionRepository.class);
when(coreExtensionRepository.isInstalled(any())).thenReturn(false);
PageRepository pageRepository = new PageRepository(pluginRepository, coreExtensionRepository, new PageDefinition[]{context -> {
for (Page page : pages) {
context.addPage(page);
}
}});
pageRepository.start();
ws = new WsActionTester(
new ComponentAction(dbClient, pageRepository, resourceTypes, userSession, new ComponentFinder(dbClient, resourceTypes),
new QualityGateFinder(dbClient), config));
}
private String execute(String componentKey) {
return ws.newRequest().setParam("component", componentKey).execute().getInput();
}
private void verify(String json, String jsonFile) {
assertJson(json).isSimilarTo(getClass().getResource(ComponentActionIT.class.getSimpleName() + "/" + jsonFile));
}
private void executeAndVerify(String componentKey, String expectedJson) {
verify(execute(componentKey), expectedJson);
}
private void addQualityProfiles(ComponentDto project, QualityProfile... qps) {
MetricDto metric = newMetricDto().setKey(QUALITY_PROFILES_KEY);
dbClient.metricDao().insert(db.getSession(), metric);
dbClient.liveMeasureDao().insert(db.getSession(),
newLiveMeasure(project, metric)
.setData(qualityProfilesToJson(qps)));
db.commit();
}
private Page[] createPages() {
Page page1 = Page.builder("my_plugin/first_page")
.setName("First Page")
.setScope(COMPONENT)
.setComponentQualifiers(Qualifier.PROJECT)
.build();
Page page2 = Page.builder("my_plugin/second_page")
.setName("Second Page")
.setScope(COMPONENT)
.setComponentQualifiers(Qualifier.PROJECT)
.build();
Page adminPage = Page.builder("my_plugin/admin_page")
.setName("Admin Page")
.setScope(COMPONENT)
.setComponentQualifiers(Qualifier.PROJECT)
.setAdmin(true)
.build();
return new Page[]{page1, page2, adminPage};
}
private void verifySuccess(String componentKey) {
String json = execute(componentKey);
assertJson(json).isSimilarTo("{\"key\":\"" + componentKey + "\"}");
}
private static QualityProfile createQProfile(String qpKey, String qpName, String languageKey) {
return new QualityProfile(qpKey, qpName, languageKey, new Date());
}
private static String qualityProfilesToJson(QualityProfile... qps) {
List<QualityProfile> qualityProfiles = Arrays.asList(qps);
return QPMeasureData.toJson(new QPMeasureData(qualityProfiles));
}
}
| 38,108 | 41.915541 | 161 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ui/ws/MarketplaceActionIT.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.ui.ws;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.platform.Server;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Navigation;
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.test.JsonAssert.assertJson;
@RunWith(DataProviderRunner.class)
public class MarketplaceActionIT {
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create();
private final Server server = mock(Server.class);
private final DbClient dbClient = db.getDbClient();
private final MarketplaceAction underTest = new MarketplaceAction(userSessionRule, server, dbClient);
private final WsActionTester ws = new WsActionTester(underTest);
@Test
public void definition() {
WebService.Action def = ws.getDef();
assertThat(def.key()).isEqualTo("marketplace");
assertThat(def.since()).isEqualTo("7.2");
assertThat(def.isPost()).isFalse();
assertThat(def.isInternal()).isTrue();
assertThat(def.description()).isNotEmpty();
assertThat(def.params()).isEmpty();
}
@Test
public void request_fails_if_user_not_logged_in() {
userSessionRule.anonymous();
TestRequest request = ws.newRequest();
assertThatThrownBy(() -> request.execute())
.isInstanceOf(UnauthorizedException.class)
.hasMessageContaining("Authentication is required");
}
@Test
public void request_fails_if_user_is_not_system_administer() {
userSessionRule.logIn();
TestRequest request = ws.newRequest();
assertThatThrownBy(() -> request.execute())
.isInstanceOf(ForbiddenException.class)
.hasMessageContaining("Insufficient privileges");
}
@Test
public void json_example() {
userSessionRule.logIn().setSystemAdministrator();
when(server.getId()).thenReturn("AU-Tpxb--iU5OvuD2FLy");
setNcloc(12345L);
String result = ws.newRequest().execute().getInput();
assertJson(result).isSimilarTo(ws.getDef().responseExampleAsString());
}
@Test
public void returns_server_id_and_nloc() {
userSessionRule.logIn().setSystemAdministrator();
when(server.getId()).thenReturn("myserver");
long ncloc = 256L;
setNcloc(ncloc);
Navigation.MarketplaceResponse expectedResponse = Navigation.MarketplaceResponse.newBuilder()
.setServerId("myserver")
.setNcloc(ncloc)
.build();
Navigation.MarketplaceResponse result = ws.newRequest().executeProtobuf(Navigation.MarketplaceResponse.class);
assertThat(result).isEqualTo(expectedResponse);
}
private void setNcloc(double ncloc) {
ProjectDto project = db.components().insertPublicProject().getProjectDto();
db.getDbClient().projectDao().updateNcloc(db.getSession(), project.getUuid(), (long) ncloc);
db.commit();
}
}
| 4,272 | 33.459677 | 114 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/ui/ws/SettingsActionIT.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.ui.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.web.page.Page;
import org.sonar.api.web.page.PageDefinition;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginRepository;
import org.sonar.process.ProcessProperties;
import org.sonar.core.extension.CoreExtensionRepository;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ui.PageRepository;
import org.sonar.server.ws.WsActionTester;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.test.JsonAssert.assertJson;
public class SettingsActionIT {
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
private MapSettings settings = new MapSettings();
private WsActionTester ws;
@Test
public void empty() {
init();
logInAsSystemAdministrator();
executeAndVerify("empty.json");
}
@Test
public void returns_page_settings() {
init(createPages());
logInAsSystemAdministrator();
executeAndVerify("with_pages.json");
}
@Test
public void returns_update_center_settings() {
init();
settings.setProperty(ProcessProperties.Property.SONAR_UPDATECENTER_ACTIVATE.getKey(), true);
logInAsSystemAdministrator();
executeAndVerify("with_update_center.json");
}
@Test
public void request_succeeds_but_settings_are_not_returned_when_user_is_not_system_administrator() {
init(createPages());
settings.setProperty(ProcessProperties.Property.SONAR_UPDATECENTER_ACTIVATE.getKey(), true);
userSessionRule.logIn().setNonSystemAdministrator();
executeAndVerify("empty.json");
}
private void init(Page... pages) {
PluginRepository pluginRepository = mock(PluginRepository.class);
when(pluginRepository.hasPlugin(any())).thenReturn(true);
when(pluginRepository.getPluginInfo(any())).thenReturn(new PluginInfo("unused"));
CoreExtensionRepository coreExtensionRepository = mock(CoreExtensionRepository.class);
when(coreExtensionRepository.isInstalled(any())).thenReturn(false);
PageRepository pageRepository = new PageRepository(pluginRepository, coreExtensionRepository, new PageDefinition[] {context -> {
for (Page page : pages) {
context.addPage(page);
}
}});
ws = new WsActionTester(new SettingsAction(pageRepository, settings.asConfig(), userSessionRule));
pageRepository.start();
}
private void executeAndVerify(String json) {
assertJson(ws.newRequest().execute().getInput()).isSimilarTo(getClass().getResource("SettingsActionIT/" + json));
}
private Page[] createPages() {
Page firstPage = Page.builder("my_plugin/first_page").setName("First Page").setAdmin(true).build();
Page secondPage = Page.builder("my_plugin/second_page").setName("Second Page").setAdmin(true).build();
return new Page[] {firstPage, secondPage};
}
private void logInAsSystemAdministrator() {
userSessionRule.logIn().setSystemAdministrator();
}
}
| 3,962 | 34.070796 | 132 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/AnonymizeActionIT.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.user.ws;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserQuery;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.user.ExternalIdentity;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER;
public class AnonymizeActionIT {
private final System2 system2 = new AlwaysIncreasingSystem2();
@Rule
public DbTester db = DbTester.create(system2);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final DbClient dbClient = db.getDbClient();
private final UserAnonymizer userAnonymizer = new UserAnonymizer(db.getDbClient());
private final WsActionTester ws = new WsActionTester(new AnonymizeAction(dbClient, userSession, userAnonymizer));
@Test
public void anonymize_user() {
UserDto user = db.users().insertUser(u -> u
.setLogin("ada.lovelace")
.setName("Ada Lovelace")
.setActive(false)
.setEmail(null)
.setScmAccounts(emptyList())
.setExternalIdentityProvider("provider")
.setExternalLogin("external.login")
.setExternalId("external.id"));
logInAsSystemAdministrator();
TestResponse response = anonymize(user.getLogin());
verifyThatUserIsAnonymized(user.getUuid());
assertThat(response.getInput()).isEmpty();
}
@Test
public void cannot_anonymize_active_user() {
createAdminUser();
UserDto user = db.users().insertUser();
userSession.logIn(user.getLogin()).setSystemAdministrator();
String login = user.getLogin();
assertThatThrownBy(() -> anonymize(login))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("User '" + user.getLogin() + "' is not deactivated");
}
@Test
public void requires_to_be_logged_in() {
createAdminUser();
assertThatThrownBy(() -> anonymize("someone"))
.isInstanceOf(UnauthorizedException.class)
.hasMessage("Authentication is required");
}
@Test
public void requires_administrator_permission_on_sonarqube() {
createAdminUser();
userSession.logIn();
assertThatThrownBy(() -> anonymize("someone"))
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void fail_if_user_does_not_exist() {
createAdminUser();
logInAsSystemAdministrator();
assertThatThrownBy(() -> anonymize("someone"))
.isInstanceOf(NotFoundException.class)
.hasMessage("User 'someone' doesn't exist");
}
@Test
public void fail_if_login_is_blank() {
createAdminUser();
logInAsSystemAdministrator();
assertThatThrownBy(() -> anonymize(""))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The 'login' parameter is missing");
}
@Test
public void fail_if_login_is_missing() {
createAdminUser();
logInAsSystemAdministrator();
assertThatThrownBy(() -> anonymize(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The 'login' parameter is missing");
}
@Test
public void test_definition() {
assertThat(ws.getDef().isPost()).isTrue();
assertThat(ws.getDef().isInternal()).isFalse();
assertThat(ws.getDef().params()).hasSize(1);
}
private void logInAsSystemAdministrator() {
userSession.logIn().setSystemAdministrator();
}
private TestResponse anonymize(@Nullable String login) {
return anonymize(ws, login);
}
private TestResponse anonymize(WsActionTester ws, @Nullable String login) {
TestRequest request = ws.newRequest()
.setMethod("POST");
Optional.ofNullable(login).ifPresent(t -> request.setParam("login", login));
return request.execute();
}
private void verifyThatUserIsAnonymized(String uuid) {
List<UserDto> users = dbClient.userDao().selectUsers(db.getSession(), UserQuery.builder().isActive(false).build());
assertThat(users).hasSize(1);
UserDto anonymized = dbClient.userDao().selectByUuid(db.getSession(), uuid);
assertThat(anonymized.getLogin()).startsWith("sq-removed-");
assertThat(anonymized.getName()).isEqualTo(anonymized.getLogin());
assertThat(anonymized.getExternalLogin()).isEqualTo(anonymized.getLogin());
assertThat(anonymized.getExternalId()).isEqualTo(anonymized.getLogin());
assertThat(anonymized.getExternalIdentityProvider()).isEqualTo(ExternalIdentity.SQ_AUTHORITY);
assertThat(anonymized.isActive()).isFalse();
}
private UserDto createAdminUser() {
UserDto admin = db.users().insertUser();
db.users().insertGlobalPermissionOnUser(admin, ADMINISTER);
db.commit();
return admin;
}
}
| 6,175 | 33.121547 | 119 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/ChangePasswordActionIT.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.user.ws;
import java.io.IOException;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.server.http.HttpResponse;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.FilterChain;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.audit.NoOpAuditPersister;
import org.sonar.db.user.SessionTokenDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.authentication.CredentialsLocalAuthentication;
import org.sonar.server.authentication.JwtHttpHandler;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.user.NewUserNotifier;
import org.sonar.server.user.UserUpdater;
import org.sonar.server.usergroups.DefaultGroupFinder;
import org.sonar.server.ws.ServletFilterHandler;
import static java.lang.String.format;
import static java.net.HttpURLConnection.HTTP_BAD_REQUEST;
import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
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.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_LOGIN;
import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_PASSWORD;
import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_PREVIOUS_PASSWORD;
public class ChangePasswordActionIT {
private static final String OLD_PASSWORD = "1234";
private static final String NEW_PASSWORD = "12345";
@Rule
public DbTester db = DbTester.create();
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone().logIn();
private final ArgumentCaptor<UserDto> userDtoCaptor = ArgumentCaptor.forClass(UserDto.class);
private final HttpRequest request = mock(HttpRequest.class);
private final HttpResponse response = mock(HttpResponse.class);
private final FilterChain chain = mock(FilterChain.class);
private final MapSettings settings = new MapSettings().setProperty("sonar.internal.pbkdf2.iterations", "1");
private final CredentialsLocalAuthentication localAuthentication = new CredentialsLocalAuthentication(db.getDbClient(), settings.asConfig());
private final UserUpdater userUpdater = new UserUpdater(mock(NewUserNotifier.class), db.getDbClient(),
new DefaultGroupFinder(db.getDbClient()),
new MapSettings().asConfig(), new NoOpAuditPersister(), localAuthentication);
private final JwtHttpHandler jwtHttpHandler = mock(JwtHttpHandler.class);
private final ChangePasswordAction underTest = new ChangePasswordAction(db.getDbClient(), userUpdater, userSessionRule, localAuthentication, jwtHttpHandler);
private ServletOutputStream responseOutputStream;
@Before
public void setUp() throws IOException {
db.users().insertDefaultGroup();
responseOutputStream = new StringOutputStream();
doReturn(responseOutputStream).when(response).getOutputStream();
}
@Test
public void a_user_can_update_his_password() {
UserTestData user = createLocalUser(OLD_PASSWORD);
String oldCryptedPassword = findEncryptedPassword(user.getLogin());
userSessionRule.logIn(user.userDto());
executeTest(user.getLogin(), OLD_PASSWORD, NEW_PASSWORD);
String newCryptedPassword = findEncryptedPassword(user.getLogin());
assertThat(newCryptedPassword).isNotEqualTo(oldCryptedPassword);
verify(jwtHttpHandler).removeToken(request, response);
verify(jwtHttpHandler).generateToken(userDtoCaptor.capture(), eq(request), eq(response));
assertThat(findSessionTokenDto(db.getSession(), user.getSessionTokenUuid())).isEmpty();
assertThat(userDtoCaptor.getValue().getLogin()).isEqualTo(user.getLogin());
verify(response).setStatus(HTTP_NO_CONTENT);
}
@Test
public void system_administrator_can_update_password_of_user() {
UserTestData admin = createLocalUser();
userSessionRule.logIn(admin.userDto()).setSystemAdministrator();
UserTestData user = createLocalUser();
String originalPassword = findEncryptedPassword(user.getLogin());
db.commit();
executeTest(user.getLogin(), null, NEW_PASSWORD);
String newPassword = findEncryptedPassword(user.getLogin());
assertThat(newPassword).isNotEqualTo(originalPassword);
assertThat(findSessionTokenDto(db.getSession(), user.getSessionTokenUuid())).isEmpty();
assertThat(findSessionTokenDto(db.getSession(), admin.getSessionTokenUuid())).isPresent();
verifyNoInteractions(jwtHttpHandler);
verify(response).setStatus(HTTP_NO_CONTENT);
}
private String findEncryptedPassword(String login) {
return db.getDbClient().userDao().selectByLogin(db.getSession(), login).getCryptedPassword();
}
private Optional<SessionTokenDto> findSessionTokenDto(DbSession dbSession, String tokenUuid) {
return db.getDbClient().sessionTokensDao().selectByUuid(dbSession, tokenUuid);
}
@Test
public void fail_to_update_someone_else_password_if_not_admin() {
UserTestData user = createLocalUser();
userSessionRule.logIn(user.getLogin());
UserTestData anotherLocalUser = createLocalUser();
String anotherLocalUserLogin = anotherLocalUser.getLogin();
assertThatThrownBy(() -> executeTest(anotherLocalUserLogin, "I dunno", NEW_PASSWORD))
.isInstanceOf(ForbiddenException.class);
verifyNoInteractions(jwtHttpHandler);
assertThat(findSessionTokenDto(db.getSession(), user.getSessionTokenUuid())).isPresent();
verifyNoInteractions(jwtHttpHandler);
}
@Test
public void fail_to_update_someone_else_password_if_not_admin_and_user_doesnt_exist() {
UserTestData user = createLocalUser();
userSessionRule.logIn(user.getLogin());
assertThatThrownBy(() -> executeTest("unknown", "I dunno", NEW_PASSWORD))
.isInstanceOf(ForbiddenException.class);
verifyNoInteractions(jwtHttpHandler);
assertThat(findSessionTokenDto(db.getSession(), user.getSessionTokenUuid())).isPresent();
verifyNoInteractions(jwtHttpHandler);
}
@Test
public void fail_to_update_unknown_user() {
UserTestData admin = createLocalUser();
userSessionRule.logIn(admin.userDto()).setSystemAdministrator();
assertThatThrownBy(() -> executeTest("polop", null, "polop"))
.isInstanceOf(NotFoundException.class)
.hasMessage("User with login 'polop' has not been found");
assertThat(findSessionTokenDto(db.getSession(), admin.getSessionTokenUuid())).isPresent();
verifyNoInteractions(jwtHttpHandler);
}
@Test
public void fail_on_disabled_user() {
UserDto user = db.users().insertUser(u -> u.setActive(false));
userSessionRule.logIn(user);
String userLogin = user.getLogin();
assertThatThrownBy(() -> executeTest(userLogin, null, "polop"))
.isInstanceOf(NotFoundException.class)
.hasMessage(format("User with login '%s' has not been found", userLogin));
verifyNoInteractions(jwtHttpHandler);
}
@Test
public void fail_to_update_password_on_self_without_login() {
when(request.getParameter(PARAM_PASSWORD)).thenReturn("new password");
when(request.getParameter(PARAM_PREVIOUS_PASSWORD)).thenReturn(NEW_PASSWORD);
executeTest(null, OLD_PASSWORD, NEW_PASSWORD);
verify(response).setStatus(HTTP_BAD_REQUEST);
assertThat(responseOutputStream).hasToString("{\"result\":\"The 'login' parameter is missing\"}");
verifyNoInteractions(jwtHttpHandler);
}
@Test
public void fail_to_update_password_on_self_without_old_password() {
UserTestData user = createLocalUser();
userSessionRule.logIn(user.userDto());
executeTest(user.getLogin(), null, NEW_PASSWORD);
verify(response).setStatus(HTTP_BAD_REQUEST);
assertThat(responseOutputStream).hasToString("{\"result\":\"The 'previousPassword' parameter is missing\"}");
assertThat(findSessionTokenDto(db.getSession(), user.getSessionTokenUuid())).isPresent();
verifyNoInteractions(jwtHttpHandler);
}
@Test
public void fail_to_update_password_on_self_without_new_password() {
UserTestData user = createLocalUser();
userSessionRule.logIn(user.userDto());
executeTest(user.getLogin(), OLD_PASSWORD, null);
verify(response).setStatus(HTTP_BAD_REQUEST);
assertThat(responseOutputStream).hasToString("{\"result\":\"The 'password' parameter is missing\"}");
assertThat(findSessionTokenDto(db.getSession(), user.getSessionTokenUuid())).isPresent();
assertThat(findSessionTokenDto(db.getSession(), user.getSessionTokenUuid())).isPresent();
verifyNoInteractions(jwtHttpHandler);
}
@Test
public void fail_to_update_password_on_self_with_bad_old_password() {
UserTestData user = createLocalUser();
userSessionRule.logIn(user.userDto());
executeTest(user.getLogin(), "I dunno", NEW_PASSWORD);
verify(response).setStatus(HTTP_BAD_REQUEST);
assertThat(responseOutputStream).hasToString("{\"result\":\"old_password_incorrect\"}");
assertThat(findSessionTokenDto(db.getSession(), user.getSessionTokenUuid())).isPresent();
verifyNoInteractions(jwtHttpHandler);
}
@Test
public void fail_to_update_password_on_external_auth() {
UserDto admin = db.users().insertUser();
userSessionRule.logIn(admin).setSystemAdministrator();
UserDto user = db.users().insertUser(u -> u.setLocal(false));
executeTest(user.getLogin(), "I dunno", NEW_PASSWORD);
verify(response).setStatus(HTTP_BAD_REQUEST);
}
@Test
public void fail_to_update_to_same_password() {
UserTestData user = createLocalUser(OLD_PASSWORD);
userSessionRule.logIn(user.userDto());
executeTest(user.getLogin(), OLD_PASSWORD, OLD_PASSWORD);
verify(response).setStatus(HTTP_BAD_REQUEST);
assertThat(responseOutputStream).hasToString("{\"result\":\"new_password_same_as_old\"}");
assertThat(findSessionTokenDto(db.getSession(), user.getSessionTokenUuid())).isPresent();
verifyNoInteractions(jwtHttpHandler);
}
@Test
public void verify_definition() {
String controllerKey = "foo";
WebService.Context context = new WebService.Context();
WebService.NewController newController = context.createController(controllerKey);
underTest.define(newController);
newController.done();
WebService.Action changePassword = context.controller(controllerKey).action("change_password");
assertThat(changePassword).isNotNull();
assertThat(changePassword.handler()).isInstanceOf(ServletFilterHandler.class);
assertThat(changePassword.isPost()).isTrue();
assertThat(changePassword.params())
.extracting(WebService.Param::key)
.containsExactlyInAnyOrder(PARAM_LOGIN, PARAM_PASSWORD, PARAM_PREVIOUS_PASSWORD);
}
private void executeTest(@Nullable String login, @Nullable String oldPassword, @Nullable String newPassword) {
when(request.getParameter(PARAM_LOGIN)).thenReturn(login);
when(request.getParameter(PARAM_PREVIOUS_PASSWORD)).thenReturn(oldPassword);
when(request.getParameter(PARAM_PASSWORD)).thenReturn(newPassword);
underTest.doFilter(request, response, chain);
}
private UserTestData createLocalUser(String password) {
UserTestData userTestData = createLocalUser();
localAuthentication.storeHashPassword(userTestData.userDto(), password);
db.getDbClient().userDao().update(db.getSession(), userTestData.userDto());
db.commit();
return userTestData;
}
private UserTestData createLocalUser() {
UserDto userDto = db.users().insertUser(u -> u.setLocal(true));
SessionTokenDto sessionTokenForUser = createSessionTokenForUser(userDto);
db.commit();
return new UserTestData(userDto, sessionTokenForUser);
}
private SessionTokenDto createSessionTokenForUser(UserDto user) {
SessionTokenDto userTokenDto = new SessionTokenDto().setUserUuid(user.getUuid()).setExpirationDate(1000L);
return db.getDbClient().sessionTokensDao().insert(db.getSession(), userTokenDto);
}
private record UserTestData(UserDto userDto, SessionTokenDto sessionTokenDto) {
String getLogin() {
return userDto.getLogin();
}
String getSessionTokenUuid() {
return sessionTokenDto.getUuid();
}
}
static class StringOutputStream extends ServletOutputStream {
private final StringBuilder buf = new StringBuilder();
StringOutputStream() {
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setWriteListener(WriteListener listener) {
}
public void write(byte[] b) {
this.buf.append(new String(b));
}
public void write(byte[] b, int off, int len) {
this.buf.append(new String(b, off, len));
}
public void write(int b) {
byte[] bytes = new byte[] {(byte) b};
this.buf.append(new String(bytes));
}
public String toString() {
return this.buf.toString();
}
}
}
| 14,235 | 38.988764 | 159 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/CreateActionIT.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.user.ws;
import java.util.List;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.audit.NoOpAuditPersister;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.authentication.CredentialsLocalAuthentication;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.management.ManagedInstanceChecker;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.user.NewUserNotifier;
import org.sonar.server.user.UserUpdater;
import org.sonar.server.user.ws.CreateAction.CreateRequest;
import org.sonar.server.usergroups.DefaultGroupFinder;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Users.CreateWsResponse;
import org.sonarqube.ws.Users.CreateWsResponse.User;
import static java.lang.String.format;
import static java.util.Collections.singletonList;
import static java.util.Optional.ofNullable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
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.sonar.db.user.UserTesting.newUserDto;
public class CreateActionIT {
private final MapSettings settings = new MapSettings().setProperty("sonar.internal.pbkdf2.iterations", "1");
private final System2 system2 = new AlwaysIncreasingSystem2();
@Rule
public DbTester db = DbTester.create(system2);
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
private GroupDto defaultGroup;
private final CredentialsLocalAuthentication localAuthentication = new CredentialsLocalAuthentication(db.getDbClient(), settings.asConfig());
private final ManagedInstanceChecker managedInstanceChecker = mock(ManagedInstanceChecker.class);
private final WsActionTester tester = new WsActionTester(new CreateAction(db.getDbClient(), new UserUpdater(mock(NewUserNotifier.class),
db.getDbClient(), new DefaultGroupFinder(db.getDbClient()), settings.asConfig(), new NoOpAuditPersister(), localAuthentication), userSessionRule, managedInstanceChecker));
@Before
public void setUp() {
defaultGroup = db.users().insertDefaultGroup();
}
@Test
public void create_user() {
logInAsSystemAdministrator();
CreateWsResponse response = call(CreateRequest.builder()
.setLogin("john")
.setName("John")
.setEmail("john@email.com")
.setScmAccounts(singletonList("jn"))
.setPassword("1234")
.build());
assertThat(response.getUser())
.extracting(User::getLogin, User::getName, User::getEmail, User::getScmAccountsList, User::getLocal)
.containsOnly("john", "John", "john@email.com", singletonList("jn"), true);
// exists in db
Optional<UserDto> dbUser = db.users().selectUserByLogin("john");
assertThat(dbUser).isPresent();
// member of default group
assertThat(db.users().selectGroupUuidsOfUser(dbUser.get())).containsOnly(defaultGroup.getUuid());
}
@Test
public void create_local_user() {
logInAsSystemAdministrator();
call(CreateRequest.builder()
.setLogin("john")
.setName("John")
.setPassword("1234")
.setLocal(true)
.build());
assertThat(db.users().selectUserByLogin("john").get())
.extracting(UserDto::isLocal, UserDto::getExternalIdentityProvider, UserDto::getExternalLogin)
.containsOnly(true, "sonarqube", "john");
}
@Test
public void create_none_local_user() {
logInAsSystemAdministrator();
call(CreateRequest.builder()
.setLogin("john")
.setName("John")
.setLocal(false)
.build());
assertThat(db.users().selectUserByLogin("john").get())
.extracting(UserDto::isLocal, UserDto::getExternalIdentityProvider, UserDto::getExternalLogin)
.containsOnly(false, "sonarqube", "john");
}
@Test
public void create_user_with_comma_in_scm_account() {
logInAsSystemAdministrator();
CreateWsResponse response = call(CreateRequest.builder()
.setLogin("john")
.setName("John")
.setEmail("john@email.com")
.setScmAccounts(singletonList("j,n"))
.setPassword("1234")
.build());
assertThat(response.getUser().getScmAccountsList()).containsOnly("j,n");
}
@Test
public void fail_when_whitespace_characters_in_scm_account_values() {
logInAsSystemAdministrator();
assertThatThrownBy(() -> {
call(CreateRequest.builder()
.setLogin("john")
.setName("John")
.setEmail("john@email.com")
.setScmAccounts(List.of("admin", " admin "))
.setPassword("1234")
.build());
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("SCM account cannot start or end with whitespace: ' admin '");
}
@Test
public void fail_when_duplicates_characters_in_scm_account_values() {
logInAsSystemAdministrator();
assertThatThrownBy(() -> {
call(CreateRequest.builder()
.setLogin("john")
.setName("John")
.setEmail("john@email.com")
.setScmAccounts(List.of("admin", "admin"))
.setPassword("1234")
.build());
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Duplicate SCM account: 'admin'");
}
@Test
public void create_user_with_empty_email() {
logInAsSystemAdministrator();
call(CreateRequest.builder()
.setLogin("john")
.setName("John")
.setPassword("1234")
.setEmail("")
.build());
assertThat(db.users().selectUserByLogin("john").get())
.extracting(UserDto::getExternalLogin)
.isEqualTo("john");
}
@Test
public void reactivate_user() {
logInAsSystemAdministrator();
db.users().insertUser(newUserDto("john", "John", "john@email.com").setActive(false));
call(CreateRequest.builder()
.setLogin("john")
.setName("John")
.setEmail("john@email.com")
.setScmAccounts(singletonList("jn"))
.setPassword("1234")
.build());
assertThat(db.users().selectUserByLogin("john").get().isActive()).isTrue();
}
@Test
public void fail_to_reactivate_user_when_active_user_exists() {
logInAsSystemAdministrator();
UserDto user = db.users().insertUser();
assertThatThrownBy(() -> {
call(CreateRequest.builder()
.setLogin(user.getLogin())
.setName("John")
.setPassword("1234")
.build());
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(format("An active user with login '%s' already exists", user.getLogin()));
}
@Test
public void fail_when_missing_login() {
logInAsSystemAdministrator();
assertThatThrownBy(() -> {
call(CreateRequest.builder()
.setLogin(null)
.setName("John")
.setPassword("1234")
.build());
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Login is mandatory and must not be empty");
}
@Test
public void fail_when_login_is_too_short() {
logInAsSystemAdministrator();
assertThatThrownBy(() -> {
call(CreateRequest.builder()
.setLogin("a")
.setName("John")
.setPassword("1234")
.build());
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("'login' length (1) is shorter than the minimum authorized (2)");
}
@Test
public void fail_when_missing_name() {
logInAsSystemAdministrator();
assertThatThrownBy(() -> {
call(CreateRequest.builder()
.setLogin("john")
.setName(null)
.setPassword("1234")
.build());
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Name is mandatory and must not be empty");
}
@Test
public void fail_when_missing_password() {
logInAsSystemAdministrator();
assertThatThrownBy(() -> {
call(CreateRequest.builder()
.setLogin("john")
.setName("John")
.setPassword(null)
.build());
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Password is mandatory and must not be empty");
}
@Test
public void fail_when_password_is_set_on_none_local_user() {
logInAsSystemAdministrator();
TestRequest request =tester.newRequest()
.setParam("login","john")
.setParam("name","John")
.setParam("password", "1234")
.setParam("local", "false");
assertThatThrownBy(() -> {
request.execute();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Password should only be set on local user");
}
@Test
public void fail_when_email_is_invalid() {
logInAsSystemAdministrator();
CreateRequest request = CreateRequest.builder()
.setLogin("pipo")
.setName("John")
.setPassword("1234")
.setEmail("invalid-email")
.build();
assertThatThrownBy(() -> {
call(request);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Email 'invalid-email' is not valid");
}
@Test
public void throw_ForbiddenException_if_not_system_administrator() {
userSessionRule.logIn().setNonSystemAdministrator();
assertThatThrownBy(() -> executeRequest("john"))
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void handle_whenInstanceManaged_shouldThrowBadRequestException() {
BadRequestException badRequestException = BadRequestException.create("message");
doThrow(badRequestException).when(managedInstanceChecker).throwIfInstanceIsManaged();
logInAsSystemAdministrator();
CreateRequest request = CreateRequest.builder()
.setLogin("pipo")
.setName("John")
.setPassword("1234")
.build();
assertThatThrownBy(() -> call(request))
.isEqualTo(badRequestException);
}
@Test
public void handle_whenInstanceManagedAndNotSystemAdministrator_shouldThrowUnauthorizedException() {
CreateRequest request = CreateRequest.builder()
.setLogin("pipo")
.setName("John")
.setPassword("1234")
.build();
assertThatThrownBy(() -> call(request))
.isInstanceOf(UnauthorizedException.class)
.hasMessage("Authentication is required");
verify(managedInstanceChecker, never()).throwIfInstanceIsManaged();
}
@Test
public void test_definition() {
WebService.Action action = tester.getDef();
assertThat(action).isNotNull();
assertThat(action.isPost()).isTrue();
assertThat(action.params()).hasSize(6);
}
private CreateWsResponse executeRequest(String login) {
return call(CreateRequest.builder()
.setLogin(login)
.setName("name of " + login)
.setEmail(login + "@email.com")
.setScmAccounts(singletonList(login.substring(0, 2)))
.setPassword("pwd_" + login)
.build());
}
private void logInAsSystemAdministrator() {
userSessionRule.logIn().setSystemAdministrator();
}
private CreateWsResponse call(CreateRequest createRequest) {
TestRequest request = tester.newRequest();
ofNullable(createRequest.getLogin()).ifPresent(e4 -> request.setParam("login", e4));
ofNullable(createRequest.getName()).ifPresent(e3 -> request.setParam("name", e3));
ofNullable(createRequest.getEmail()).ifPresent(e2 -> request.setParam("email", e2));
ofNullable(createRequest.getPassword()).ifPresent(e1 -> request.setParam("password", e1));
ofNullable(createRequest.getScmAccounts()).ifPresent(e -> request.setMultiParam("scmAccount", e));
request.setParam("local", Boolean.toString(createRequest.isLocal()));
return request.executeProtobuf(CreateWsResponse.class);
}
}
| 13,021 | 31.153086 | 175 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/CurrentActionHomepageIT.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.user.ws;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Optional;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.ResourceType;
import org.sonar.api.resources.ResourceTypeTree;
import org.sonar.api.resources.ResourceTypes;
import org.sonar.api.utils.System2;
import org.sonar.core.platform.EditionProvider;
import org.sonar.core.platform.PlatformEditionProvider;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ProjectData;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.AvatarResolverImpl;
import org.sonar.server.permission.PermissionService;
import org.sonar.server.permission.PermissionServiceImpl;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Users.CurrentWsResponse;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
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.web.UserRole.USER;
import static org.sonarqube.ws.Users.CurrentWsResponse.HomepageType.PROJECTS;
@RunWith(DataProviderRunner.class)
public class CurrentActionHomepageIT {
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private final DbClient dbClient = db.getDbClient();
private final PlatformEditionProvider platformEditionProvider = mock(PlatformEditionProvider.class);
private final HomepageTypesImpl homepageTypes = new HomepageTypesImpl();
private final PermissionService permissionService = new PermissionServiceImpl(new ResourceTypes(new ResourceTypeTree[] {
ResourceTypeTree.builder().addType(ResourceType.builder(Qualifiers.PROJECT).build()).build()}));
private final WsActionTester ws = new WsActionTester(
new CurrentAction(userSessionRule, dbClient, new AvatarResolverImpl(), homepageTypes, platformEditionProvider, permissionService));
@Test
public void return_homepage_when_set_to_portfolios() {
UserDto user = db.users().insertUser(u -> u.setHomepageType("PORTFOLIOS"));
userSessionRule.logIn(user);
CurrentWsResponse response = call();
assertThat(response.getHomepage())
.extracting(CurrentWsResponse.Homepage::getType)
.isEqualTo(CurrentWsResponse.HomepageType.PORTFOLIOS);
}
@Test
@UseDataProvider("enterpriseAndAbove")
public void return_homepage_when_set_to_a_portfolio(EditionProvider.Edition edition) {
setPlatformEdition(edition);
ComponentDto portfolio = db.components().insertPrivatePortfolio();
UserDto user = db.users().insertUser(u -> u.setHomepageType("PORTFOLIO").setHomepageParameter(portfolio.uuid()));
userSessionRule.logIn(user).addProjectPermission(USER, portfolio);
CurrentWsResponse response = call();
assertThat(response.getHomepage())
.extracting(CurrentWsResponse.Homepage::getType, CurrentWsResponse.Homepage::getComponent)
.containsExactly(CurrentWsResponse.HomepageType.PORTFOLIO, portfolio.getKey());
}
@Test
@UseDataProvider("enterpriseAndAbove")
public void return_default_when_set_to_a_portfolio_but_no_rights_on_this_portfolio(EditionProvider.Edition edition) {
setPlatformEdition(edition);
ComponentDto portfolio = db.components().insertPrivatePortfolio();
UserDto user = db.users().insertUser(u -> u.setHomepageType("PORTFOLIO").setHomepageParameter(portfolio.uuid()));
userSessionRule.logIn(user);
CurrentWsResponse response = call();
assertThat(response.getHomepage())
.extracting(CurrentWsResponse.Homepage::getType)
.isEqualTo(PROJECTS);
}
@Test
@UseDataProvider("enterpriseAndAbove")
public void return_homepage_when_set_to_an_application(EditionProvider.Edition edition) {
setPlatformEdition(edition);
ComponentDto application = db.components().insertPrivateApplication().getMainBranchComponent();
UserDto user = db.users().insertUser(u -> u.setHomepageType("APPLICATION").setHomepageParameter(application.uuid()));
userSessionRule.logIn(user).addProjectPermission(USER, application);
CurrentWsResponse response = call();
assertThat(response.getHomepage())
.extracting(CurrentWsResponse.Homepage::getType, CurrentWsResponse.Homepage::getComponent)
.containsExactly(CurrentWsResponse.HomepageType.APPLICATION, application.getKey());
}
@Test
@UseDataProvider("enterpriseAndAbove")
public void return_default_homepage_when_set_to_an_application_but_no_rights_on_this_application(EditionProvider.Edition edition) {
setPlatformEdition(edition);
ComponentDto application = db.components().insertPrivateApplication().getMainBranchComponent();
UserDto user = db.users().insertUser(u -> u.setHomepageType("APPLICATION").setHomepageParameter(application.uuid()));
userSessionRule.logIn(user);
CurrentWsResponse response = call();
assertThat(response.getHomepage())
.extracting(CurrentWsResponse.Homepage::getType)
.isEqualTo(PROJECTS);
}
@Test
@UseDataProvider("allEditions")
public void return_homepage_when_set_to_a_project(EditionProvider.Edition edition) {
setPlatformEdition(edition);
ProjectData projectData = db.components().insertPrivateProject();
ComponentDto mainBranch = projectData.getMainBranchComponent();
UserDto user = db.users().insertUser(u -> u.setHomepageType("PROJECT").setHomepageParameter(mainBranch.uuid()));
userSessionRule.logIn(user).addProjectPermission(USER, projectData.getProjectDto());
CurrentWsResponse response = call();
assertThat(response.getHomepage())
.extracting(CurrentWsResponse.Homepage::getType, CurrentWsResponse.Homepage::getComponent)
.containsExactly(CurrentWsResponse.HomepageType.PROJECT, mainBranch.getKey());
}
@Test
@UseDataProvider("allEditions")
public void return_default_homepage_when_set_to_a_project_but_no_rights_on_this_project(EditionProvider.Edition edition) {
setPlatformEdition(edition);
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
UserDto user = db.users().insertUser(u -> u.setHomepageType("PROJECT").setHomepageParameter(project.uuid()));
userSessionRule.logIn(user);
CurrentWsResponse response = call();
assertThat(response.getHomepage())
.extracting(CurrentWsResponse.Homepage::getType)
.isEqualTo(PROJECTS);
}
@Test
public void return_homepage_when_set_to_a_branch() {
ProjectData projectData = db.components().insertPrivateProject();
ComponentDto project = projectData.getMainBranchComponent();
String branchName = randomAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchName));
UserDto user = db.users().insertUser(u -> u.setHomepageType("PROJECT").setHomepageParameter(branch.uuid()));
userSessionRule.logIn(user).addProjectPermission(USER, projectData.getProjectDto());
CurrentWsResponse response = call();
assertThat(response.getHomepage())
.extracting(CurrentWsResponse.Homepage::getType, CurrentWsResponse.Homepage::getComponent, CurrentWsResponse.Homepage::getBranch)
.containsExactly(CurrentWsResponse.HomepageType.PROJECT, branch.getKey(), branchName);
}
@Test
public void fallback_when_user_homepage_project_does_not_exist_in_db() {
UserDto user = db.users().insertUser(u -> u.setHomepageType("PROJECT").setHomepageParameter("not-existing-project-uuid"));
userSessionRule.logIn(user.getLogin());
CurrentWsResponse response = ws.newRequest().executeProtobuf(CurrentWsResponse.class);
assertThat(response.getHomepage()).isNotNull();
}
@Test
@UseDataProvider("enterpriseAndAbove")
public void fallback_when_user_homepage_portfolio_does_not_exist_in_db(EditionProvider.Edition edition) {
setPlatformEdition(edition);
UserDto user = db.users().insertUser(u -> u.setHomepageType("PORTFOLIO").setHomepageParameter("not-existing-portfolio-uuid"));
userSessionRule.logIn(user.getLogin());
CurrentWsResponse response = ws.newRequest().executeProtobuf(CurrentWsResponse.class);
assertThat(response.getHomepage()).isNotNull();
}
@Test
public void fallback_when_edition_is_null() {
setPlatformEdition(null);
ComponentDto application = db.components().insertPrivateApplication().getMainBranchComponent();
UserDto user = db.users().insertUser(u -> u.setHomepageType("APPLICATION").setHomepageParameter(application.uuid()));
userSessionRule.logIn(user.getLogin());
CurrentWsResponse response = ws.newRequest().executeProtobuf(CurrentWsResponse.class);
assertThat(response.getHomepage()).isNotNull();
assertThat(response.getHomepage().getType()).isEqualTo(PROJECTS);
}
@Test
@UseDataProvider("enterpriseAndAbove")
public void fallback_when_user_homepage_application_does_not_exist_in_db(EditionProvider.Edition edition) {
setPlatformEdition(edition);
UserDto user = db.users().insertUser(u -> u.setHomepageType("APPLICATION").setHomepageParameter("not-existing-application-uuid"));
userSessionRule.logIn(user.getLogin());
CurrentWsResponse response = ws.newRequest().executeProtobuf(CurrentWsResponse.class);
assertThat(response.getHomepage()).isNotNull();
}
@Test
@UseDataProvider("belowEnterprise")
public void fallback_when_user_homepage_application_and_edition_below_enterprise(EditionProvider.Edition edition) {
setPlatformEdition(edition);
ComponentDto application = db.components().insertPrivateApplication().getMainBranchComponent();
UserDto user = db.users().insertUser(u -> u.setHomepageType("APPLICATION").setHomepageParameter(application.uuid()));
userSessionRule.logIn(user.getLogin());
CurrentWsResponse response = ws.newRequest().executeProtobuf(CurrentWsResponse.class);
assertThat(response.getHomepage().getType()).hasToString("PROJECTS");
}
@Test
public void fallback_to_PROJECTS() {
UserDto user = db.users().insertUser(u -> u.setHomepageType("PROJECT").setHomepageParameter("not-existing-project-uuid"));
userSessionRule.logIn(user.getLogin());
CurrentWsResponse response = ws.newRequest().executeProtobuf(CurrentWsResponse.class);
assertThat(response.getHomepage().getType()).hasToString("PROJECTS");
}
private CurrentWsResponse call() {
return ws.newRequest().executeProtobuf(CurrentWsResponse.class);
}
private void setPlatformEdition(@Nullable EditionProvider.Edition edition) {
when(platformEditionProvider.get()).thenReturn(Optional.ofNullable(edition));
}
@DataProvider
public static Object[][] enterpriseAndAbove() {
return new Object[][] {
{EditionProvider.Edition.ENTERPRISE},
{EditionProvider.Edition.DATACENTER}
};
}
@DataProvider
public static Object[][] belowEnterprise() {
return new Object[][] {
{EditionProvider.Edition.COMMUNITY},
{EditionProvider.Edition.DEVELOPER}
};
}
@DataProvider
public static Object[][] allEditions() {
return new Object[][] {
{EditionProvider.Edition.COMMUNITY},
{EditionProvider.Edition.DEVELOPER},
{EditionProvider.Edition.ENTERPRISE},
{EditionProvider.Edition.DATACENTER}
};
}
}
| 12,493 | 41.352542 | 135 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/CurrentActionIT.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.user.ws;
import java.util.Map;
import org.assertj.core.groups.Tuple;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.ResourceType;
import org.sonar.api.resources.ResourceTypeTree;
import org.sonar.api.resources.ResourceTypes;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.core.platform.PlatformEditionProvider;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.property.PropertyDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.AvatarResolverImpl;
import org.sonar.server.permission.PermissionService;
import org.sonar.server.permission.PermissionServiceImpl;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Users.CurrentWsResponse;
import static com.google.common.collect.Lists.newArrayList;
import static java.util.Collections.emptyList;
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.sonar.api.web.UserRole.USER;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS;
import static org.sonar.db.permission.GlobalPermission.SCAN;
import static org.sonar.db.user.GroupTesting.newGroupDto;
import static org.sonar.test.JsonAssert.assertJson;
public class CurrentActionIT {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private final PlatformEditionProvider platformEditionProvider = mock(PlatformEditionProvider.class);
private final HomepageTypesImpl homepageTypes = new HomepageTypesImpl();
private final PermissionService permissionService = new PermissionServiceImpl(new ResourceTypes(new ResourceTypeTree[] {
ResourceTypeTree.builder().addType(ResourceType.builder(Qualifiers.PROJECT).build()).build()}));
private final WsActionTester ws = new WsActionTester(
new CurrentAction(userSession, db.getDbClient(), new AvatarResolverImpl(), homepageTypes, platformEditionProvider, permissionService));
@Test
public void return_user_info() {
UserDto user = db.users().insertUser(u -> u
.setLogin("obiwan.kenobi")
.setName("Obiwan Kenobi")
.setEmail("obiwan.kenobi@starwars.com")
.setLocal(true)
.setExternalLogin("obiwan")
.setExternalIdentityProvider("sonarqube")
.setScmAccounts(newArrayList("obiwan:github", "obiwan:bitbucket")));
userSession.logIn(user);
CurrentWsResponse response = call();
assertThat(response)
.extracting(CurrentWsResponse::getIsLoggedIn, CurrentWsResponse::getLogin, CurrentWsResponse::getName, CurrentWsResponse::getEmail, CurrentWsResponse::getAvatar,
CurrentWsResponse::getLocal,
CurrentWsResponse::getExternalIdentity, CurrentWsResponse::getExternalProvider, CurrentWsResponse::getScmAccountsList)
.containsExactly(true, "obiwan.kenobi", "Obiwan Kenobi", "obiwan.kenobi@starwars.com", "f5aa64437a1821ffe8b563099d506aef", true, "obiwan", "sonarqube",
newArrayList("obiwan:bitbucket", "obiwan:github"));
}
@Test
public void return_educationPrinciples_dismiss_notice() {
UserDto user = db.users().insertUser();
userSession.logIn(user);
PropertyDto property = new PropertyDto().setUserUuid(user.getUuid()).setKey("user.dismissedNotices.educationPrinciples");
db.properties().insertProperties(userSession.getLogin(), null, null, null, property);
CurrentWsResponse response = call();
assertThat(response.getDismissedNoticesMap().entrySet())
.extracting(Map.Entry::getKey, Map.Entry::getValue)
.contains(Tuple.tuple("educationPrinciples", true));
}
@Test
public void return_educationPrinciples_not_dismissed() {
UserDto user = db.users().insertUser();
userSession.logIn(user);
CurrentWsResponse response = call();
assertThat(response.getDismissedNoticesMap().entrySet())
.extracting(Map.Entry::getKey, Map.Entry::getValue)
.contains(Tuple.tuple("educationPrinciples", false));
}
@Test
public void return_minimal_user_info() {
UserDto user = db.users().insertUser(u -> u
.setLogin("obiwan.kenobi")
.setName("Obiwan Kenobi")
.setEmail(null)
.setLocal(true)
.setExternalLogin("obiwan")
.setExternalIdentityProvider("sonarqube")
.setScmAccounts(emptyList()));
userSession.logIn(user);
CurrentWsResponse response = call();
assertThat(response)
.extracting(CurrentWsResponse::getIsLoggedIn, CurrentWsResponse::getLogin, CurrentWsResponse::getName, CurrentWsResponse::hasAvatar, CurrentWsResponse::getLocal,
CurrentWsResponse::getExternalIdentity, CurrentWsResponse::getExternalProvider, CurrentWsResponse::getUsingSonarLintConnectedMode)
.containsExactly(true, "obiwan.kenobi", "Obiwan Kenobi", false, true, "obiwan", "sonarqube", false);
assertThat(response.hasEmail()).isFalse();
assertThat(response.getScmAccountsList()).isEmpty();
assertThat(response.getGroupsList()).isEmpty();
assertThat(response.getPermissions().getGlobalList()).isEmpty();
}
@Test
public void convert_empty_email_to_null() {
UserDto user = db.users().insertUser(u -> u
.setLogin("obiwan.kenobi")
.setEmail(""));
userSession.logIn(user);
CurrentWsResponse response = call();
assertThat(response.hasEmail()).isFalse();
}
@Test
public void return_group_membership() {
UserDto user = db.users().insertUser();
userSession.logIn(user);
db.users().insertMember(db.users().insertGroup(newGroupDto().setName("Jedi")), user);
db.users().insertMember(db.users().insertGroup(newGroupDto().setName("Rebel")), user);
CurrentWsResponse response = call();
assertThat(response.getGroupsList()).containsOnly("Jedi", "Rebel");
}
@Test
public void return_permissions() {
UserDto user = db.users().insertUser();
userSession
.logIn(user)
.addPermission(SCAN)
.addPermission(ADMINISTER_QUALITY_PROFILES);
CurrentWsResponse response = call();
assertThat(response.getPermissions().getGlobalList()).containsOnly("profileadmin", "scan");
}
@Test
public void fail_with_ISE_when_user_login_in_db_does_not_exist() {
db.users().insertUser(usert -> usert.setLogin("another"));
userSession.logIn("obiwan.kenobi");
assertThatThrownBy(this::call)
.isInstanceOf(IllegalStateException.class)
.hasMessage("User login 'obiwan.kenobi' cannot be found");
}
@Test
public void anonymous() {
userSession
.anonymous()
.addPermission(SCAN)
.addPermission(PROVISION_PROJECTS);
CurrentWsResponse response = call();
assertThat(response.getIsLoggedIn()).isFalse();
assertThat(response.getPermissions().getGlobalList()).containsOnly("scan", "provisioning");
assertThat(response)
.extracting(CurrentWsResponse::hasLogin, CurrentWsResponse::hasName, CurrentWsResponse::hasEmail, CurrentWsResponse::hasLocal,
CurrentWsResponse::hasExternalIdentity, CurrentWsResponse::hasExternalProvider)
.containsOnly(false);
assertThat(response.getScmAccountsList()).isEmpty();
assertThat(response.getGroupsList()).isEmpty();
}
@Test
public void json_example() {
ComponentDto componentDto = db.components().insertPrivateProject(u -> u.setUuid("UUID-of-the-death-star").setKey("death-star-key")).getMainBranchComponent();
UserDto obiwan = db.users().insertUser(user -> user
.setLogin("obiwan.kenobi")
.setName("Obiwan Kenobi")
.setEmail("obiwan.kenobi@starwars.com")
.setLocal(true)
.setExternalLogin("obiwan.kenobi")
.setExternalIdentityProvider("sonarqube")
.setScmAccounts(newArrayList("obiwan:github", "obiwan:bitbucket"))
.setHomepageType("PROJECT")
.setHomepageParameter("UUID-of-the-death-star"));
userSession
.logIn(obiwan)
.addPermission(SCAN)
.addPermission(ADMINISTER_QUALITY_PROFILES)
.addProjectPermission(USER, db.components().getProjectDtoByMainBranch(componentDto));
db.users().insertMember(db.users().insertGroup(newGroupDto().setName("Jedi")), obiwan);
db.users().insertMember(db.users().insertGroup(newGroupDto().setName("Rebel")), obiwan);
String response = ws.newRequest().execute().getInput();
assertJson(response).isSimilarTo(getClass().getResource("current-example.json"));
}
@Test
public void handle_givenSonarLintUserInDatabase_returnSonarLintUserFromTheEndpoint() {
UserDto user = db.users().insertUser(u -> u.setLastSonarlintConnectionDate(System.currentTimeMillis()));
userSession.logIn(user);
CurrentWsResponse response = call();
assertThat(response.getUsingSonarLintConnectedMode()).isTrue();
}
@Test
public void return_sonarlintAd_dismiss_notice() {
UserDto user = db.users().insertUser();
userSession.logIn(user);
PropertyDto property = new PropertyDto().setUserUuid(user.getUuid()).setKey("user.dismissedNotices.sonarlintAd");
db.properties().insertProperties(userSession.getLogin(), null, null, null, property);
CurrentWsResponse response = call();
assertThat(response.getDismissedNoticesMap().entrySet())
.extracting(Map.Entry::getKey, Map.Entry::getValue)
.contains(Tuple.tuple("sonarlintAd", true));
}
@Test
public void return_sonarlintAd_not_dismissed() {
UserDto user = db.users().insertUser();
userSession.logIn(user);
CurrentWsResponse response = call();
assertThat(response.getDismissedNoticesMap().entrySet())
.extracting(Map.Entry::getKey, Map.Entry::getValue)
.contains(Tuple.tuple("sonarlintAd", false));
}
@Test
public void test_definition() {
WebService.Action definition = ws.getDef();
assertThat(definition.key()).isEqualTo("current");
assertThat(definition.description()).isEqualTo("Get the details of the current authenticated user.");
assertThat(definition.since()).isEqualTo("5.2");
assertThat(definition.isPost()).isFalse();
assertThat(definition.isInternal()).isTrue();
assertThat(definition.responseExampleAsString()).isNotEmpty();
assertThat(definition.params()).isEmpty();
assertThat(definition.changelog()).isNotEmpty();
}
private CurrentWsResponse call() {
return ws.newRequest().executeProtobuf(CurrentWsResponse.class);
}
}
| 11,469 | 38.688581 | 167 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/DeactivateActionIT.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.user.ws;
import java.util.Optional;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.alm.setting.AlmSettingDto;
import org.sonar.db.ce.CeTaskMessageType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.db.permission.template.PermissionTemplateUserDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.property.PropertyDto;
import org.sonar.db.property.PropertyQuery;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.SessionTokenDto;
import org.sonar.db.user.UserDismissedMessageDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.management.ManagedInstanceService;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.user.ExternalIdentity;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static java.util.Collections.singletonList;
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.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.db.property.PropertyTesting.newUserPropertyDto;
import static org.sonar.test.JsonAssert.assertJson;
public class DeactivateActionIT {
private final System2 system2 = new AlwaysIncreasingSystem2();
@Rule
public DbTester db = DbTester.create(system2);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final DbClient dbClient = db.getDbClient();
private final DbSession dbSession = db.getSession();
private final UserAnonymizer userAnonymizer = new UserAnonymizer(db.getDbClient(), () -> "anonymized");
private final UserDeactivator userDeactivator = new UserDeactivator(dbClient, userAnonymizer);
private final ManagedInstanceService managedInstanceService = mock(ManagedInstanceService.class);
private final WsActionTester ws = new WsActionTester(new DeactivateAction(dbClient, userSession, new UserJsonWriter(userSession), userDeactivator, managedInstanceService
));
@Test
public void deactivate_user_and_delete_their_related_data() {
createAdminUser();
UserDto user = db.users().insertUser(u -> u
.setLogin("ada.lovelace")
.setEmail("ada.lovelace@noteg.com")
.setName("Ada Lovelace")
.setScmAccounts(singletonList("al")));
logInAsSystemAdministrator();
deactivate(user.getLogin());
verifyThatUserIsDeactivated(user.getLogin());
}
@Test
public void anonymize_user_if_param_provided() {
createAdminUser();
UserDto user = db.users().insertUser(u -> u
.setLogin("ada.lovelace")
.setEmail("ada.lovelace@noteg.com")
.setName("Ada Lovelace")
.setScmAccounts(singletonList("al")));
logInAsSystemAdministrator();
deactivate(user.getLogin(), true);
verifyThatUserIsDeactivated("anonymized");
verifyThatUserIsAnomymized("anonymized");
}
@Test
public void deactivate_user_deletes_their_group_membership() {
createAdminUser();
logInAsSystemAdministrator();
UserDto user = db.users().insertUser();
GroupDto group1 = db.users().insertGroup();
db.users().insertGroup();
db.users().insertMember(group1, user);
deactivate(user.getLogin());
assertThat(db.getDbClient().groupMembershipDao().selectGroupUuidsByUserUuid(dbSession, user.getUuid())).isEmpty();
}
@Test
public void deactivate_user_deletes_their_tokens() {
createAdminUser();
logInAsSystemAdministrator();
UserDto user = db.users().insertUser();
db.users().insertToken(user);
db.users().insertToken(user);
db.commit();
deactivate(user.getLogin());
assertThat(db.getDbClient().userTokenDao().selectByUser(dbSession, user)).isEmpty();
}
@Test
public void deactivate_user_deletes_their_properties() {
createAdminUser();
logInAsSystemAdministrator();
UserDto user = db.users().insertUser();
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
db.properties().insertProperty(newUserPropertyDto(user), null, null, null, user.getLogin());
db.properties().insertProperty(newUserPropertyDto(user), null, null, null, user.getLogin());
db.properties().insertProperty(newUserPropertyDto(user).setEntityUuid(project.uuid()), project.getKey(),
project.name(), project.qualifier(), user.getLogin());
deactivate(user.getLogin());
assertThat(db.getDbClient().propertiesDao().selectByQuery(PropertyQuery.builder().setUserUuid(user.getUuid()).build(), dbSession)).isEmpty();
assertThat(db.getDbClient().propertiesDao().selectByQuery(PropertyQuery.builder().setUserUuid(user.getUuid()).setEntityUuid(project.uuid()).build(), dbSession)).isEmpty();
}
@Test
public void deactivate_user_deletes_their_permissions() {
createAdminUser();
logInAsSystemAdministrator();
UserDto user = db.users().insertUser();
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
db.users().insertGlobalPermissionOnUser(user, GlobalPermission.SCAN);
db.users().insertGlobalPermissionOnUser(user, GlobalPermission.ADMINISTER_QUALITY_PROFILES);
db.users().insertProjectPermissionOnUser(user, UserRole.USER, project);
db.users().insertProjectPermissionOnUser(user, UserRole.CODEVIEWER, project);
deactivate(user.getLogin());
assertThat(db.getDbClient().userPermissionDao().selectGlobalPermissionsOfUser(dbSession, user.getUuid())).isEmpty();
assertThat(db.getDbClient().userPermissionDao().selectEntityPermissionsOfUser(dbSession, user.getUuid(), project.uuid())).isEmpty();
}
@Test
public void deactivate_user_deletes_their_permission_templates() {
createAdminUser();
logInAsSystemAdministrator();
UserDto user = db.users().insertUser();
PermissionTemplateDto template = db.permissionTemplates().insertTemplate();
PermissionTemplateDto anotherTemplate = db.permissionTemplates().insertTemplate();
db.permissionTemplates().addUserToTemplate(template.getUuid(), user.getUuid(), UserRole.USER, template.getName(), user.getLogin());
db.permissionTemplates().addUserToTemplate(anotherTemplate.getUuid(), user.getUuid(), UserRole.CODEVIEWER, anotherTemplate.getName(), user.getLogin());
deactivate(user.getLogin());
assertThat(db.getDbClient().permissionTemplateDao().selectUserPermissionsByTemplateId(dbSession, template.getUuid())).extracting(PermissionTemplateUserDto::getUserUuid)
.isEmpty();
assertThat(db.getDbClient().permissionTemplateDao().selectUserPermissionsByTemplateId(dbSession, anotherTemplate.getUuid())).extracting(PermissionTemplateUserDto::getUserUuid)
.isEmpty();
}
@Test
public void deactivate_user_deletes_their_qprofiles_permissions() {
createAdminUser();
logInAsSystemAdministrator();
UserDto user = db.users().insertUser();
QProfileDto profile = db.qualityProfiles().insert();
db.qualityProfiles().addUserPermission(profile, user);
deactivate(user.getLogin());
assertThat(db.getDbClient().qProfileEditUsersDao().exists(dbSession, profile, user)).isFalse();
}
@Test
public void deactivate_user_deletes_their_default_assignee_settings() {
createAdminUser();
logInAsSystemAdministrator();
UserDto user = db.users().insertUser();
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto anotherProject = db.components().insertPrivateProject().getMainBranchComponent();
db.properties().insertProperty(new PropertyDto().setKey("sonar.issues.defaultAssigneeLogin").setValue(user.getLogin())
.setEntityUuid(project.uuid()), project.getKey(), project.name(), project.qualifier(), user.getLogin());
db.properties().insertProperty(new PropertyDto().setKey("sonar.issues.defaultAssigneeLogin").setValue(user.getLogin())
.setEntityUuid(anotherProject.uuid()), anotherProject.getKey(), anotherProject.name(), anotherProject.qualifier(), user.getLogin());
db.properties().insertProperty(new PropertyDto().setKey("other").setValue(user.getLogin())
.setEntityUuid(anotherProject.uuid()), anotherProject.getKey(), anotherProject.name(), anotherProject.qualifier(), user.getLogin());
deactivate(user.getLogin());
assertThat(db.getDbClient().propertiesDao().selectByQuery(PropertyQuery.builder().setKey("sonar.issues.defaultAssigneeLogin").build(), db.getSession())).isEmpty();
assertThat(db.getDbClient().propertiesDao().selectByQuery(PropertyQuery.builder().build(), db.getSession())).extracting(PropertyDto::getKey).containsOnly("other");
}
@Test
public void deactivate_user_deletes_their_qgate_permissions() {
createAdminUser();
logInAsSystemAdministrator();
UserDto user = db.users().insertUser();
QualityGateDto qualityGate = db.qualityGates().insertQualityGate();
db.qualityGates().addUserPermission(qualityGate, user);
assertThat(db.countRowsOfTable("qgate_user_permissions")).isOne();
deactivate(user.getLogin());
assertThat(db.countRowsOfTable("qgate_user_permissions")).isZero();
}
@Test
public void deactivate_user_deletes_their_alm_pat() {
createAdminUser();
logInAsSystemAdministrator();
AlmSettingDto almSettingDto = db.almSettings().insertBitbucketAlmSetting();
UserDto user = db.users().insertUser();
db.almPats().insert(p -> p.setUserUuid(user.getUuid()), p -> p.setAlmSettingUuid(almSettingDto.getUuid()));
UserDto anotherUser = db.users().insertUser();
db.almPats().insert(p -> p.setUserUuid(anotherUser.getUuid()), p -> p.setAlmSettingUuid(almSettingDto.getUuid()));
deactivate(user.getLogin());
assertThat(db.getDbClient().almPatDao().selectByUserAndAlmSetting(dbSession, user.getUuid(), almSettingDto)).isEmpty();
assertThat(db.getDbClient().almPatDao().selectByUserAndAlmSetting(dbSession, anotherUser.getUuid(), almSettingDto)).isNotNull();
}
@Test
public void deactivate_user_deletes_their_session_tokens() {
createAdminUser();
logInAsSystemAdministrator();
UserDto user = db.users().insertUser();
SessionTokenDto sessionToken1 = db.users().insertSessionToken(user);
SessionTokenDto sessionToken2 = db.users().insertSessionToken(user);
UserDto anotherUser = db.users().insertUser();
SessionTokenDto sessionToken3 = db.users().insertSessionToken(anotherUser);
deactivate(user.getLogin());
assertThat(db.getDbClient().sessionTokensDao().selectByUuid(dbSession, sessionToken1.getUuid())).isNotPresent();
assertThat(db.getDbClient().sessionTokensDao().selectByUuid(dbSession, sessionToken2.getUuid())).isNotPresent();
assertThat(db.getDbClient().sessionTokensDao().selectByUuid(dbSession, sessionToken3.getUuid())).isPresent();
}
@Test
public void deactivate_user_deletes_their_dismissed_messages() {
createAdminUser();
logInAsSystemAdministrator();
ProjectDto project1 = db.components().insertPrivateProject().getProjectDto();
ProjectDto project2 = db.components().insertPrivateProject().getProjectDto();
UserDto user = db.users().insertUser();
db.users().insertUserDismissedMessage(user, project1, CeTaskMessageType.SUGGEST_DEVELOPER_EDITION_UPGRADE);
db.users().insertUserDismissedMessage(user, project2, CeTaskMessageType.SUGGEST_DEVELOPER_EDITION_UPGRADE);
UserDto anotherUser = db.users().insertUser();
UserDismissedMessageDto msg3 = db.users().insertUserDismissedMessage(anotherUser, project1, CeTaskMessageType.SUGGEST_DEVELOPER_EDITION_UPGRADE);
UserDismissedMessageDto msg4 = db.users().insertUserDismissedMessage(anotherUser, project2, CeTaskMessageType.SUGGEST_DEVELOPER_EDITION_UPGRADE);
deactivate(user.getLogin());
assertThat(db.getDbClient().userDismissedMessagesDao().selectByUser(dbSession, user)).isEmpty();
assertThat(db.getDbClient().userDismissedMessagesDao().selectByUser(dbSession, anotherUser))
.extracting(UserDismissedMessageDto::getUuid)
.containsExactlyInAnyOrder(msg3.getUuid(), msg4.getUuid());
}
@Test
public void user_cannot_deactivate_itself_on_sonarqube() {
createAdminUser();
UserDto user = db.users().insertUser();
userSession.logIn(user.getLogin()).setSystemAdministrator();
assertThatThrownBy(() -> {
deactivate(user.getLogin());
verifyThatUserExists(user.getLogin());
})
.isInstanceOf(BadRequestException.class)
.hasMessage("Self-deactivation is not possible");
}
@Test
public void deactivation_requires_to_be_logged_in() {
createAdminUser();
assertThatThrownBy(() -> {
deactivate("someone");
})
.isInstanceOf(UnauthorizedException.class)
.hasMessage("Authentication is required");
}
@Test
public void deactivation_requires_administrator_permission_on_sonarqube() {
createAdminUser();
userSession.logIn();
assertThatThrownBy(() -> {
deactivate("someone");
})
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void fail_if_user_does_not_exist() {
createAdminUser();
logInAsSystemAdministrator();
assertThatThrownBy(() -> {
deactivate("someone");
})
.isInstanceOf(NotFoundException.class)
.hasMessage("User 'someone' doesn't exist");
}
@Test
public void fail_if_login_is_blank() {
createAdminUser();
logInAsSystemAdministrator();
assertThatThrownBy(() -> {
deactivate("");
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The 'login' parameter is missing");
}
@Test
public void fail_if_login_is_missing() {
createAdminUser();
logInAsSystemAdministrator();
assertThatThrownBy(() -> {
deactivate(null);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The 'login' parameter is missing");
}
@Test
public void fail_to_deactivate_last_administrator() {
UserDto admin = db.users().insertUser();
db.users().insertGlobalPermissionOnUser(admin, GlobalPermission.ADMINISTER);
logInAsSystemAdministrator();
assertThatThrownBy(() -> {
deactivate(admin.getLogin());
})
.isInstanceOf(BadRequestException.class)
.hasMessage("User is last administrator, and cannot be deactivated");
}
@Test
public void administrators_can_be_deactivated_if_there_are_still_other_administrators() {
UserDto admin = createAdminUser();
UserDto anotherAdmin = createAdminUser();
logInAsSystemAdministrator();
deactivate(admin.getLogin());
verifyThatUserIsDeactivated(admin.getLogin());
verifyThatUserExists(anotherAdmin.getLogin());
}
@Test
public void test_definition() {
assertThat(ws.getDef().isPost()).isTrue();
assertThat(ws.getDef().isInternal()).isFalse();
assertThat(ws.getDef().params()).hasSize(2);
}
@Test
public void test_example() {
createAdminUser();
UserDto user = db.users().insertUser(u -> u
.setLogin("ada.lovelace")
.setEmail("ada.lovelace@noteg.com")
.setName("Ada Lovelace")
.setLocal(true)
.setScmAccounts(singletonList("al")));
logInAsSystemAdministrator();
String json = deactivate(user.getLogin()).getInput();
assertJson(json).isSimilarTo(ws.getDef().responseExampleAsString());
}
@Test
public void anonymizeUser_whenSamlAndScimUser_shouldDeleteScimMapping() {
createAdminUser();
logInAsSystemAdministrator();
UserDto user = db.users().insertUser();
db.getDbClient().scimUserDao().enableScimForUser(dbSession, user.getUuid());
db.commit();
deactivate(user.getLogin(), true);
assertThat(db.getDbClient().scimUserDao().findByUserUuid(dbSession, user.getUuid())).isEmpty();
}
@Test
public void handle_whenUserManagedAndInstanceManaged_shouldThrowBadRequestException() {
createAdminUser();
logInAsSystemAdministrator();
UserDto user = db.users().insertUser();
when(managedInstanceService.isUserManaged(any(), eq(user.getLogin()))).thenReturn(true);
assertThatExceptionOfType(BadRequestException.class)
.isThrownBy(() -> deactivate(user.getLogin()))
.withMessage("Operation not allowed when the instance is externally managed.");
}
@Test
public void handle_whenInstanceManagedAndNotSystemAdministrator_shouldThrowUnauthorizedException() {
UserDto userDto = db.users().insertUser();
String login = userDto.getLogin();
assertThatThrownBy(() -> deactivate(login))
.isInstanceOf(UnauthorizedException.class)
.hasMessage("Authentication is required");
}
private void logInAsSystemAdministrator() {
userSession.logIn().setSystemAdministrator();
}
private TestResponse deactivate(@Nullable String login) {
return deactivate(login, false);
}
private TestResponse deactivate(@Nullable String login, boolean anonymize) {
return deactivate(ws, login, anonymize);
}
private TestResponse deactivate(WsActionTester ws, @Nullable String login, boolean anonymize) {
TestRequest request = ws.newRequest()
.setMethod("POST");
Optional.ofNullable(login).ifPresent(t -> request.setParam("login", login));
if (anonymize) {
request.setParam("anonymize", "true");
}
return request.execute();
}
private void verifyThatUserExists(String login) {
assertThat(db.users().selectUserByLogin(login)).isPresent();
}
private void verifyThatUserIsDeactivated(String login) {
Optional<UserDto> user = db.users().selectUserByLogin(login);
assertThat(user).isPresent();
assertThat(user.get().isActive()).isFalse();
assertThat(user.get().getEmail()).isNull();
assertThat(user.get().getSortedScmAccounts()).isEmpty();
}
private void verifyThatUserIsAnomymized(String login) {
Optional<UserDto> user = db.users().selectUserByLogin(login);
assertThat(user).isPresent();
assertThat(user.get().getName()).isEqualTo(login);
assertThat(user.get().getExternalLogin()).isEqualTo(login);
assertThat(user.get().getExternalId()).isEqualTo(login);
assertThat(user.get().getExternalIdentityProvider()).isEqualTo(ExternalIdentity.SQ_AUTHORITY);
}
private UserDto createAdminUser() {
UserDto admin = db.users().insertUser();
db.users().insertGlobalPermissionOnUser(admin, GlobalPermission.ADMINISTER);
db.commit();
return admin;
}
}
| 20,074 | 38.440079 | 179 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/DismissNoticeActionIT.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.user.ws;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.property.PropertyDto;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class DismissNoticeActionIT {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
private final WsActionTester tester = new WsActionTester(new DismissNoticeAction(userSessionRule, db.getDbClient()));
@Test
public void dismiss_educationPrinciples() {
userSessionRule.logIn();
TestResponse testResponse = tester.newRequest()
.setParam("notice", "educationPrinciples")
.execute();
assertThat(testResponse.getStatus()).isEqualTo(204);
Optional<PropertyDto> propertyDto = db.properties().findFirstUserProperty(userSessionRule.getUuid(), "user.dismissedNotices.educationPrinciples");
assertThat(propertyDto).isPresent();
}
@Test
public void dismiss_sonarlintAd() {
userSessionRule.logIn();
TestResponse testResponse = tester.newRequest()
.setParam("notice", "sonarlintAd")
.execute();
assertThat(testResponse.getStatus()).isEqualTo(204);
Optional<PropertyDto> propertyDto = db.properties().findFirstUserProperty(userSessionRule.getUuid(), "user.dismissedNotices.sonarlintAd");
assertThat(propertyDto).isPresent();
}
@Test
public void authentication_is_required() {
TestRequest testRequest = tester.newRequest()
.setParam("notice", "anyValue");
assertThatThrownBy(testRequest::execute)
.isInstanceOf(UnauthorizedException.class)
.hasMessage("Authentication is required");
}
@Test
public void notice_parameter_is_mandatory() {
userSessionRule.logIn();
TestRequest testRequest = tester.newRequest();
assertThatThrownBy(testRequest::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The 'notice' parameter is missing");
}
@Test
public void notice_not_supported() {
userSessionRule.logIn();
TestRequest testRequest = tester.newRequest()
.setParam("notice", "not_supported_value");
assertThatThrownBy(testRequest::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Value of parameter 'notice' (not_supported_value) must be one of: [educationPrinciples, sonarlintAd]");
}
@Test
public void notice_already_exist_dont_fail() {
userSessionRule.logIn();
PropertyDto property = new PropertyDto().setKey("user.dismissedNotices.educationPrinciples").setUserUuid(userSessionRule.getUuid());
db.properties().insertProperties(userSessionRule.getLogin(), null, null, null, property);
assertThat(db.properties().findFirstUserProperty(userSessionRule.getUuid(), "user.dismissedNotices.educationPrinciples")).isPresent();
TestResponse testResponse = tester.newRequest()
.setParam("notice", "sonarlintAd")
.execute();
assertThat(testResponse.getStatus()).isEqualTo(204);
assertThat(db.properties().findFirstUserProperty(userSessionRule.getUuid(), "user.dismissedNotices.educationPrinciples")).isPresent();
}
}
| 4,381 | 33.777778 | 150 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/GroupsActionIT.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.user.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.db.DbTester;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.usergroups.DefaultGroupFinder;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.MediaTypes;
import org.sonarqube.ws.Users.GroupsWsResponse;
import static java.util.Collections.singletonList;
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.sonar.api.server.ws.WebService.SelectionMode.ALL;
import static org.sonar.api.server.ws.WebService.SelectionMode.DESELECTED;
import static org.sonar.api.server.ws.WebService.SelectionMode.SELECTED;
import static org.sonar.db.permission.GlobalPermission.SCAN;
import static org.sonar.db.user.GroupTesting.newGroupDto;
import static org.sonar.db.user.UserTesting.newUserDto;
import static org.sonar.test.JsonAssert.assertJson;
public class GroupsActionIT {
private static final String USER_LOGIN = "john";
@Rule
public DbTester db = DbTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone().logIn().addPermission(GlobalPermission.ADMINISTER);
private WsActionTester ws = new WsActionTester(new GroupsAction(db.getDbClient(), userSession,
new DefaultGroupFinder(db.getDbClient())));
@Test
public void empty_groups() {
insertUser();
insertDefaultGroup();
GroupsWsResponse response = call(ws.newRequest().setParam("login", USER_LOGIN));
assertThat(response.getGroupsList()).isEmpty();
}
@Test
public void return_selected_groups_selected_param_is_set_to_all() {
UserDto user = insertUser();
GroupDto usersGroup = insertDefaultGroup();
GroupDto adminGroup = insertGroup("sonar-admins", "Sonar Admins");
addUserToGroup(user, usersGroup);
GroupsWsResponse response = call(ws.newRequest().setParam("login", USER_LOGIN).setParam(Param.SELECTED, ALL.value()));
assertThat(response.getGroupsList())
.extracting(GroupsWsResponse.Group::getId, GroupsWsResponse.Group::getName, GroupsWsResponse.Group::getDescription, GroupsWsResponse.Group::getSelected)
.containsOnly(
tuple(usersGroup.getUuid(), usersGroup.getName(), usersGroup.getDescription(), true),
tuple(adminGroup.getUuid(), adminGroup.getName(), adminGroup.getDescription(), false));
}
@Test
public void return_selected_groups_selected_param_is_set_to_selected() {
UserDto user = insertUser();
GroupDto usersGroup = insertDefaultGroup();
insertGroup("sonar-admins", "Sonar Admins");
addUserToGroup(user, usersGroup);
GroupsWsResponse response = call(ws.newRequest().setParam("login", USER_LOGIN).setParam(Param.SELECTED, SELECTED.value()));
assertThat(response.getGroupsList())
.extracting(GroupsWsResponse.Group::getId, GroupsWsResponse.Group::getName, GroupsWsResponse.Group::getDescription, GroupsWsResponse.Group::getSelected)
.containsOnly(tuple(usersGroup.getUuid(), usersGroup.getName(), usersGroup.getDescription(), true));
}
@Test
public void return_selected_groups_selected_param_is_not_set() {
UserDto user = insertUser();
GroupDto usersGroup = insertDefaultGroup();
insertGroup("sonar-admins", "Sonar Admins");
addUserToGroup(user, usersGroup);
GroupsWsResponse response = call(ws.newRequest().setParam("login", USER_LOGIN));
assertThat(response.getGroupsList())
.extracting(GroupsWsResponse.Group::getId, GroupsWsResponse.Group::getName, GroupsWsResponse.Group::getDescription, GroupsWsResponse.Group::getSelected)
.containsOnly(tuple(usersGroup.getUuid(), usersGroup.getName(), usersGroup.getDescription(), true));
}
@Test
public void return_not_selected_groups_selected_param_is_set_to_deselected() {
UserDto user = insertUser();
GroupDto usersGroup = insertDefaultGroup();
GroupDto adminGroup = insertGroup("sonar-admins", "Sonar Admins");
addUserToGroup(user, usersGroup);
GroupsWsResponse response = call(ws.newRequest().setParam("login", USER_LOGIN).setParam(Param.SELECTED, DESELECTED.value()));
assertThat(response.getGroupsList())
.extracting(GroupsWsResponse.Group::getId, GroupsWsResponse.Group::getName, GroupsWsResponse.Group::getDescription, GroupsWsResponse.Group::getSelected)
.containsOnly(tuple(adminGroup.getUuid(), adminGroup.getName(), adminGroup.getDescription(), false));
}
@Test
public void search_with_pagination() {
UserDto user = insertUser();
insertDefaultGroup();
for (int i = 1; i <= 9; i++) {
GroupDto groupDto = insertGroup("group-" + i, "group-" + i);
addUserToGroup(user, groupDto);
}
GroupsWsResponse response = call(ws.newRequest().setParam("login", USER_LOGIN)
.setParam(Param.PAGE_SIZE, "3")
.setParam(Param.PAGE, "2")
.setParam(Param.SELECTED, ALL.value()));
assertThat(response.getGroupsList()).extracting(GroupsWsResponse.Group::getName).containsOnly("group-4", "group-5", "group-6");
assertThat(response.getPaging().getPageSize()).isEqualTo(3);
assertThat(response.getPaging().getPageIndex()).isEqualTo(2);
assertThat(response.getPaging().getTotal()).isEqualTo(10);
}
@Test
public void search_by_text_query() {
UserDto user = insertUser();
GroupDto usersGroup = insertDefaultGroup();
GroupDto adminGroup = insertGroup("sonar-admins", "Sonar Admins");
addUserToGroup(user, usersGroup);
assertThat(call(ws.newRequest().setParam("login", USER_LOGIN).setParam("q", "admin").setParam(Param.SELECTED, ALL.value())).getGroupsList())
.extracting(GroupsWsResponse.Group::getName).containsOnly(adminGroup.getName());
assertThat(call(ws.newRequest().setParam("login", USER_LOGIN).setParam("q", "users").setParam(Param.SELECTED, ALL.value())).getGroupsList())
.extracting(GroupsWsResponse.Group::getName).containsOnly(usersGroup.getName());
}
@Test
public void return_default_group_information() {
UserDto user = insertUser();
GroupDto usersGroup = insertDefaultGroup();
GroupDto adminGroup = insertGroup("sonar-admins", "Sonar Admins");
addUserToGroup(user, usersGroup);
GroupsWsResponse response = call(ws.newRequest().setParam("login", USER_LOGIN).setParam(Param.SELECTED, ALL.value()));
assertThat(response.getGroupsList())
.extracting(GroupsWsResponse.Group::getId, GroupsWsResponse.Group::getName, GroupsWsResponse.Group::getDefault)
.containsOnly(
tuple(usersGroup.getUuid(), usersGroup.getName(), true),
tuple(adminGroup.getUuid(), adminGroup.getName(), false));
}
@Test
public void return_groups() {
UserDto user = insertUser();
GroupDto group = db.users().insertDefaultGroup();
addUserToGroup(user, group);
GroupsWsResponse response = call(ws.newRequest()
.setParam("login", USER_LOGIN)
.setParam(Param.SELECTED, ALL.value()));
assertThat(response.getGroupsList())
.extracting(GroupsWsResponse.Group::getId, GroupsWsResponse.Group::getName, GroupsWsResponse.Group::getDescription, GroupsWsResponse.Group::getSelected,
GroupsWsResponse.Group::getDefault)
.containsOnly(tuple(group.getUuid(), group.getName(), group.getDescription(), true, true));
}
@Test
public void fail_when_no_default_group() {
UserDto user = insertUser();
GroupDto group = db.users().insertGroup("group1");
addUserToGroup(user, group);
assertThatThrownBy(() -> {
call(ws.newRequest().setParam("login", USER_LOGIN));
})
.isInstanceOf(IllegalStateException.class)
.hasMessage("Default group cannot be found");
}
@Test
public void fail_on_unknown_user() {
insertDefaultGroup();
assertThatThrownBy(() -> {
call(ws.newRequest().setParam("login", USER_LOGIN));
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Unknown user: john");
}
@Test
public void fail_on_disabled_user() {
UserDto userDto = db.users().insertUser(user -> user.setLogin("disabled").setActive(false));
insertDefaultGroup();
assertThatThrownBy(() -> {
call(ws.newRequest().setParam("login", userDto.getLogin()));
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Unknown user: disabled");
}
@Test
public void fail_when_page_size_is_greater_than_500() {
UserDto user = insertUser();
insertDefaultGroup();
assertThatThrownBy(() -> {
call(ws.newRequest()
.setParam("login", user.getLogin())
.setParam(Param.PAGE_SIZE, "501"));
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The 'ps' parameter must be less than 500");
}
@Test
public void fail_on_missing_permission() {
userSession.logIn().addPermission(SCAN);
assertThatThrownBy(() -> {
call(ws.newRequest().setParam("login", USER_LOGIN));
})
.isInstanceOf(ForbiddenException.class);
}
@Test
public void fail_on_missing_permission_and_non_existent_user() {
userSession.logIn().addPermission(SCAN);
assertThatThrownBy(() -> {
call(ws.newRequest().setParam("login", "unknown"));
})
.isInstanceOf(ForbiddenException.class);
}
@Test
public void fail_when_no_permission() {
userSession.logIn("not-admin");
TestRequest request = ws.newRequest().setParam("login", USER_LOGIN);
assertThatThrownBy(() -> call(request))
.isInstanceOf(ForbiddenException.class);
}
@Test
public void test_json_example() {
UserDto user = insertUser();
GroupDto usersGroup = insertDefaultGroup();
insertGroup("sonar-admins", "Sonar Admins");
addUserToGroup(user, usersGroup);
String response = ws.newRequest()
.setMediaType(MediaTypes.JSON)
.setParam("login", USER_LOGIN)
.setParam(Param.SELECTED, ALL.value())
.setParam(Param.PAGE_SIZE, "25")
.setParam(Param.PAGE, "1")
.execute().getInput();
assertJson(response).ignoreFields("id").isSimilarTo(ws.getDef().responseExampleAsString());
}
@Test
public void verify_definition() {
WebService.Action action = ws.getDef();
assertThat(action.since()).isEqualTo("5.2");
assertThat(action.isPost()).isFalse();
assertThat(action.isInternal()).isFalse();
assertThat(action.responseExampleAsString()).isNotEmpty();
assertThat(action.params()).extracting(Param::key).containsOnly("p", "q", "ps", "login", "selected");
WebService.Param qualifiers = action.param("login");
assertThat(qualifiers.isRequired()).isTrue();
}
private GroupDto insertGroup(String name, String description) {
return db.users().insertGroup(newGroupDto().setName(name).setDescription(description));
}
private GroupDto insertDefaultGroup() {
return db.users().insertDefaultGroup();
}
private void addUserToGroup(UserDto user, GroupDto usersGroup) {
db.users().insertMember(usersGroup, user);
}
private UserDto insertUser() {
return db.users().insertUser(newUserDto()
.setActive(true)
.setEmail("john@email.com")
.setLogin(USER_LOGIN)
.setName("John")
.setScmAccounts(singletonList("jn")));
}
private GroupsWsResponse call(TestRequest request) {
return request.executeProtobuf(GroupsWsResponse.class);
}
}
| 12,551 | 36.580838 | 158 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/IdentityProvidersActionIT.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.user.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.authentication.Display;
import org.sonar.api.server.authentication.IdentityProvider;
import org.sonar.api.server.ws.WebService;
import org.sonar.server.authentication.IdentityProviderRepositoryRule;
import org.sonar.server.authentication.TestIdentityProvider;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.test.JsonAssert.assertJson;
public class IdentityProvidersActionIT {
@Rule
public IdentityProviderRepositoryRule identityProviderRepository = new IdentityProviderRepositoryRule()
.addIdentityProvider(GITHUB)
.addIdentityProvider(BIT_BUCKET);
WsActionTester ws = new WsActionTester(new IdentityProvidersAction(identityProviderRepository));
@Test
public void json_example() {
String response = ws.newRequest().execute().getInput();
assertJson(response).isSimilarTo(getClass().getResource("identity_providers-example.json"));
}
@Test
public void test_definition() {
WebService.Action webService = ws.getDef();
assertThat(webService.key()).isEqualTo("identity_providers");
assertThat(webService.responseExampleAsString()).isNotEmpty();
assertThat(webService.since()).isEqualTo("5.5");
assertThat(webService.isInternal()).isTrue();
}
private static IdentityProvider GITHUB = new TestIdentityProvider()
.setKey("github")
.setName("Github")
.setDisplay(Display.builder()
.setIconPath("/static/authgithub/github.svg")
.setBackgroundColor("#444444")
.build())
.setEnabled(true);
private static IdentityProvider BIT_BUCKET = new TestIdentityProvider()
.setKey("bitbucket")
.setName("Bitbucket")
.setDisplay(Display.builder()
.setIconPath("/static/authbitbucket/bitbucket.svg")
.setBackgroundColor("#205081")
.setHelpMessage("You need an existing account on bitbucket.com")
.build())
.setEnabled(true);
}
| 2,873 | 35.379747 | 105 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/SearchActionIT.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.user.ws;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Set;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.DateUtils;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbTester;
import org.sonar.db.scim.ScimUserDao;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ServerException;
import org.sonar.server.issue.AvatarResolverImpl;
import org.sonar.server.management.ManagedInstanceService;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Common.Paging;
import org.sonarqube.ws.Users.SearchWsResponse;
import org.sonarqube.ws.Users.SearchWsResponse.User;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
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.tuple;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.api.utils.DateUtils.formatDateTime;
import static org.sonar.test.JsonAssert.assertJson;
public class SearchActionIT {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create();
private ManagedInstanceService managedInstanceService = mock(ManagedInstanceService.class);
private WsActionTester ws = new WsActionTester(new SearchAction(userSession, db.getDbClient(), new AvatarResolverImpl(), managedInstanceService));
@Test
public void search_for_all_active_users() {
UserDto user1 = db.users().insertUser();
UserDto user2 = db.users().insertUser();
UserDto user3 = db.users().insertUser(u -> u.setActive(false));
userSession.logIn();
SearchWsResponse response = ws.newRequest()
.executeProtobuf(SearchWsResponse.class);
assertThat(response.getUsersList())
.extracting(User::getLogin, User::getName)
.containsExactlyInAnyOrder(
tuple(user1.getLogin(), user1.getName()),
tuple(user2.getLogin(), user2.getName()));
}
@Test
public void search_deactivated_users() {
UserDto user1 = db.users().insertUser(u -> u.setActive(false));
UserDto user2 = db.users().insertUser(u -> u.setActive(true));
userSession.logIn();
SearchWsResponse response = ws.newRequest()
.setParam("deactivated", "true")
.executeProtobuf(SearchWsResponse.class);
assertThat(response.getUsersList())
.extracting(User::getLogin, User::getName)
.containsExactlyInAnyOrder(
tuple(user1.getLogin(), user1.getName()));
}
@Test
public void search_with_query() {
userSession.logIn();
UserDto user = db.users().insertUser(u -> u
.setLogin("user-%_%-login")
.setName("user-name")
.setEmail("user@mail.com")
.setLocal(true)
.setScmAccounts(singletonList("user1")));
assertThat(ws.newRequest()
.setParam("q", "user-%_%-")
.executeProtobuf(SearchWsResponse.class).getUsersList())
.extracting(User::getLogin)
.containsExactlyInAnyOrder(user.getLogin());
assertThat(ws.newRequest()
.setParam("q", "user@MAIL.com")
.executeProtobuf(SearchWsResponse.class).getUsersList())
.extracting(User::getLogin)
.containsExactlyInAnyOrder(user.getLogin());
assertThat(ws.newRequest()
.setParam("q", "user-name")
.executeProtobuf(SearchWsResponse.class).getUsersList())
.extracting(User::getLogin)
.containsExactlyInAnyOrder(user.getLogin());
}
@Test
public void return_avatar() {
UserDto user = db.users().insertUser(u -> u.setEmail("john@doe.com"));
userSession.logIn();
SearchWsResponse response = ws.newRequest()
.executeProtobuf(SearchWsResponse.class);
assertThat(response.getUsersList())
.extracting(User::getLogin, User::getAvatar)
.containsExactlyInAnyOrder(tuple(user.getLogin(), "6a6c19fea4a3676970167ce51f39e6ee"));
}
@Test
public void return_isManagedFlag() {
UserDto nonManagedUser = db.users().insertUser(u -> u.setEmail("john@doe.com"));
UserDto managedUser = db.users().insertUser(u -> u.setEmail("externalUser@doe.com"));
mockUsersAsManaged(managedUser.getUuid());
userSession.logIn().setSystemAdministrator();
SearchWsResponse response = ws.newRequest()
.executeProtobuf(SearchWsResponse.class);
assertThat(response.getUsersList())
.extracting(User::getLogin, User::getManaged)
.containsExactlyInAnyOrder(
tuple(managedUser.getLogin(), true),
tuple(nonManagedUser.getLogin(), false)
);
}
@Test
public void search_whenFilteringByManagedAndInstanceNotManaged_throws() {
userSession.logIn().setSystemAdministrator();
TestRequest testRequest = ws.newRequest()
.setParam("managed", "true");
assertThatExceptionOfType(BadRequestException.class)
.isThrownBy(() -> testRequest.executeProtobuf(SearchWsResponse.class))
.withMessage("The 'managed' parameter is only available for managed instances.");
}
@Test
public void search_whenFilteringByManagedAndInstanceManaged_returnsCorrectResults() {
UserDto nonManagedUser = db.users().insertUser(u -> u.setEmail("john@doe.com"));
UserDto managedUser = db.users().insertUser(u -> u.setEmail("externalUser@doe.com"));
db.users().enableScimForUser(managedUser);
mockUsersAsManaged(managedUser.getUuid());
mockInstanceExternallyManagedAndFilterForManagedUsers();
userSession.logIn().setSystemAdministrator();
SearchWsResponse response = ws.newRequest()
.setParam("managed", "true")
.executeProtobuf(SearchWsResponse.class);
assertThat(response.getUsersList())
.extracting(User::getLogin, User::getManaged)
.containsExactlyInAnyOrder(
tuple(managedUser.getLogin(), true)
);
}
@Test
public void search_whenFilteringByNonManagedAndInstanceManaged_returnsCorrectResults() {
UserDto nonManagedUser = db.users().insertUser(u -> u.setEmail("john@doe.com"));
UserDto managedUser = db.users().insertUser(u -> u.setEmail("externalUser@doe.com"));
db.users().enableScimForUser(managedUser);
mockUsersAsManaged(managedUser.getUuid());
mockInstanceExternallyManagedAndFilterForManagedUsers();
userSession.logIn().setSystemAdministrator();
SearchWsResponse response = ws.newRequest()
.setParam("managed", "false")
.executeProtobuf(SearchWsResponse.class);
assertThat(response.getUsersList())
.extracting(User::getLogin, User::getManaged)
.containsExactlyInAnyOrder(
tuple(nonManagedUser.getLogin(), false)
);
}
private void mockInstanceExternallyManagedAndFilterForManagedUsers() {
when(managedInstanceService.isInstanceExternallyManaged()).thenReturn(true);
when(managedInstanceService.getManagedUsersSqlFilter(anyBoolean()))
.thenAnswer(invocation -> {
Boolean managed = invocation.getArgument(0, Boolean.class);
return new ScimUserDao(mock(UuidFactory.class)).getManagedUserSqlFilter(managed);
});
}
@Test
public void return_scm_accounts() {
UserDto user = db.users().insertUser(u -> u.setScmAccounts(asList("john1", "john2")));
userSession.logIn();
SearchWsResponse response = ws.newRequest()
.executeProtobuf(SearchWsResponse.class);
assertThat(response.getUsersList())
.extracting(User::getLogin, u -> u.getScmAccounts().getScmAccountsList())
.containsExactlyInAnyOrder(tuple(user.getLogin(), asList("john1", "john2")));
}
@Test
public void return_tokens_count_when_system_administer() {
UserDto user = db.users().insertUser();
db.users().insertToken(user);
db.users().insertToken(user);
userSession.logIn().setSystemAdministrator();
assertThat(ws.newRequest()
.executeProtobuf(SearchWsResponse.class).getUsersList())
.extracting(User::getLogin, User::getTokensCount)
.containsExactlyInAnyOrder(tuple(user.getLogin(), 2));
userSession.logIn();
assertThat(ws.newRequest()
.executeProtobuf(SearchWsResponse.class).getUsersList())
.extracting(User::getLogin, User::hasTokensCount)
.containsExactlyInAnyOrder(tuple(user.getLogin(), false));
}
@Test
public void return_email_only_when_system_administer() {
UserDto user = db.users().insertUser();
userSession.logIn().setSystemAdministrator();
assertThat(ws.newRequest()
.executeProtobuf(SearchWsResponse.class).getUsersList())
.extracting(User::getLogin, User::getEmail)
.containsExactlyInAnyOrder(tuple(user.getLogin(), user.getEmail()));
userSession.logIn();
assertThat(ws.newRequest()
.executeProtobuf(SearchWsResponse.class).getUsersList())
.extracting(User::getLogin, User::hasEmail)
.containsExactlyInAnyOrder(tuple(user.getLogin(), false));
}
@Test
public void return_user_not_having_email() {
UserDto user = db.users().insertUser(u -> u.setEmail(null));
userSession.logIn().setSystemAdministrator();
SearchWsResponse response = ws.newRequest()
.executeProtobuf(SearchWsResponse.class);
assertThat(response.getUsersList())
.extracting(User::getLogin, User::hasEmail)
.containsExactlyInAnyOrder(tuple(user.getLogin(), false));
}
@Test
public void return_groups_only_when_system_administer() {
UserDto user = db.users().insertUser();
GroupDto group1 = db.users().insertGroup("group1");
GroupDto group2 = db.users().insertGroup("group2");
GroupDto group3 = db.users().insertGroup("group3");
db.users().insertMember(group1, user);
db.users().insertMember(group2, user);
userSession.logIn().setSystemAdministrator();
assertThat(ws.newRequest()
.executeProtobuf(SearchWsResponse.class).getUsersList())
.extracting(User::getLogin, u -> u.getGroups().getGroupsList())
.containsExactlyInAnyOrder(tuple(user.getLogin(), asList(group1.getName(), group2.getName())));
userSession.logIn();
assertThat(ws.newRequest()
.executeProtobuf(SearchWsResponse.class).getUsersList())
.extracting(User::getLogin, User::hasGroups)
.containsExactlyInAnyOrder(tuple(user.getLogin(), false));
}
@Test
public void return_external_information() {
UserDto user = db.users().insertUser();
userSession.logIn().setSystemAdministrator();
SearchWsResponse response = ws.newRequest()
.executeProtobuf(SearchWsResponse.class);
assertThat(response.getUsersList())
.extracting(User::getLogin, User::getExternalIdentity, User::getExternalProvider)
.containsExactlyInAnyOrder(tuple(user.getLogin(), user.getExternalLogin(), user.getExternalIdentityProvider()));
}
@Test
public void return_external_identity_only_when_system_administer() {
UserDto user = db.users().insertUser();
userSession.logIn().setSystemAdministrator();
assertThat(ws.newRequest()
.executeProtobuf(SearchWsResponse.class).getUsersList())
.extracting(User::getLogin, User::getExternalIdentity)
.containsExactlyInAnyOrder(tuple(user.getLogin(), user.getExternalLogin()));
userSession.logIn();
assertThat(ws.newRequest()
.executeProtobuf(SearchWsResponse.class).getUsersList())
.extracting(User::getLogin, User::hasExternalIdentity)
.containsExactlyInAnyOrder(tuple(user.getLogin(), false));
}
@Test
public void only_return_login_and_name_when_not_logged() {
UserDto user = db.users().insertUser();
db.users().insertToken(user);
GroupDto group = db.users().insertGroup();
db.users().insertMember(group, user);
userSession.anonymous();
SearchWsResponse response = ws.newRequest()
.executeProtobuf(SearchWsResponse.class);
assertThat(response.getUsersList())
.extracting(User::getLogin, User::getName, User::hasTokensCount, User::hasScmAccounts, User::hasAvatar, User::hasGroups, User::hasManaged)
.containsExactlyInAnyOrder(tuple(user.getLogin(), user.getName(), false, false, false, false, false));
}
@Test
public void return_last_connection_date_when_system_administer() {
UserDto userWithLastConnectionDate = db.users().insertUser();
db.users().updateLastConnectionDate(userWithLastConnectionDate, 10_000_000_000L);
UserDto userWithoutLastConnectionDate = db.users().insertUser();
userSession.logIn().setSystemAdministrator();
SearchWsResponse response = ws.newRequest()
.executeProtobuf(SearchWsResponse.class);
assertThat(response.getUsersList())
.extracting(User::getLogin, User::hasLastConnectionDate, User::getLastConnectionDate)
.containsExactlyInAnyOrder(
tuple(userWithLastConnectionDate.getLogin(), true, formatDateTime(10_000_000_000L)),
tuple(userWithoutLastConnectionDate.getLogin(), false, ""));
}
@Test
public void return_all_fields_for_logged_user() {
UserDto user = db.users().insertUser();
db.users().updateLastConnectionDate(user, 10_000_000_000L);
db.users().insertToken(user);
db.users().insertToken(user);
GroupDto group = db.users().insertGroup();
db.users().insertMember(group, user);
UserDto otherUser = db.users().insertUser();
userSession.logIn(user);
assertThat(ws.newRequest().setParam("q", user.getLogin())
.executeProtobuf(SearchWsResponse.class).getUsersList())
.extracting(User::getLogin, User::getName, User::getEmail, User::getExternalIdentity, User::getExternalProvider,
User::hasScmAccounts, User::hasAvatar, User::hasGroups, User::getTokensCount, User::hasLastConnectionDate, User::hasManaged)
.containsExactlyInAnyOrder(
tuple(user.getLogin(), user.getName(), user.getEmail(), user.getExternalLogin(), user.getExternalIdentityProvider(), true, true, true, 2, true, true));
userSession.logIn(otherUser);
assertThat(ws.newRequest().setParam("q", user.getLogin())
.executeProtobuf(SearchWsResponse.class).getUsersList())
.extracting(User::getLogin, User::getName, User::hasEmail, User::hasExternalIdentity, User::hasExternalProvider,
User::hasScmAccounts, User::hasAvatar, User::hasGroups, User::hasTokensCount, User::hasLastConnectionDate)
.containsExactlyInAnyOrder(
tuple(user.getLogin(), user.getName(), false, false, true, true, true, false, false, false));
}
@Test
public void search_whenNoPagingInformationProvided_setsDefaultValues() {
userSession.logIn();
IntStream.rangeClosed(0, 9).forEach(i -> db.users().insertUser(u -> u.setLogin("user-" + i).setName("User " + i)));
SearchWsResponse response = ws.newRequest()
.executeProtobuf(SearchWsResponse.class);
assertThat(response.getPaging().getTotal()).isEqualTo(10);
assertThat(response.getPaging().getPageIndex()).isEqualTo(1);
assertThat(response.getPaging().getPageSize()).isEqualTo(50);
}
@Test
public void search_with_paging() {
userSession.logIn();
IntStream.rangeClosed(0, 9).forEach(i -> db.users().insertUser(u -> u.setLogin("user-" + i).setName("User " + i)));
SearchWsResponse response = ws.newRequest()
.setParam(Param.PAGE_SIZE, "5")
.executeProtobuf(SearchWsResponse.class);
assertThat(response.getUsersList())
.extracting(User::getLogin)
.containsExactly("user-0", "user-1", "user-2", "user-3", "user-4");
assertThat(response.getPaging())
.extracting(Paging::getPageIndex, Paging::getPageSize, Paging::getTotal)
.containsExactly(1, 5, 10);
response = ws.newRequest()
.setParam(Param.PAGE_SIZE, "5")
.setParam(Param.PAGE, "2")
.executeProtobuf(SearchWsResponse.class);
assertThat(response.getUsersList())
.extracting(User::getLogin)
.containsExactly("user-5", "user-6", "user-7", "user-8", "user-9");
assertThat(response.getPaging())
.extracting(Paging::getPageIndex, Paging::getPageSize, Paging::getTotal)
.containsExactly(2, 5, 10);
}
@Test
public void return_empty_result_when_no_user() {
userSession.logIn();
SearchWsResponse response = ws.newRequest()
.executeProtobuf(SearchWsResponse.class);
assertThat(response.getUsersList()).isEmpty();
assertThat(response.getPaging().getTotal()).isZero();
}
@Test
public void test_json_example() {
UserDto fmallet = db.users().insertUser(u -> u.setLogin("fmallet").setName("Freddy Mallet").setEmail("f@m.com")
.setLocal(true)
.setScmAccounts(emptyList())
.setExternalLogin("fmallet")
.setExternalIdentityProvider("sonarqube"));
long lastConnection = DateUtils.parseOffsetDateTime("2019-03-27T09:51:50+0100").toInstant().toEpochMilli();
fmallet = db.users().updateLastConnectionDate(fmallet, lastConnection);
fmallet = db.users().updateSonarLintLastConnectionDate(fmallet, lastConnection);
UserDto simon = db.users().insertUser(u -> u.setLogin("sbrandhof").setName("Simon").setEmail("s.brandhof@company.tld")
.setLocal(false)
.setExternalLogin("sbrandhof@ldap.com")
.setExternalIdentityProvider("sonarqube")
.setScmAccounts(asList("simon.brandhof", "s.brandhof@company.tld")));
mockUsersAsManaged(simon.getUuid());
GroupDto sonarUsers = db.users().insertGroup("sonar-users");
GroupDto sonarAdministrators = db.users().insertGroup("sonar-administrators");
db.users().insertMember(sonarUsers, simon);
db.users().insertMember(sonarUsers, fmallet);
db.users().insertMember(sonarAdministrators, fmallet);
db.users().insertToken(simon);
db.users().insertToken(simon);
db.users().insertToken(simon);
db.users().insertToken(fmallet);
userSession.logIn().setSystemAdministrator();
String response = ws.newRequest().execute().getInput();
assertJson(response).isSimilarTo(getClass().getResource("search-example.json"));
}
@Test
public void test_definition() {
WebService.Action action = ws.getDef();
assertThat(action).isNotNull();
assertThat(action.isPost()).isFalse();
assertThat(action.responseExampleAsString()).isNotEmpty();
assertThat(action.params()).hasSize(9);
}
@Test
public void search_whenFilteringConnectionDate_shouldApplyFilter() {
userSession.logIn().setSystemAdministrator();
final Instant lastConnection = Instant.now();
UserDto user = db.users().insertUser(u -> u
.setLogin("user-%_%-login")
.setName("user-name")
.setEmail("user@mail.com")
.setLocal(true)
.setScmAccounts(singletonList("user1")));
user = db.users().updateLastConnectionDate(user, lastConnection.toEpochMilli());
user = db.users().updateSonarLintLastConnectionDate(user, lastConnection.toEpochMilli());
assertThat(ws.newRequest()
.setParam("q", "user-%_%-")
.executeProtobuf(SearchWsResponse.class).getUsersList())
.extracting(User::getLogin)
.containsExactlyInAnyOrder(user.getLogin());
assertUserWithFilter(SearchAction.LAST_CONNECTION_DATE_FROM, lastConnection.minus(1, ChronoUnit.DAYS), user.getLogin(), true);
assertUserWithFilter(SearchAction.LAST_CONNECTION_DATE_FROM, lastConnection.plus(1, ChronoUnit.DAYS), user.getLogin(), false);
assertUserWithFilter(SearchAction.LAST_CONNECTION_DATE_TO, lastConnection.minus(1, ChronoUnit.DAYS), user.getLogin(), false);
assertUserWithFilter(SearchAction.LAST_CONNECTION_DATE_TO, lastConnection.plus(1, ChronoUnit.DAYS), user.getLogin(), true);
assertUserWithFilter(SearchAction.SONAR_LINT_LAST_CONNECTION_DATE_FROM, lastConnection.minus(1, ChronoUnit.DAYS), user.getLogin(), true);
assertUserWithFilter(SearchAction.SONAR_LINT_LAST_CONNECTION_DATE_FROM, lastConnection.plus(1, ChronoUnit.DAYS), user.getLogin(), false);
assertUserWithFilter(SearchAction.SONAR_LINT_LAST_CONNECTION_DATE_TO, lastConnection.minus(1, ChronoUnit.DAYS), user.getLogin(), false);
assertUserWithFilter(SearchAction.SONAR_LINT_LAST_CONNECTION_DATE_TO, lastConnection.plus(1, ChronoUnit.DAYS), user.getLogin(), true);
assertUserWithFilter(SearchAction.SONAR_LINT_LAST_CONNECTION_DATE_FROM, lastConnection, user.getLogin(), true);
assertUserWithFilter(SearchAction.SONAR_LINT_LAST_CONNECTION_DATE_TO, lastConnection, user.getLogin(), true);
}
@Test
public void search_whenNoLastConnection_shouldReturnForBeforeOnly() {
userSession.logIn().setSystemAdministrator();
final Instant lastConnection = Instant.now();
UserDto user = db.users().insertUser(u -> u
.setLogin("user-%_%-login")
.setName("user-name")
.setEmail("user@mail.com")
.setLocal(true)
.setScmAccounts(singletonList("user1")));
assertUserWithFilter(SearchAction.LAST_CONNECTION_DATE_FROM, lastConnection, user.getLogin(), false);
assertUserWithFilter(SearchAction.LAST_CONNECTION_DATE_TO, lastConnection, user.getLogin(), true);
assertUserWithFilter(SearchAction.SONAR_LINT_LAST_CONNECTION_DATE_FROM, lastConnection, user.getLogin(), false);
assertUserWithFilter(SearchAction.SONAR_LINT_LAST_CONNECTION_DATE_TO, lastConnection, user.getLogin(), true);
}
@Test
public void search_whenNotAdmin_shouldThrowForbidden() {
userSession.logIn();
Stream.of(SearchAction.LAST_CONNECTION_DATE_FROM, SearchAction.LAST_CONNECTION_DATE_TO,
SearchAction.SONAR_LINT_LAST_CONNECTION_DATE_FROM, SearchAction.SONAR_LINT_LAST_CONNECTION_DATE_TO)
.map(param -> ws.newRequest().setParam(param, formatDateTime(OffsetDateTime.now())))
.forEach(SearchActionIT::assertForbiddenException);
}
private static void assertForbiddenException(TestRequest testRequest) {
assertThatThrownBy(() -> testRequest.executeProtobuf(SearchWsResponse.class))
.asInstanceOf(InstanceOfAssertFactories.type(ServerException.class))
.extracting(ServerException::httpCode)
.isEqualTo(403);
}
private void assertUserWithFilter(String field, Instant filterValue, String userLogin, boolean isExpectedToBeThere) {
var assertion = assertThat(ws.newRequest()
.setParam("q", "user-%_%-")
.setParam(field, DateUtils.formatDateTime(filterValue.toEpochMilli()))
.executeProtobuf(SearchWsResponse.class).getUsersList());
if (isExpectedToBeThere) {
assertion
.extracting(User::getLogin)
.containsExactlyInAnyOrder(userLogin);
} else {
assertion.isEmpty();
}
}
private void mockUsersAsManaged(String... userUuids) {
when(managedInstanceService.getUserUuidToManaged(any(), any())).thenAnswer(invocation ->
{
Set<?> allUsersUuids = invocation.getArgument(1, Set.class);
return allUsersUuids.stream()
.map(userUuid -> (String) userUuid)
.collect(toMap(identity(), userUuid -> Set.of(userUuids).contains(userUuid)));
}
);
}
}
| 24,369 | 40.026936 | 159 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/SetHomepageActionIT.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.user.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.component.TestComponentFinder;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT;
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.sonar.server.user.ws.SetHomepageAction.PARAM_COMPONENT;
import static org.sonar.server.user.ws.SetHomepageAction.PARAM_TYPE;
public class SetHomepageActionIT {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create();
private final DbClient dbClient = db.getDbClient();
private final WsActionTester ws = new WsActionTester(new SetHomepageAction(userSession, dbClient, TestComponentFinder.from(db)));
@Test
public void verify_definition() {
WebService.Action action = ws.getDef();
assertThat(action.key()).isEqualTo("set_homepage");
assertThat(action.isInternal()).isTrue();
assertThat(action.isPost()).isTrue();
assertThat(action.since()).isEqualTo("7.0");
assertThat(action.description()).isEqualTo("Set homepage of current user.<br> Requires authentication.");
assertThat(action.responseExample()).isNull();
assertThat(action.params()).hasSize(3);
WebService.Param typeParam = action.param("type");
assertThat(typeParam.isRequired()).isTrue();
assertThat(typeParam.description()).isEqualTo("Type of the requested page");
WebService.Param componentParam = action.param("component");
assertThat(componentParam.isRequired()).isFalse();
assertThat(componentParam.description()).isEqualTo("Project key. It should only be used when parameter 'type' is set to 'PROJECT'");
assertThat(componentParam.since()).isEqualTo("7.1");
WebService.Param branchParam = action.param("branch");
assertThat(branchParam.isRequired()).isFalse();
assertThat(branchParam.description()).isEqualTo("Branch key. It can only be used when parameter 'type' is set to 'PROJECT'");
assertThat(branchParam.since()).isEqualTo("7.1");
}
@Test
public void set_project_homepage() {
ComponentDto mainBranch = db.components().insertPrivateProject().getMainBranchComponent();
UserDto user = db.users().insertUser();
userSession.logIn(user);
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TYPE, "PROJECT")
.setParam("component", mainBranch.getKey())
.execute();
UserDto actual = db.getDbClient().userDao().selectByLogin(db.getSession(), user.getLogin());
assertThat(actual).isNotNull();
assertThat(actual.getHomepageType()).isEqualTo("PROJECT");
assertThat(actual.getHomepageParameter()).isEqualTo(mainBranch.uuid());
}
@Test
public void set_branch_homepage() {
ComponentDto mainBranch = db.components().insertPublicProject().getMainBranchComponent();
String branchName = randomAlphanumeric(248);
ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setKey(branchName));
UserDto user = db.users().insertUser();
userSession.logIn(user);
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TYPE, "PROJECT")
.setParam("component", branch.getKey())
.setParam("branch", branchName)
.execute();
UserDto actual = db.getDbClient().userDao().selectByLogin(db.getSession(), user.getLogin());
assertThat(actual).isNotNull();
assertThat(actual.getHomepageType()).isEqualTo("PROJECT");
assertThat(actual.getHomepageParameter()).isEqualTo(branch.uuid());
}
@Test
public void set_issues_homepage() {
UserDto user = db.users().insertUser();
userSession.logIn(user);
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TYPE, "ISSUES")
.execute();
UserDto actual = db.getDbClient().userDao().selectByLogin(db.getSession(), user.getLogin());
assertThat(actual).isNotNull();
assertThat(actual.getHomepageType()).isEqualTo("ISSUES");
assertThat(actual.getHomepageParameter()).isNullOrEmpty();
}
@Test
public void set_projects_homepage() {
UserDto user = db.users().insertUser();
userSession.logIn(user);
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TYPE, "PROJECTS")
.execute();
UserDto actual = db.getDbClient().userDao().selectByLogin(db.getSession(), user.getLogin());
assertThat(actual).isNotNull();
assertThat(actual.getHomepageType()).isEqualTo("PROJECTS");
assertThat(actual.getHomepageParameter()).isNullOrEmpty();
}
@Test
public void set_portfolios_homepage() {
UserDto user = db.users().insertUser();
userSession.logIn(user);
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TYPE, "PORTFOLIOS")
.execute();
UserDto actual = db.getDbClient().userDao().selectByLogin(db.getSession(), user.getLogin());
assertThat(actual).isNotNull();
assertThat(actual.getHomepageType()).isEqualTo("PORTFOLIOS");
assertThat(actual.getHomepageParameter()).isNullOrEmpty();
}
@Test
public void set_portfolio_homepage() {
ComponentDto portfolio = db.components().insertPrivatePortfolio();
UserDto user = db.users().insertUser();
userSession.logIn(user);
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TYPE, "PORTFOLIO")
.setParam(PARAM_COMPONENT, portfolio.getKey())
.execute();
UserDto actual = db.getDbClient().userDao().selectByLogin(db.getSession(), user.getLogin());
assertThat(actual).isNotNull();
assertThat(actual.getHomepageType()).isEqualTo("PORTFOLIO");
assertThat(actual.getHomepageParameter()).isEqualTo(portfolio.uuid());
}
@Test
public void set_application_homepage() {
ComponentDto application = db.components().insertPrivateApplication().getMainBranchComponent();
UserDto user = db.users().insertUser();
userSession.logIn(user);
ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TYPE, "APPLICATION")
.setParam(PARAM_COMPONENT, application.getKey())
.execute();
UserDto actual = db.getDbClient().userDao().selectByLogin(db.getSession(), user.getLogin());
assertThat(actual).isNotNull();
assertThat(actual.getHomepageType()).isEqualTo("APPLICATION");
assertThat(actual.getHomepageParameter()).isEqualTo(application.uuid());
}
@Test
public void response_has_no_content() {
UserDto user = db.users().insertUser();
userSession.logIn(user);
TestResponse response = ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TYPE, "PROJECTS")
.execute();
assertThat(response.getStatus()).isEqualTo(SC_NO_CONTENT);
assertThat(response.getInput()).isEmpty();
}
@Test
public void fail_when_missing_project_key_when_requesting_project_type() {
UserDto user = db.users().insertUser();
userSession.logIn(user);
assertThatThrownBy(() -> ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TYPE, "PROJECT")
.execute())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Type PROJECT requires a parameter");
}
@Test
public void fail_when_invalid_homepage_type() {
UserDto user = db.users().insertUser();
userSession.logIn(user);
assertThatThrownBy(() -> ws.newRequest()
.setMethod("POST")
.setParam(PARAM_TYPE, "PIPO")
.execute())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Value of parameter 'type' (PIPO) must be one of: [PROJECT, PROJECTS, ISSUES, PORTFOLIOS, PORTFOLIO, APPLICATION]");
}
@Test
public void fail_for_anonymous() {
userSession.anonymous();
assertThatThrownBy(() -> ws.newRequest()
.setMethod("POST")
.execute())
.isInstanceOf(UnauthorizedException.class)
.hasMessageContaining("Authentication is required");
}
}
| 9,159 | 34.921569 | 144 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/UpdateActionIT.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.user.ws;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.user.UserDto;
import org.sonar.server.authentication.CredentialsLocalAuthentication;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.management.ManagedInstanceChecker;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.user.NewUserNotifier;
import org.sonar.server.user.UserUpdater;
import org.sonar.server.usergroups.DefaultGroupFinder;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import static com.google.common.collect.Lists.newArrayList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
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.sonar.db.user.UserTesting.newUserDto;
public class UpdateActionIT {
private final MapSettings settings = new MapSettings().setProperty("sonar.internal.pbkdf2.iterations", "1");
private final System2 system2 = new System2();
@Rule
public DbTester db = DbTester.create(system2);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone().logIn().setSystemAdministrator();
private final DbClient dbClient = db.getDbClient();
private final DbSession dbSession = db.getSession();
private final CredentialsLocalAuthentication localAuthentication = new CredentialsLocalAuthentication(db.getDbClient(), settings.asConfig());
private final ManagedInstanceChecker managedInstanceChecker = mock(ManagedInstanceChecker.class);
private final WsActionTester ws = new WsActionTester(new UpdateAction(
new UserUpdater(mock(NewUserNotifier.class), dbClient, new DefaultGroupFinder(db.getDbClient()), settings.asConfig(), null, localAuthentication),
userSession, new UserJsonWriter(userSession), dbClient, managedInstanceChecker));
@Before
public void setUp() {
db.users().insertDefaultGroup();
}
@Test
public void update_user() {
createUser();
ws.newRequest()
.setParam("login", "john")
.setParam("name", "Jon Snow")
.setParam("email", "jon.snow@thegreatw.all")
.execute()
.assertJson(getClass(), "update_user.json");
}
@Test
public void fail_on_update_name_non_local_user() {
createUser(false);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam("login", "john")
.setParam("name", "Jean Neige")
.execute();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Name cannot be updated for a non-local user");
}
@Test
public void fail_on_update_email_non_local_user() {
createUser(false);
assertThatThrownBy(() -> {
ws.newRequest()
.setParam("login", "john")
.setParam("email", "jean.neige@thegreatw.all")
.execute();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Email cannot be updated for a non-local user");
}
@Test
public void update_only_name() {
createUser();
ws.newRequest()
.setParam("login", "john")
.setParam("name", "Jon Snow")
.execute()
.assertJson(getClass(), "update_name.json");
}
@Test
public void update_only_email() {
createUser();
ws.newRequest()
.setParam("login", "john")
.setParam("email", "jon.snow@thegreatw.all")
.execute()
.assertJson(getClass(), "update_email.json");
}
@Test
public void blank_email_is_updated_to_null() {
createUser();
ws.newRequest()
.setParam("login", "john")
.setParam("email", "")
.execute()
.assertJson(getClass(), "blank_email_is_updated_to_null.json");
UserDto userDto = dbClient.userDao().selectByLogin(dbSession, "john");
assertThat(userDto.getEmail()).isNull();
}
@Test
public void remove_scm_accounts() {
createUser();
ws.newRequest()
.setParam("login", "john")
.setMultiParam("scmAccount", singletonList(""))
.execute();
UserDto userDto = dbClient.userDao().selectByLogin(dbSession, "john");
assertThat(userDto.getSortedScmAccounts()).isEmpty();
}
@Test
public void update_only_scm_accounts() {
createUser();
ws.newRequest()
.setParam("login", "john")
.setMultiParam("scmAccount", singletonList("jon.snow"))
.execute()
.assertJson(getClass(), "update_scm_accounts.json");
UserDto user = dbClient.userDao().selectByLogin(dbSession, "john");
assertThat(user.getSortedScmAccounts()).containsOnly("jon.snow");
}
@Test
public void update_scm_account() {
createUser();
ws.newRequest()
.setParam("login", "john")
.setMultiParam("scmAccount", List.of("jon", "snow"))
.execute();
UserDto user = dbClient.userDao().selectByLogin(dbSession, "john");
assertThat(user.getSortedScmAccounts()).containsExactly("jon", "snow");
}
@Test
public void fail_when_duplicates_characters_in_scm_account_values() {
createUser();
assertThatThrownBy(() -> {
ws.newRequest()
.setParam("login", "john")
.setMultiParam("scmAccount", Arrays.asList("jon.snow", "jon.snow", "jon.jon", "jon.snow"))
.execute();
}).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Duplicate SCM account: 'jon.snow'");
;
}
@Test
public void fail_when_whitespace_characters_in_scm_account_values() {
createUser();
assertThatThrownBy(() -> {
ws.newRequest()
.setParam("login", "john")
.setMultiParam("scmAccount", Arrays.asList("jon.snow", "jon.snow", "jon.jon", " jon.snow "))
.execute();
}).isInstanceOf(IllegalArgumentException.class)
.hasMessage("SCM account cannot start or end with whitespace: ' jon.snow '");
;
}
@Test
public void update_scm_account_ordered_case_insensitive() {
createUser();
ws.newRequest()
.setParam("login", "john")
.setMultiParam("scmAccount", Arrays.asList("jon.3", "Jon.1", "JON.2"))
.execute();
UserDto user = dbClient.userDao().selectByLogin(dbSession, "john");
assertThat(user.getSortedScmAccounts()).containsExactly("jon.1", "jon.2", "jon.3");
}
@Test
public void fail_on_missing_permission() {
createUser();
userSession.logIn("polop");
assertThatThrownBy(() -> {
ws.newRequest()
.setParam("login", "john")
.execute();
})
.isInstanceOf(ForbiddenException.class);
}
@Test
public void fail_on_unknown_user() {
assertThatThrownBy(() -> {
ws.newRequest()
.setParam("login", "john")
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage("User 'john' doesn't exist");
}
@Test
public void fail_on_disabled_user() {
db.users().insertUser(u -> u.setLogin("john").setActive(false));
TestRequest request = ws.newRequest()
.setParam("login", "john");
assertThatThrownBy(() -> {
request.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage("User 'john' doesn't exist");
}
@Test
public void fail_on_invalid_email() {
createUser();
TestRequest request = ws.newRequest()
.setParam("login", "john")
.setParam("email", "invalid-email");
assertThatThrownBy(() -> {
request.execute();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Email 'invalid-email' is not valid");
}
@Test
public void handle_whenInstanceManaged_shouldThrowBadRequestException() {
BadRequestException badRequestException = BadRequestException.create("message");
doThrow(badRequestException).when(managedInstanceChecker).throwIfInstanceIsManaged();
TestRequest updateRequest = ws.newRequest();
assertThatThrownBy(updateRequest::execute)
.isEqualTo(badRequestException);
}
@Test
public void handle_whenInstanceManagedAndNotSystemAdministrator_shouldThrowUnauthorizedException() {
userSession.anonymous();
TestRequest updateRequest = ws.newRequest();
assertThatThrownBy(updateRequest::execute)
.isInstanceOf(UnauthorizedException.class)
.hasMessage("Authentication is required");
verify(managedInstanceChecker, never()).throwIfInstanceIsManaged();
}
@Test
public void test_definition() {
WebService.Action action = ws.getDef();
assertThat(action).isNotNull();
assertThat(action.isPost()).isTrue();
assertThat(action.params()).hasSize(4);
}
private void createUser() {
createUser(true);
}
private void createUser(boolean local) {
UserDto userDto = newUserDto()
.setEmail("john@email.com")
.setLogin("john")
.setName("John")
.setScmAccounts(newArrayList("jn"))
.setActive(true)
.setLocal(local)
.setExternalLogin("jo")
.setExternalIdentityProvider("sonarqube");
dbClient.userDao().insert(dbSession, userDto);
dbSession.commit();
}
}
| 10,401 | 29.684366 | 149 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/UpdateIdentityProviderActionIT.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.user.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.user.UserDto;
import org.sonar.server.authentication.CredentialsLocalAuthentication;
import org.sonar.server.authentication.IdentityProviderRepositoryRule;
import org.sonar.server.authentication.TestIdentityProvider;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.management.ManagedInstanceChecker;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.user.NewUserNotifier;
import org.sonar.server.user.UserUpdater;
import org.sonar.server.usergroups.DefaultGroupFinder;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
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.sonar.db.user.UserTesting.newUserDto;
public class UpdateIdentityProviderActionIT {
private final static String SQ_AUTHORITY = "sonarqube";
@Rule
public IdentityProviderRepositoryRule identityProviderRepository = new IdentityProviderRepositoryRule()
.addIdentityProvider(new TestIdentityProvider().setName("Gitlab").setKey("gitlab").setEnabled(true))
.addIdentityProvider(new TestIdentityProvider().setName("Github").setKey("github").setEnabled(true));
@Rule
public DbTester db = DbTester.create();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone().logIn().setSystemAdministrator();
private final MapSettings settings = new MapSettings().setProperty("sonar.internal.pbkdf2.iterations", "1");
private final DbClient dbClient = db.getDbClient();
private final DbSession dbSession = db.getSession();
private final CredentialsLocalAuthentication localAuthentication = new CredentialsLocalAuthentication(dbClient, settings.asConfig());
private final ManagedInstanceChecker managedInstanceChecker = mock(ManagedInstanceChecker.class);
private final WsActionTester underTest = new WsActionTester(new UpdateIdentityProviderAction(dbClient, identityProviderRepository,
new UserUpdater(mock(NewUserNotifier.class), dbClient, new DefaultGroupFinder(db.getDbClient()), settings.asConfig(), null, localAuthentication),
userSession, managedInstanceChecker));
@Test
public void change_identity_provider_of_a_local_user_all_params() {
String userLogin = "login-1";
String newExternalLogin = "login@github.com";
String newExternalIdentityProvider = "github";
createUser(true, userLogin, userLogin, SQ_AUTHORITY);
TestRequest request = underTest.newRequest()
.setParam("login", userLogin)
.setParam("newExternalProvider", newExternalIdentityProvider)
.setParam("newExternalIdentity", newExternalLogin);
request.execute();
assertThat(dbClient.userDao().selectByExternalLoginAndIdentityProvider(dbSession, newExternalLogin, newExternalIdentityProvider))
.isNotNull()
.extracting(UserDto::isLocal, UserDto::getExternalLogin, UserDto::getExternalIdentityProvider)
.contains(false, newExternalLogin, newExternalIdentityProvider);
}
@Test
public void change_identity_provider_of_a_local_user_mandatory_params_only_provider_login_stays_same() {
String userLogin = "login-1";
String newExternalIdentityProvider = "github";
createUser(true, userLogin, userLogin, SQ_AUTHORITY);
TestRequest request = underTest.newRequest()
.setParam("login", userLogin)
.setParam("newExternalProvider", newExternalIdentityProvider);
request.execute();
assertThat(dbClient.userDao().selectByExternalLoginAndIdentityProvider(dbSession, userLogin, newExternalIdentityProvider))
.isNotNull()
.extracting(UserDto::isLocal, UserDto::getExternalLogin, UserDto::getExternalIdentityProvider)
.contains(false, userLogin, newExternalIdentityProvider);
}
@Test
public void change_identity_provider_of_a_external_user_to_new_one() {
String userLogin = "login-1";
String oldExternalIdentityProvider = "gitlab";
String oldExternalIdentity = "john@gitlab.com";
createUser(false, userLogin, oldExternalIdentity, oldExternalIdentityProvider);
String newExternalIdentityProvider = "github";
String newExternalIdentity = "john@github.com";
TestRequest request = underTest.newRequest()
.setParam("login", userLogin)
.setParam("newExternalProvider", newExternalIdentityProvider)
.setParam("newExternalIdentity", newExternalIdentity);
request.execute();
assertThat(dbClient.userDao().selectByExternalLoginAndIdentityProvider(dbSession, newExternalIdentity, newExternalIdentityProvider))
.isNotNull()
.extracting(UserDto::isLocal, UserDto::getExternalLogin, UserDto::getExternalIdentityProvider)
.contains(false, newExternalIdentity, newExternalIdentityProvider);
}
@Test
public void change_identity_provider_of_a_local_user_to_ldap_default_using_sonarqube_as_parameter() {
String userLogin = "login-1";
String newExternalIdentityProvider = "LDAP_default";
createUser(true, userLogin, userLogin, SQ_AUTHORITY);
TestRequest request = underTest.newRequest()
.setParam("login", userLogin)
.setParam("newExternalProvider", "sonarqube");
request.execute();
assertThat(dbClient.userDao().selectByExternalLoginAndIdentityProvider(dbSession, userLogin, newExternalIdentityProvider))
.isNotNull()
.extracting(UserDto::isLocal, UserDto::getExternalLogin, UserDto::getExternalIdentityProvider)
.contains(false, userLogin, newExternalIdentityProvider);
}
@Test
public void change_identity_provider_of_a_local_user_to_ldap_default_using_ldap_as_parameter() {
String userLogin = "login-1";
String newExternalIdentityProvider = "LDAP_default";
createUser(true, userLogin, userLogin, SQ_AUTHORITY);
TestRequest request = underTest.newRequest()
.setParam("login", userLogin)
.setParam("newExternalProvider", "LDAP");
request.execute();
assertThat(dbClient.userDao().selectByExternalLoginAndIdentityProvider(dbSession, userLogin, newExternalIdentityProvider))
.isNotNull()
.extracting(UserDto::isLocal, UserDto::getExternalLogin, UserDto::getExternalIdentityProvider)
.contains(false, userLogin, newExternalIdentityProvider);
}
@Test
public void change_identity_provider_of_a_local_user_to_ldap_default_using_ldap_server_key_as_parameter() {
String userLogin = "login-1";
String newExternalIdentityProvider = "LDAP_server42";
createUser(true, userLogin, userLogin, SQ_AUTHORITY);
TestRequest request = underTest.newRequest()
.setParam("login", userLogin)
.setParam("newExternalProvider", newExternalIdentityProvider);
request.execute();
assertThat(dbClient.userDao().selectByExternalLoginAndIdentityProvider(dbSession, userLogin, newExternalIdentityProvider))
.isNotNull()
.extracting(UserDto::isLocal, UserDto::getExternalLogin, UserDto::getExternalIdentityProvider)
.contains(false, userLogin, newExternalIdentityProvider);
}
@Test
public void fail_if_user_not_exist() {
TestRequest request = underTest.newRequest()
.setParam("login", "not-existing")
.setParam("newExternalProvider", "gitlab");
assertThatThrownBy(request::execute)
.isInstanceOf(NotFoundException.class)
.hasMessage("User 'not-existing' doesn't exist");
}
@Test
public void fail_if_identity_provider_not_exist() {
createUser(true, "login-1", "login-1", SQ_AUTHORITY);
TestRequest request = underTest.newRequest()
.setParam("login", "login-1")
.setParam("newExternalProvider", "not-existing");
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Value of parameter 'newExternalProvider' (not-existing) must be one of: [github, gitlab] or [LDAP, LDAP_{serverKey}]");
}
@Test
public void fail_if_anonymous() {
userSession.anonymous();
TestRequest request = underTest.newRequest()
.setParam("login", "not-existing")
.setParam("newExternalProvider", "something");
assertThatThrownBy(request::execute)
.isInstanceOf(UnauthorizedException.class);
}
@Test
public void fail_if_not_admin() {
userSession.logIn("some-user");
TestRequest request = underTest.newRequest()
.setParam("login", "not-existing")
.setParam("newExternalProvider", "something");
assertThatThrownBy(request::execute)
.isInstanceOf(ForbiddenException.class);
}
@Test
public void handle_whenInstanceManaged_shouldThrowBadRequestException() {
BadRequestException badRequestException = BadRequestException.create("message");
doThrow(badRequestException).when(managedInstanceChecker).throwIfInstanceIsManaged();
TestRequest request = underTest.newRequest();
assertThatThrownBy(request::execute)
.isEqualTo(badRequestException);
}
@Test
public void handle_whenInstanceManagedAndNotSystemAdministrator_shouldThrowUnauthorizedException() {
userSession.anonymous();
TestRequest request = underTest.newRequest();
assertThatThrownBy(request::execute)
.isInstanceOf(UnauthorizedException.class)
.hasMessage("Authentication is required");
verify(managedInstanceChecker, never()).throwIfInstanceIsManaged();
}
private void createUser(boolean local, String login, String externalLogin, String externalIdentityProvider) {
UserDto userDto = newUserDto()
.setEmail("john@email.com")
.setLogin(login)
.setName("John")
.setScmAccounts(newArrayList("jn"))
.setActive(true)
.setLocal(local)
.setExternalLogin(externalLogin)
.setExternalIdentityProvider(externalIdentityProvider);
dbClient.userDao().insert(dbSession, userDto);
dbSession.commit();
}
}
| 11,209 | 41.623574 | 149 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/UpdateLoginActionIT.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.user.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.management.ManagedInstanceChecker;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.user.NewUserNotifier;
import org.sonar.server.user.UserUpdater;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static java.lang.String.format;
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.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
public class UpdateLoginActionIT {
private final System2 system2 = new System2();
@Rule
public DbTester db = DbTester.create(system2);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone().logIn().setSystemAdministrator();
private final ManagedInstanceChecker managedInstanceChecker = mock(ManagedInstanceChecker.class);
private final WsActionTester ws = new WsActionTester(new UpdateLoginAction(db.getDbClient(), userSession,
new UserUpdater(mock(NewUserNotifier.class), db.getDbClient(), null, null, null, null), managedInstanceChecker));
@Test
public void update_login_from_sonarqube_account_when_user_is_local() {
userSession.logIn().setSystemAdministrator();
UserDto user = db.users().insertUser(u -> u
.setLogin("old_login")
.setLocal(true)
.setExternalIdentityProvider("sonarqube")
.setExternalLogin("old_login")
.setExternalId("old_login"));
ws.newRequest()
.setParam("login", user.getLogin())
.setParam("newLogin", "new_login")
.execute();
assertThat(db.getDbClient().userDao().selectByLogin(db.getSession(), "old_login")).isNull();
UserDto userReloaded = db.getDbClient().userDao().selectByUuid(db.getSession(), user.getUuid());
assertThat(userReloaded.getLogin()).isEqualTo("new_login");
assertThat(userReloaded.getExternalLogin()).isEqualTo("new_login");
assertThat(userReloaded.getExternalId()).isEqualTo("new_login");
assertThat(userReloaded.isLocal()).isTrue();
assertThat(userReloaded.getCryptedPassword()).isNotNull().isEqualTo(user.getCryptedPassword());
assertThat(userReloaded.getSalt()).isNotNull().isEqualTo(user.getSalt());
}
@Test
public void update_login_from_sonarqube_account_when_user_is_not_local() {
userSession.logIn().setSystemAdministrator();
UserDto user = db.users().insertUser(u -> u
.setLogin("old_login")
.setLocal(false)
.setExternalIdentityProvider("sonarqube")
.setExternalLogin("old_login")
.setExternalId("old_login"));
ws.newRequest()
.setParam("login", user.getLogin())
.setParam("newLogin", "new_login")
.execute();
assertThat(db.getDbClient().userDao().selectByLogin(db.getSession(), "old_login")).isNull();
UserDto userReloaded = db.getDbClient().userDao().selectByUuid(db.getSession(), user.getUuid());
assertThat(userReloaded.getLogin()).isEqualTo("new_login");
assertThat(userReloaded.getExternalLogin()).isEqualTo("new_login");
assertThat(userReloaded.getExternalId()).isEqualTo("new_login");
assertThat(userReloaded.isLocal()).isFalse();
assertThat(userReloaded.getCryptedPassword()).isNotNull().isEqualTo(user.getCryptedPassword());
assertThat(userReloaded.getSalt()).isNotNull().isEqualTo(user.getSalt());
}
@Test
public void update_login_from_external_account() {
userSession.logIn().setSystemAdministrator();
UserDto user = db.users().insertUser(u -> u
.setLogin("old_login")
.setLocal(false)
.setExternalIdentityProvider("github")
.setExternalLogin("github_login")
.setExternalId("github_id")
.setCryptedPassword(null)
.setSalt(null));
ws.newRequest()
.setParam("login", user.getLogin())
.setParam("newLogin", "new_login")
.execute();
UserDto userReloaded = db.getDbClient().userDao().selectByUuid(db.getSession(), user.getUuid());
assertThat(userReloaded.getLogin()).isEqualTo("new_login");
assertThat(userReloaded.getExternalLogin()).isEqualTo("github_login");
assertThat(userReloaded.getExternalId()).isEqualTo("github_id");
assertThat(userReloaded.isLocal()).isFalse();
assertThat(userReloaded.getCryptedPassword()).isNull();
assertThat(userReloaded.getSalt()).isNull();
}
@Test
public void fail_with_IAE_when_new_login_is_already_used() {
userSession.logIn().setSystemAdministrator();
UserDto user = db.users().insertUser();
UserDto user2 = db.users().insertUser();
assertThatThrownBy(() -> {
ws.newRequest()
.setParam("login", user.getLogin())
.setParam("newLogin", user2.getLogin())
.execute();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(format("A user with login '%s' already exists", user2.getLogin()));
}
@Test
public void fail_with_NFE_when_login_does_not_match_active_user() {
userSession.logIn().setSystemAdministrator();
UserDto user = db.users().insertDisabledUser();
assertThatThrownBy(() -> {
ws.newRequest()
.setParam("login", user.getLogin())
.setParam("newLogin", "new_login")
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage(format("User '%s' doesn't exist", user.getLogin()));
}
@Test
public void fail_with_NFE_when_login_does_not_match_existing_user() {
userSession.logIn().setSystemAdministrator();
assertThatThrownBy(() -> {
ws.newRequest()
.setParam("login", "unknown")
.setParam("newLogin", "new_login")
.execute();
})
.isInstanceOf(NotFoundException.class)
.hasMessage("User 'unknown' doesn't exist");
}
@Test
public void fail_when_not_system_administrator() {
userSession.logIn();
assertThatThrownBy(() -> {
ws.newRequest()
.setParam("login", "old_login")
.setParam("newLogin", "new_login")
.execute();
})
.isInstanceOf(ForbiddenException.class);
}
@Test
public void response_has_no_content() {
UserDto user = db.users().insertUser();
userSession.logIn().setSystemAdministrator();
TestResponse response = ws.newRequest()
.setParam("login", user.getLogin())
.setParam("newLogin", "new_login")
.execute();
assertThat(response.getStatus()).isEqualTo(204);
assertThat(response.getInput()).isEmpty();
}
@Test
public void handle_whenInstanceManaged_shouldThrowBadRequestException() {
BadRequestException badRequestException = BadRequestException.create("message");
doThrow(badRequestException).when(managedInstanceChecker).throwIfInstanceIsManaged();
TestRequest request = ws.newRequest();
assertThatThrownBy(request::execute)
.isEqualTo(badRequestException);
}
@Test
public void handle_whenInstanceManagedAndNotSystemAdministrator_shouldThrowUnauthorizedException() {
userSession.anonymous();
TestRequest request = ws.newRequest();
assertThatThrownBy(request::execute)
.isInstanceOf(UnauthorizedException.class)
.hasMessage("Authentication is required");
verify(managedInstanceChecker, never()).throwIfInstanceIsManaged();
}
@Test
public void test_definition() {
WebService.Action def = ws.getDef();
assertThat(def.key()).isEqualTo("update_login");
assertThat(def.isPost()).isTrue();
assertThat(def.isInternal()).isFalse();
assertThat(def.since()).isEqualTo("7.6");
assertThat(def.params())
.extracting(Param::key, Param::isRequired, Param::maximumLength, Param::minimumLength)
.containsExactlyInAnyOrder(
tuple("login", true, null, null),
tuple("newLogin", true, 255, 2));
}
}
| 9,216 | 36.016064 | 117 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/user/ws/UserAnonymizerIT.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.user.ws;
import java.util.Iterator;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.user.UserDto;
import org.sonar.server.user.ExternalIdentity;
import static org.assertj.core.api.Assertions.assertThat;
public class UserAnonymizerIT {
private final System2 system2 = new AlwaysIncreasingSystem2();
@Rule
public DbTester db = DbTester.create(system2);
private final UserAnonymizer userAnonymizer = new UserAnonymizer(db.getDbClient());
@Test
public void anonymize_user() {
UserDto user = db.users().insertUser(u -> u.setLogin("login1"));
userAnonymizer.anonymize(db.getSession(), user);
assertThat(user.getLogin()).startsWith("sq-removed-");
assertThat(user.getExternalIdentityProvider()).isEqualTo(ExternalIdentity.SQ_AUTHORITY);
assertThat(user.getExternalId()).isEqualTo(user.getLogin());
assertThat(user.getExternalLogin()).isEqualTo(user.getLogin());
assertThat(user.getName()).isEqualTo(user.getLogin());
}
@Test
public void try_avoid_login_collisions() {
List<String> logins = List.of("login1", "login2", "login3");
Iterator<String> randomGeneratorIt = logins.iterator();
UserAnonymizer userAnonymizer = new UserAnonymizer(db.getDbClient(), randomGeneratorIt::next);
UserDto user1 = db.users().insertUser(u -> u.setLogin("login1"));
UserDto user2 = db.users().insertUser(u -> u.setLogin("login2"));
UserDto userToAnonymize = db.users().insertUser(u -> u.setLogin("toAnonymize").setActive(false));
userAnonymizer.anonymize(db.getSession(), userToAnonymize);
assertThat(userToAnonymize.getLogin()).isEqualTo("login3");
}
}
| 2,647 | 39.121212 | 101 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/usergroups/ws/AddUserActionIT.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.usergroups.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.WebService.Action;
import org.sonar.db.DbTester;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.management.ManagedInstanceChecker;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.usergroups.DefaultGroupFinder;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
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.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER;
import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_GROUP_NAME;
import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_LOGIN;
public class AddUserActionIT {
@Rule
public DbTester db = DbTester.create(new AlwaysIncreasingSystem2());
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private ManagedInstanceChecker managedInstanceChecker = mock(ManagedInstanceChecker.class);
private final WsActionTester ws = new WsActionTester(new AddUserAction(db.getDbClient(), userSession, newGroupWsSupport(), managedInstanceChecker));
@Test
public void verify_definition() {
Action wsDef = ws.getDef();
assertThat(wsDef.isInternal()).isFalse();
assertThat(wsDef.since()).isEqualTo("5.2");
assertThat(wsDef.isPost()).isTrue();
assertThat(wsDef.changelog()).extracting(Change::getVersion, Change::getDescription).containsOnly(
tuple("10.0", "Parameter 'id' is removed. Use 'name' instead."),
tuple("8.4", "Parameter 'id' is deprecated. Format changes from integer to string. Use 'name' instead."));
}
@Test
public void add_user_to_group_referenced_by_its_name() {
insertDefaultGroup();
GroupDto group = db.users().insertGroup();
UserDto user = db.users().insertUser();
loginAsAdmin();
newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
assertThat(db.users().selectGroupUuidsOfUser(user)).containsOnly(group.getUuid());
}
@Test
public void add_user_to_another_group() {
insertDefaultGroup();
GroupDto admins = db.users().insertGroup("admins");
GroupDto users = db.users().insertGroup("users");
UserDto user = db.users().insertUser("my-admin");
db.users().insertMember(users, user);
loginAsAdmin();
newRequest()
.setParam(PARAM_GROUP_NAME, admins.getName())
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
assertThat(db.users().selectGroupUuidsOfUser(user)).containsOnly(admins.getUuid(), users.getUuid());
}
@Test
public void do_not_fail_if_user_is_already_member_of_group() {
insertDefaultGroup();
GroupDto users = db.users().insertGroup();
UserDto user = db.users().insertUser();
db.users().insertMember(users, user);
loginAsAdmin();
newRequest()
.setParam(PARAM_GROUP_NAME, users.getName())
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
// do not insert duplicated row
assertThat(db.users().selectGroupUuidsOfUser(user)).hasSize(1).containsOnly(users.getUuid());
}
@Test
public void group_has_multiple_members() {
insertDefaultGroup();
GroupDto users = db.users().insertGroup();
UserDto user1 = db.users().insertUser();
UserDto user2 = db.users().insertUser();
db.users().insertMember(users, user1);
loginAsAdmin();
newRequest()
.setParam(PARAM_GROUP_NAME, users.getName())
.setParam(PARAM_LOGIN, user2.getLogin())
.execute();
assertThat(db.users().selectGroupUuidsOfUser(user1)).containsOnly(users.getUuid());
assertThat(db.users().selectGroupUuidsOfUser(user2)).containsOnly(users.getUuid());
}
@Test
public void response_status_is_no_content() {
db.users().insertDefaultGroup();
GroupDto group = db.users().insertGroup();
UserDto user = db.users().insertUser();
loginAsAdmin();
TestResponse response = newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
assertThat(response.getStatus()).isEqualTo(HTTP_NO_CONTENT);
}
@Test
public void fail_if_group_does_not_exist() {
UserDto user = db.users().insertUser();
loginAsAdmin();
TestRequest request = newRequest()
.setParam(PARAM_GROUP_NAME, "unknown")
.setParam(PARAM_LOGIN, user.getLogin());
assertThatThrownBy(request::execute)
.isInstanceOf(NotFoundException.class)
.hasMessage("No group with name 'unknown'");
}
@Test
public void fail_if_user_does_not_exist() {
GroupDto group = db.users().insertGroup("admins");
loginAsAdmin();
TestRequest request = newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam(PARAM_LOGIN, "my-admin");
assertThatThrownBy(request::execute)
.isInstanceOf(NotFoundException.class)
.hasMessage("Could not find a user with login 'my-admin'");
}
@Test
public void fail_if_not_administrator() {
GroupDto group = db.users().insertGroup();
UserDto user = db.users().insertUser();
assertThatThrownBy(() -> {
executeRequest(group, user);
})
.isInstanceOf(UnauthorizedException.class);
}
@Test
public void fail_to_add_user_to_default_group() {
UserDto user = db.users().insertUser();
GroupDto defaultGroup = db.users().insertDefaultGroup();
loginAsAdmin();
TestRequest request = newRequest()
.setParam(PARAM_GROUP_NAME, defaultGroup.getName())
.setParam(PARAM_LOGIN, user.getLogin());
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Default group 'sonar-users' cannot be used to perform this action");
}
@Test
public void fail_when_no_default_group() {
GroupDto group = db.users().insertGroup();
UserDto user = db.users().insertUser();
loginAsAdmin();
TestRequest request = newRequest()
.setParam(PARAM_LOGIN, user.getLogin())
.setParam(PARAM_GROUP_NAME, group.getName());
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalStateException.class)
.hasMessage("Default group cannot be found");
}
@Test
public void fail_if_instance_is_externally_managed() {
loginAsAdmin();
BadRequestException exception = BadRequestException.create("Not allowed");
doThrow(exception).when(managedInstanceChecker).throwIfInstanceIsManaged();
TestRequest testRequest = newRequest()
.setParam("name", "long-desc");
assertThatThrownBy(testRequest::execute)
.isEqualTo(exception);
}
private void executeRequest(GroupDto groupDto, UserDto userDto) {
newRequest()
.setParam(PARAM_GROUP_NAME, groupDto.getName())
.setParam(PARAM_LOGIN, userDto.getLogin())
.execute();
}
private TestRequest newRequest() {
return ws.newRequest();
}
private void loginAsAdmin() {
userSession.logIn().addPermission(ADMINISTER);
}
private void insertDefaultGroup() {
db.users().insertDefaultGroup();
}
private GroupWsSupport newGroupWsSupport() {
return new GroupWsSupport(db.getDbClient(), new DefaultGroupFinder(db.getDbClient()));
}
}
| 8,686 | 32.933594 | 150 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/usergroups/ws/CreateActionIT.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.usergroups.ws;
import org.apache.commons.lang.StringUtils;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.core.util.SequenceUuidFactory;
import org.sonar.db.DbTester;
import org.sonar.db.user.GroupDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.ServerException;
import org.sonar.server.management.ManagedInstanceChecker;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
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.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER;
public class CreateActionIT {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private ManagedInstanceChecker managedInstanceChecker = mock(ManagedInstanceChecker.class);
private final CreateAction underTest = new CreateAction(db.getDbClient(), userSession, newGroupService(), managedInstanceChecker);
private final WsActionTester tester = new WsActionTester(underTest);
@Test
public void define_create_action() {
WebService.Action action = tester.getDef();
assertThat(action).isNotNull();
assertThat(action.key()).isEqualTo("create");
assertThat(action.isPost()).isTrue();
assertThat(action.responseExampleAsString()).isNotEmpty();
assertThat(action.params()).hasSize(2);
assertThat(action.changelog()).extracting(Change::getVersion, Change::getDescription).containsOnly(
tuple("8.4", "Field 'id' format in the response changes from integer to string."));
}
@Test
public void create_group() {
loginAsAdmin();
tester.newRequest()
.setParam("name", "some-product-bu")
.setParam("description", "Business Unit for Some Awesome Product")
.execute()
.assertJson("{" +
" \"group\": {" +
" \"name\": \"some-product-bu\"," +
" \"description\": \"Business Unit for Some Awesome Product\"," +
" \"membersCount\": 0" +
" }" +
"}");
assertThat(db.users().selectGroup("some-product-bu")).isPresent();
}
@Test
public void return_default_field() {
loginAsAdmin();
tester.newRequest()
.setParam("name", "some-product-bu")
.setParam("description", "Business Unit for Some Awesome Product")
.execute()
.assertJson("{" +
" \"group\": {" +
" \"name\": \"some-product-bu\"," +
" \"description\": \"Business Unit for Some Awesome Product\"," +
" \"membersCount\": 0," +
" \"default\": false" +
" }" +
"}");
}
@Test
public void fail_if_not_administrator() {
userSession.logIn("not-admin");
assertThatThrownBy(() -> {
tester.newRequest()
.setParam("name", "some-product-bu")
.setParam("description", "Business Unit for Some Awesome Product")
.execute();
})
.isInstanceOf(ForbiddenException.class);
}
@Test
public void fail_if_name_is_too_short() {
loginAsAdmin();
assertThatThrownBy(() -> {
tester.newRequest()
.setParam("name", "")
.execute();
})
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void fail_if_name_is_too_long() {
loginAsAdmin();
assertThatThrownBy(() -> {
tester.newRequest()
.setParam("name", StringUtils.repeat("a", 255 + 1))
.execute();
})
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void fail_if_name_is_anyone() {
loginAsAdmin();
assertThatThrownBy(() -> {
tester.newRequest()
.setParam("name", "AnYoNe")
.execute();
})
.isInstanceOf(BadRequestException.class);
}
@Test
public void fail_if_group_with_same_name_already_exists() {
GroupDto group = db.users().insertGroup();
loginAsAdmin();
assertThatThrownBy(() -> {
tester.newRequest()
.setParam("name", group.getName())
.execute();
})
.isInstanceOf(ServerException.class)
.hasMessage("Group '" + group.getName() + "' already exists");
}
@Test
public void fail_if_description_is_too_long() {
loginAsAdmin();
assertThatThrownBy(() -> {
tester.newRequest()
.setParam("name", "long-desc")
.setParam("description", StringUtils.repeat("a", 1_000))
.execute();
})
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void fail_if_instance_is_externally_managed() {
loginAsAdmin();
BadRequestException exception = BadRequestException.create("Not allowed");
doThrow(exception).when(managedInstanceChecker).throwIfInstanceIsManaged();
TestRequest testRequest = tester.newRequest();
assertThatThrownBy(testRequest::execute)
.isEqualTo(exception);
}
private void loginAsAdmin() {
userSession.logIn().addPermission(ADMINISTER);
}
private GroupService newGroupService() {
return new GroupService(db.getDbClient(), new SequenceUuidFactory());
}
}
| 6,330 | 30.81407 | 132 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/usergroups/ws/DeleteActionIT.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.usergroups.ws;
import java.util.Map;
import java.util.Set;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.WebService.Action;
import org.sonar.api.web.UserRole;
import org.sonar.core.util.UuidFactoryImpl;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.db.permission.template.PermissionTemplateTesting;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.management.ManagedInstanceService;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
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.tuple;
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.db.permission.GlobalPermission.ADMINISTER;
import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_GROUP_NAME;
public class DeleteActionIT {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create(new AlwaysIncreasingSystem2());
private final GroupService groupService = new GroupService(db.getDbClient(), UuidFactoryImpl.INSTANCE);
private final ManagedInstanceService managedInstanceService = mock(ManagedInstanceService.class);
private final WsActionTester ws = new WsActionTester(new DeleteAction(db.getDbClient(), userSession, groupService, managedInstanceService));
@Test
public void verify_definition() {
Action wsDef = ws.getDef();
assertThat(wsDef.isInternal()).isFalse();
assertThat(wsDef.since()).isEqualTo("5.2");
assertThat(wsDef.isPost()).isTrue();
assertThat(wsDef.changelog()).extracting(Change::getVersion, Change::getDescription).containsOnly(
tuple("10.0", "Parameter 'id' is removed. Use 'name' instead."),
tuple("8.4", "Parameter 'id' is deprecated. Format changes from integer to string. Use 'name' instead."));
}
@Test
public void response_has_no_content() {
addAdmin();
insertDefaultGroup();
GroupDto group = db.users().insertGroup();
loginAsAdmin();
TestResponse response = newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.execute();
assertThat(response.getStatus()).isEqualTo(204);
}
@Test
public void delete_by_name() {
addAdmin();
insertDefaultGroup();
GroupDto group = db.users().insertGroup();
loginAsAdmin();
newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.execute();
assertThat(db.users().selectGroupByUuid(group.getUuid())).isNull();
}
@Test
public void delete_ifNotGroupFound_throwsNotFoundException() {
addAdmin();
insertDefaultGroup();
GroupDto group = db.users().insertGroup();
loginAsAdmin();
TestRequest groupDeletionRequest = newRequest().setParam(PARAM_GROUP_NAME, group.getName() + "_toto");
assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(groupDeletionRequest::execute)
.withMessageStartingWith("No group with name ");
}
@Test
public void delete_members() {
addAdmin();
insertDefaultGroup();
GroupDto group = db.users().insertGroup();
UserDto user = db.users().insertUser();
db.users().insertMember(group, user);
loginAsAdmin();
newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.execute();
assertThat(db.countRowsOfTable("groups_users")).isZero();
}
@Test
public void delete_permissions() {
addAdmin();
insertDefaultGroup();
GroupDto group = db.users().insertGroup();
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
db.users().insertProjectPermissionOnGroup(group, UserRole.ADMIN, project);
loginAsAdmin();
newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.execute();
assertThat(db.countRowsOfTable("group_roles")).isZero();
}
@Test
public void delete_group_from_permission_templates() {
addAdmin();
insertDefaultGroup();
GroupDto group = db.users().insertGroup();
PermissionTemplateDto template = db.getDbClient().permissionTemplateDao().insert(db.getSession(),
PermissionTemplateTesting.newPermissionTemplateDto());
db.getDbClient().permissionTemplateDao().insertGroupPermission(db.getSession(), template.getUuid(), group.getUuid(), "perm",
template.getName(), group.getName());
db.commit();
loginAsAdmin();
assertThat(db.countRowsOfTable("perm_templates_groups")).isOne();
newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.execute();
assertThat(db.countRowsOfTable("perm_templates_groups")).isZero();
}
@Test
public void delete_qprofile_permissions() {
addAdmin();
insertDefaultGroup();
GroupDto group = db.users().insertGroup();
QProfileDto profile = db.qualityProfiles().insert();
db.qualityProfiles().addGroupPermission(profile, group);
loginAsAdmin();
newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.execute();
assertThat(db.countRowsOfTable("qprofile_edit_groups")).isZero();
}
@Test
public void delete_qgate_permissions() {
addAdmin();
insertDefaultGroup();
GroupDto group = db.users().insertGroup();
QualityGateDto qualityGate = db.qualityGates().insertQualityGate();
db.qualityGates().addGroupPermission(qualityGate, group);
loginAsAdmin();
newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.execute();
assertThat(db.countRowsOfTable("qgate_group_permissions")).isZero();
}
@Test
public void delete_scim_group() {
addAdmin();
insertDefaultGroup();
GroupDto group = db.users().insertGroup();
db.users().insertScimGroup(group);
loginAsAdmin();
newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.execute();
assertThat(db.countRowsOfTable("scim_groups")).isZero();
}
@Test
public void fail_to_delete_default_group() {
loginAsAdmin();
GroupDto defaultGroup = db.users().insertDefaultGroup();
assertThatThrownBy(() -> {
newRequest()
.setParam(PARAM_GROUP_NAME, defaultGroup.getName())
.execute();
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Default group 'sonar-users' cannot be used to perform this action");
}
@Test
public void cannot_delete_last_system_admin_group() {
insertDefaultGroup();
GroupDto group = db.users().insertGroup();
db.users().insertPermissionOnGroup(group, ADMINISTER.getKey());
loginAsAdmin();
TestRequest request = newRequest()
.setParam(PARAM_GROUP_NAME, group.getName());
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The last system admin group cannot be deleted");
}
@Test
public void delete_admin_group_fails_if_no_admin_users_left() {
// admin users are part of the group to be deleted
db.users().insertDefaultGroup();
GroupDto adminGroup = db.users().insertGroup("admins");
db.users().insertPermissionOnGroup(adminGroup, ADMINISTER.getKey());
UserDto bigBoss = db.users().insertUser();
db.users().insertMember(adminGroup, bigBoss);
loginAsAdmin();
assertThatThrownBy(() -> {
executeDeleteGroupRequest(adminGroup);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The last system admin group cannot be deleted");
}
@Test
public void delete_admin_group_succeeds_if_other_groups_have_administrators() {
db.users().insertDefaultGroup();
GroupDto adminGroup1 = db.users().insertGroup("admins");
db.users().insertPermissionOnGroup(adminGroup1, ADMINISTER.getKey());
GroupDto adminGroup2 = db.users().insertGroup("admins2");
db.users().insertPermissionOnGroup(adminGroup2, ADMINISTER.getKey());
UserDto bigBoss = db.users().insertUser();
db.users().insertMember(adminGroup2, bigBoss);
loginAsAdmin();
executeDeleteGroupRequest(adminGroup1);
assertThat(db.users().selectGroupPermissions(adminGroup2, null)).hasSize(1);
}
@Test
public void delete_local_group_when_instance_is_managed_shouldSucceed() {
when(managedInstanceService.isInstanceExternallyManaged()).thenReturn(true);
addAdmin();
insertDefaultGroup();
GroupDto group = insertGroupAndMockIsManaged(false);
loginAsAdmin();
TestResponse response = newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.execute();
assertThat(response.getStatus()).isEqualTo(204);
}
@Test
public void fail_to_delete_managed_group_when_instance_is_managed() {
when(managedInstanceService.isInstanceExternallyManaged()).thenReturn(true);
addAdmin();
insertDefaultGroup();
GroupDto group = insertGroupAndMockIsManaged(true);
loginAsAdmin();
TestRequest request = newRequest()
.setParam(PARAM_GROUP_NAME, group.getName());
assertThatThrownBy(request::execute)
.isInstanceOf(BadRequestException.class)
.hasMessage("Deleting managed groups is not allowed.");
}
private GroupDto insertGroupAndMockIsManaged(boolean isManaged) {
GroupDto group = db.users().insertGroup();
when(managedInstanceService.getGroupUuidToManaged(any(DbSession.class), eq(Set.of(group.getUuid()))))
.thenReturn(Map.of(group.getUuid(), isManaged));
return group;
}
private void executeDeleteGroupRequest(GroupDto adminGroup1) {
newRequest()
.setParam(PARAM_GROUP_NAME, adminGroup1.getName())
.execute();
}
private void addAdmin() {
UserDto admin = db.users().insertUser();
db.users().insertGlobalPermissionOnUser(admin, ADMINISTER);
}
private void loginAsAdmin() {
userSession.logIn().addPermission(ADMINISTER);
}
private void insertDefaultGroup() {
db.users().insertDefaultGroup();
}
private TestRequest newRequest() {
return ws.newRequest();
}
}
| 11,534 | 32.242075 | 142 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/usergroups/ws/ExternalGroupServiceIT.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.usergroups.ws;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
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.user.ExternalGroupDto;
import org.sonar.db.user.GroupDto;
import static org.assertj.core.api.Assertions.assertThat;
public class ExternalGroupServiceIT {
private static final String GROUP_NAME = "GROUP_NAME";
private static final String EXTERNAL_ID = "EXTERNAL_ID";
private static final String EXTERNAL_IDENTITY_PROVIDER = "EXTERNAL_IDENTITY_PROVIDER";
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private final DbClient dbClient = dbTester.getDbClient();
private final DbSession dbSession = dbTester.getSession();
private final GroupService groupService = new GroupService(dbClient, UuidFactoryFast.getInstance());
private final ExternalGroupService externalGroupService = new ExternalGroupService(dbClient, groupService);
@Test
public void createOrUpdateExternalGroup_whenNewGroup_shouldCreateIt() {
externalGroupService.createOrUpdateExternalGroup(dbSession, new GroupRegistration(EXTERNAL_ID, EXTERNAL_IDENTITY_PROVIDER, GROUP_NAME));
assertGroupAndExternalGroup();
}
@Test
public void createOrUpdateExternalGroup_whenExistingLocalGroup_shouldMatchAndMakeItExternal() {
dbTester.users().insertGroup(GROUP_NAME);
externalGroupService.createOrUpdateExternalGroup(dbSession, new GroupRegistration(EXTERNAL_ID, EXTERNAL_IDENTITY_PROVIDER, GROUP_NAME));
assertThat(dbTester.users().countAllGroups()).isEqualTo(1);
assertGroupAndExternalGroup();
}
@Test
public void createOrUpdateExternalGroup_whenExistingExternalGroup_shouldUpdate() {
dbTester.users().insertDefaultGroup();
GroupDto existingGroupDto = dbTester.users().insertGroup(GROUP_NAME);
dbTester.users().insertExternalGroup(new ExternalGroupDto(existingGroupDto.getUuid(), EXTERNAL_ID, EXTERNAL_IDENTITY_PROVIDER));
String updatedGroupName = "updated_" + GROUP_NAME;
externalGroupService.createOrUpdateExternalGroup(dbSession, new GroupRegistration(EXTERNAL_ID, EXTERNAL_IDENTITY_PROVIDER, updatedGroupName));
Optional<GroupDto> groupDto = dbTester.users().selectGroup(updatedGroupName);
assertThat(groupDto)
.isPresent().get()
.extracting(GroupDto::getName)
.isEqualTo(updatedGroupName);
}
private void assertGroupAndExternalGroup() {
Optional<GroupDto> groupDto = dbTester.users().selectGroup(GROUP_NAME);
assertThat(groupDto)
.isPresent().get()
.extracting(GroupDto::getName).isEqualTo(GROUP_NAME);
assertThat((dbTester.users().selectExternalGroupByGroupUuid(groupDto.get().getUuid())))
.isPresent().get()
.extracting(ExternalGroupDto::externalId, ExternalGroupDto::externalIdentityProvider)
.containsExactly(EXTERNAL_ID, EXTERNAL_IDENTITY_PROVIDER);
}
}
| 3,854 | 39.578947 | 146 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/usergroups/ws/RemoveUserActionIT.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.usergroups.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.WebService.Action;
import org.sonar.db.DbTester;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.management.ManagedInstanceChecker;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.usergroups.DefaultGroupFinder;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
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.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER;
import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_GROUP_NAME;
import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_LOGIN;
public class RemoveUserActionIT {
@Rule
public DbTester db = DbTester.create(new AlwaysIncreasingSystem2());
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private ManagedInstanceChecker managedInstanceChecker = mock(ManagedInstanceChecker.class);
private final WsActionTester ws = new WsActionTester(
new RemoveUserAction(db.getDbClient(), userSession, new GroupWsSupport(db.getDbClient(), new DefaultGroupFinder(db.getDbClient())), managedInstanceChecker));
@Test
public void verify_definition() {
Action wsDef = ws.getDef();
assertThat(wsDef.isInternal()).isFalse();
assertThat(wsDef.since()).isEqualTo("5.2");
assertThat(wsDef.isPost()).isTrue();
assertThat(wsDef.changelog()).extracting(Change::getVersion, Change::getDescription).containsOnly(
tuple("10.0", "Parameter 'id' is removed. Use 'name' instead."),
tuple("8.4", "Parameter 'id' is deprecated. Format changes from integer to string. Use 'name' instead."));
}
@Test
public void does_nothing_if_user_is_not_in_group() {
// keep an administrator
insertAnAdministrator();
insertDefaultGroup();
GroupDto group = db.users().insertGroup("admins");
UserDto user = db.users().insertUser("my-admin");
loginAsAdmin();
newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
assertThat(db.users().selectGroupUuidsOfUser(user)).isEmpty();
}
@Test
public void remove_user_by_group_name() {
insertAnAdministrator();
insertDefaultGroup();
GroupDto group = db.users().insertGroup("a_group");
UserDto user = db.users().insertUser("a_user");
db.users().insertMember(group, user);
loginAsAdmin();
newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
assertThat(db.users().selectGroupUuidsOfUser(user)).isEmpty();
}
@Test
public void remove_user_only_from_one_group() {
// keep an administrator
insertAnAdministrator();
insertDefaultGroup();
GroupDto users = db.users().insertGroup("user");
GroupDto admins = db.users().insertGroup("admins");
UserDto user = db.users().insertUser("user");
db.users().insertMember(users, user);
db.users().insertMember(admins, user);
loginAsAdmin();
newRequest()
.setParam(PARAM_GROUP_NAME, admins.getName())
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
assertThat(db.users().selectGroupUuidsOfUser(user)).containsOnly(users.getUuid());
}
@Test
public void response_status_is_no_content() {
// keep an administrator
insertAnAdministrator();
insertDefaultGroup();
GroupDto users = db.users().insertGroup("users");
UserDto user = db.users().insertUser("my-admin");
db.users().insertMember(users, user);
loginAsAdmin();
TestResponse response = newRequest()
.setParam(PARAM_GROUP_NAME, users.getName())
.setParam(PARAM_LOGIN, user.getLogin())
.execute();
assertThat(response.getStatus()).isEqualTo(HTTP_NO_CONTENT);
}
@Test
public void fail_if_unknown_group() {
UserDto user = db.users().insertUser("my-admin");
loginAsAdmin();
TestRequest request = newRequest()
.setParam(PARAM_GROUP_NAME, "unknown")
.setParam(PARAM_LOGIN, user.getLogin());
assertThatThrownBy(request::execute)
.isInstanceOf(NotFoundException.class);
}
@Test
public void fail_if_unknown_user() {
insertDefaultGroup();
GroupDto group = db.users().insertGroup("admins");
loginAsAdmin();
TestRequest request = newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam(PARAM_LOGIN, "my-admin");
assertThatThrownBy(request::execute)
.isInstanceOf(NotFoundException.class);
}
@Test
public void throw_ForbiddenException_if_not_administrator() {
GroupDto group = db.users().insertGroup("a-group");
UserDto user = db.users().insertUser();
db.users().insertMember(group, user);
userSession.logIn("admin");
TestRequest request = newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam(PARAM_LOGIN, user.getLogin());
assertThatThrownBy(request::execute)
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void fail_to_remove_the_last_administrator() {
db.users().insertDefaultGroup();
GroupDto adminGroup = db.users().insertGroup("sonar-admins");
db.users().insertPermissionOnGroup(adminGroup, ADMINISTER);
UserDto adminUser = db.users().insertUser("the-single-admin");
db.users().insertMember(adminGroup, adminUser);
loginAsAdmin();
TestRequest request = newRequest()
.setParam(PARAM_GROUP_NAME, adminGroup.getName())
.setParam(PARAM_LOGIN, adminUser.getLogin());
assertThatThrownBy(request::execute)
.isInstanceOf(BadRequestException.class)
.hasMessage("The last administrator user cannot be removed");
}
@Test
public void fail_to_remove_user_from_default_group() {
UserDto user = db.users().insertUser();
GroupDto defaultGroup = db.users().insertDefaultGroup();
db.users().insertMember(defaultGroup, user);
loginAsAdmin();
TestRequest request = newRequest()
.setParam(PARAM_GROUP_NAME, defaultGroup.getName())
.setParam(PARAM_LOGIN, user.getLogin());
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Default group 'sonar-users' cannot be used to perform this action");
}
@Test
public void fail_if_instance_is_externally_managed() {
loginAsAdmin();
BadRequestException exception = BadRequestException.create("Not allowed");
doThrow(exception).when(managedInstanceChecker).throwIfInstanceIsManaged();
TestRequest testRequest = newRequest();
assertThatThrownBy(testRequest::execute)
.isEqualTo(exception);
}
private TestRequest newRequest() {
return ws.newRequest();
}
private void loginAsAdmin() {
userSession.logIn("admin").addPermission(ADMINISTER);
}
private void insertAnAdministrator() {
db.users().insertAdminByUserPermission();
}
private void insertDefaultGroup() {
db.users().insertDefaultGroup();
}
}
| 8,507 | 33.585366 | 161 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/usergroups/ws/SearchActionIT.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.usergroups.ws;
import java.util.Set;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.scim.ScimGroupDao;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.management.ManagedInstanceService;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.usergroups.DefaultGroupFinder;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Common.Paging;
import org.sonarqube.ws.MediaTypes;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
import static org.apache.commons.lang.StringUtils.capitalize;
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.tuple;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.api.server.ws.WebService.Param.FIELDS;
import static org.sonar.api.server.ws.WebService.Param.PAGE;
import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER;
import static org.sonar.db.user.GroupTesting.newGroupDto;
import static org.sonar.test.JsonAssert.assertJson;
import static org.sonarqube.ws.UserGroups.Group;
import static org.sonarqube.ws.UserGroups.SearchWsResponse;
public class SearchActionIT {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final ManagedInstanceService managedInstanceService = mock(ManagedInstanceService.class);
private final WsActionTester ws = new WsActionTester(new SearchAction(db.getDbClient(), userSession,
new DefaultGroupFinder(db.getDbClient()), managedInstanceService));
@Test
public void define_search_action() {
WebService.Action action = ws.getDef();
assertThat(action).isNotNull();
assertThat(action.key()).isEqualTo("search");
assertThat(action.responseExampleAsString()).isNotEmpty();
assertThat(action.params()).hasSize(5);
assertThat(action.changelog()).extracting(Change::getVersion, Change::getDescription).containsOnly(
tuple("10.0", "Field 'id' in the response has been removed"),
tuple("10.0", "New parameter 'managed' to optionally search by managed status"),
tuple("10.0", "Response includes 'managed' field."),
tuple("8.4", "Field 'id' in the response is deprecated. Format changes from integer to string."),
tuple("6.4", "Paging response fields moved to a Paging object"),
tuple("6.4", "'default' response field has been added"));
}
@Test
public void search_without_parameters() {
insertDefaultGroup(0);
insertGroup("admins", 0);
insertGroup("customer1", 0);
insertGroup("customer2", 0);
insertGroup("customer3", 0);
loginAsAdmin();
SearchWsResponse response = call(ws.newRequest());
assertThat(response.getGroupsList()).extracting(Group::getName, Group::getDescription, Group::getMembersCount).containsOnly(
tuple("admins", "Admins", 0),
tuple("customer1", "Customer1", 0),
tuple("customer2", "Customer2", 0),
tuple("customer3", "Customer3", 0),
tuple("sonar-users", "Users", 0));
}
@Test
public void search_returnsCorrectlyIsManagedFlag() {
insertDefaultGroup(0);
insertGroup("admins", 0);
insertGroup("customer1", 0);
GroupDto customer2group = insertGroup("customer2", 0);
GroupDto customer3group = insertGroup("customer3", 0);
mockGroupAsManaged(customer2group.getUuid(), customer3group.getUuid());
loginAsAdmin();
SearchWsResponse response = call(ws.newRequest());
assertThat(response.getGroupsList()).extracting(Group::getName, Group::getManaged).containsOnly(
tuple("admins", false),
tuple("customer1", false),
tuple("customer2", true),
tuple("customer3", true),
tuple("sonar-users", false));
}
@Test
public void search_with_members() {
insertDefaultGroup(5);
insertGroup("admins", 1);
insertGroup("customer1", 0);
insertGroup("customer2", 4);
insertGroup("customer3", 0);
loginAsAdmin();
SearchWsResponse response = call(ws.newRequest());
assertThat(response.getGroupsList()).extracting(Group::getName, Group::getDescription, Group::getMembersCount).containsOnly(
tuple("admins", "Admins", 1),
tuple("customer1", "Customer1", 0),
tuple("customer2", "Customer2", 4),
tuple("customer3", "Customer3", 0),
tuple("sonar-users", "Users", 5));
}
@Test
public void search_whenFilteringByManagedAndInstanceManaged_returnsCorrectResults() {
insertGroupsAndMockExternallyManaged();
SearchWsResponse managedResponse = call(ws.newRequest().setParam("managed", "true"));
assertThat(managedResponse.getGroupsList()).extracting(Group::getName, Group::getManaged).containsOnly(
tuple("group1", true),
tuple("group3", true));
assertThat(managedResponse.getPaging().getTotal()).isEqualTo(2);
}
@Test
public void search_whenFilteringByManagedNonAndInstanceManaged_returnsCorrectResults() {
insertGroupsAndMockExternallyManaged();
SearchWsResponse notManagedResponse = call(ws.newRequest().setParam("managed", "false"));
assertThat(notManagedResponse.getGroupsList()).extracting(Group::getName, Group::getManaged).containsOnly(
tuple("group2", false),
tuple("group4", false),
tuple("sonar-users", false));
assertThat(notManagedResponse.getPaging().getTotal()).isEqualTo(3);
}
@Test
public void search_whenFilteringByManagedNonAndInstanceManagedAndTextParameter_returnsCorrectResults() {
insertGroupsAndMockExternallyManaged();
SearchWsResponse notManagedResponse = call(ws.newRequest().setParam("managed", "false").setParam("q", "sonar"));
assertThat(notManagedResponse.getGroupsList()).extracting(Group::getName, Group::getManaged).containsOnly(
tuple("sonar-users", false));
assertThat(notManagedResponse.getPaging().getTotal()).isEqualTo(1);
}
@Test
public void search_whenFilteringByManagedAndInstanceNotManaged_throws() {
userSession.logIn().setSystemAdministrator();
TestRequest testRequest = ws.newRequest()
.setParam("managed", "true");
assertThatExceptionOfType(BadRequestException.class)
.isThrownBy(() -> testRequest.executeProtobuf(SearchWsResponse.class))
.withMessage("The 'managed' parameter is only available for managed instances.");
}
@Test
public void search_with_query() {
insertDefaultGroup(0);
insertGroup("admins", 0);
insertGroup("customer%_%/1", 0);
insertGroup("customer%_%/2", 0);
insertGroup("customer%_%/3", 0);
loginAsAdmin();
SearchWsResponse response = call(ws.newRequest().setParam(TEXT_QUERY, "tomer%_%/"));
assertThat(response.getGroupsList()).extracting(Group::getName, Group::getDescription, Group::getMembersCount).containsOnly(
tuple("customer%_%/1", "Customer%_%/1", 0),
tuple("customer%_%/2", "Customer%_%/2", 0),
tuple("customer%_%/3", "Customer%_%/3", 0));
}
@Test
public void search_with_paging() {
insertDefaultGroup(0);
insertGroup("admins", 0);
insertGroup("customer1", 0);
insertGroup("customer2", 0);
insertGroup("customer3", 0);
loginAsAdmin();
SearchWsResponse response = call(ws.newRequest().setParam(PAGE_SIZE, "3"));
assertThat(response.getPaging()).extracting(Paging::getPageIndex, Paging::getPageSize, Paging::getTotal).containsOnly(1, 3, 5);
assertThat(response.getGroupsList()).extracting(Group::getName, Group::getDescription, Group::getMembersCount).containsOnly(
tuple("admins", "Admins", 0),
tuple("customer1", "Customer1", 0),
tuple("customer2", "Customer2", 0));
response = call(ws.newRequest().setParam(PAGE_SIZE, "3").setParam(PAGE, "2"));
assertThat(response.getPaging()).extracting(Paging::getPageIndex, Paging::getPageSize, Paging::getTotal).containsOnly(2, 3, 5);
assertThat(response.getGroupsList()).extracting(Group::getName, Group::getDescription, Group::getMembersCount).containsOnly(
tuple("customer3", "Customer3", 0),
tuple("sonar-users", "Users", 0));
response = call(ws.newRequest().setParam(PAGE_SIZE, "3").setParam(PAGE, "3"));
assertThat(response.getPaging()).extracting(Paging::getPageIndex, Paging::getPageSize, Paging::getTotal).containsOnly(3, 3, 5);
assertThat(response.getGroupsList()).isEmpty();
}
@Test
public void search_with_fields() {
insertDefaultGroup(0);
loginAsAdmin();
assertThat(call(ws.newRequest()).getGroupsList())
.extracting(Group::hasName, Group::hasDescription, Group::hasMembersCount, Group::hasManaged)
.containsOnly(tuple(true, true, true, true));
assertThat(call(ws.newRequest().setParam(FIELDS, "")).getGroupsList())
.extracting(Group::hasName, Group::hasDescription, Group::hasMembersCount, Group::hasManaged)
.containsOnly(tuple(true, true, true, true));
assertThat(call(ws.newRequest().setParam(FIELDS, "name")).getGroupsList())
.extracting(Group::hasName, Group::hasDescription, Group::hasMembersCount, Group::hasManaged)
.containsOnly(tuple(true, false, false, false));
assertThat(call(ws.newRequest().setParam(FIELDS, "description")).getGroupsList())
.extracting(Group::hasName, Group::hasDescription, Group::hasMembersCount, Group::hasManaged)
.containsOnly(tuple(false, true, false, false));
assertThat(call(ws.newRequest().setParam(FIELDS, "membersCount")).getGroupsList())
.extracting(Group::hasName, Group::hasDescription, Group::hasMembersCount, Group::hasManaged)
.containsOnly(tuple(false, false, true, false));
assertThat(call(ws.newRequest().setParam(FIELDS, "managed")).getGroupsList())
.extracting(Group::hasName, Group::hasDescription, Group::hasMembersCount, Group::hasManaged)
.containsOnly(tuple(false, false, false, true));
}
@Test
public void return_default_group() {
db.users().insertDefaultGroup();
loginAsAdmin();
SearchWsResponse response = call(ws.newRequest());
assertThat(response.getGroupsList()).extracting(Group::getName, Group::getDefault).containsOnly(tuple("sonar-users", true));
}
@Test
public void fail_when_not_logged_in() {
userSession.anonymous();
assertThatThrownBy(() -> {
call(ws.newRequest());
})
.isInstanceOf(UnauthorizedException.class);
}
@Test
public void test_json_example() {
insertDefaultGroup(17);
GroupDto groupDto = insertGroup("administrators", 2);
mockGroupAsManaged(groupDto.getUuid());
loginAsAdmin();
String response = ws.newRequest().setMediaType(MediaTypes.JSON).execute().getInput();
assertJson(response).ignoreFields("id").isSimilarTo(ws.getDef().responseExampleAsString());
}
@Test
public void verify_definition() {
WebService.Action action = ws.getDef();
assertThat(action.since()).isEqualTo("5.2");
assertThat(action.isPost()).isFalse();
assertThat(action.isInternal()).isFalse();
assertThat(action.responseExampleAsString()).isNotEmpty();
assertThat(action.params()).extracting(WebService.Param::key).containsOnly("p", "q", "ps", "f", "managed");
assertThat(action.param("f").possibleValues()).containsOnly("name", "description", "membersCount", "managed");
}
private SearchWsResponse call(TestRequest request) {
return request.executeProtobuf(SearchWsResponse.class);
}
private void insertDefaultGroup(int numberOfMembers) {
GroupDto group = db.users().insertDefaultGroup();
addMembers(group, numberOfMembers);
}
private GroupDto insertGroup(String name, int numberOfMembers) {
GroupDto group = newGroupDto().setName(name).setDescription(capitalize(name));
db.users().insertGroup(group);
addMembers(group, numberOfMembers);
return group;
}
private void insertGroupsAndMockExternallyManaged() {
insertDefaultGroup(0);
GroupDto group1 = insertGroup("group1", 0);
insertGroup("group2", 0);
GroupDto group3 = insertGroup("group3", 0);
insertGroup("group4", 0);
loginAsAdmin();
mockGroupAsManaged(group1.getUuid(), group3.getUuid());
mockInstanceExternallyManagedAndFilterForManagedGroups();
}
private void mockInstanceExternallyManagedAndFilterForManagedGroups() {
when(managedInstanceService.isInstanceExternallyManaged()).thenReturn(true);
when(managedInstanceService.getManagedGroupsSqlFilter(anyBoolean()))
.thenAnswer(invocation -> {
Boolean managed = invocation.getArgument(0, Boolean.class);
return new ScimGroupDao(mock(UuidFactory.class)).getManagedGroupSqlFilter(managed);
});
}
private void mockGroupAsManaged(String... groupUuids) {
when(managedInstanceService.getGroupUuidToManaged(any(), any())).thenAnswer(invocation -> {
@SuppressWarnings("unchecked")
Set<String> allGroupUuids = (Set<String>) invocation.getArgument(1, Set.class);
return allGroupUuids.stream()
.collect(toMap(identity(), userUuid -> Set.of(groupUuids).contains(userUuid)));
});
DbSession session = db.getSession();
for (String groupUuid : groupUuids) {
db.getDbClient().scimGroupDao().enableScimForGroup(session, groupUuid);
}
session.commit();
}
private void addMembers(GroupDto group, int numberOfMembers) {
for (int i = 0; i < numberOfMembers; i++) {
UserDto user = db.users().insertUser();
db.users().insertMember(group, user);
}
}
private void loginAsAdmin() {
userSession.logIn("user").addPermission(ADMINISTER);
}
}
| 15,175 | 39.148148 | 131 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/usergroups/ws/UpdateActionIT.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.usergroups.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.WebService.Action;
import org.sonar.api.utils.System2;
import org.sonar.core.util.UuidFactoryImpl;
import org.sonar.db.DbTester;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.ServerException;
import org.sonar.server.management.ManagedInstanceChecker;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER;
import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_GROUP_CURRENT_NAME;
import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_GROUP_DESCRIPTION;
import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_GROUP_NAME;
import static org.sonar.test.JsonAssert.assertJson;
public class UpdateActionIT {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private ManagedInstanceChecker managedInstanceChecker = mock(ManagedInstanceChecker.class);
private final WsActionTester ws = new WsActionTester(
new UpdateAction(db.getDbClient(), userSession, new GroupService(db.getDbClient(), UuidFactoryImpl.INSTANCE), managedInstanceChecker));
@Test
public void verify_definition() {
Action wsDef = ws.getDef();
assertThat(wsDef.isInternal()).isFalse();
assertThat(wsDef.since()).isEqualTo("5.2");
assertThat(wsDef.isPost()).isTrue();
assertThat(wsDef.changelog()).extracting(Change::getVersion, Change::getDescription).isNotEmpty();
}
@Test
public void update_both_name_and_description() {
insertDefaultGroup();
GroupDto group = db.users().insertGroup();
UserDto user = db.users().insertUser();
db.users().insertMember(group, user);
loginAsAdmin();
String result = newRequest()
.setParam(PARAM_GROUP_CURRENT_NAME, group.getName())
.setParam(PARAM_GROUP_NAME, "new-name")
.setParam(PARAM_GROUP_DESCRIPTION, "New Description")
.execute().getInput();
assertJson(result).isSimilarTo("""
{
"group": {
"name": "new-name",
"description": "New Description",
"membersCount": 1
}
}""");
}
@Test
public void update_only_name() {
insertDefaultGroup();
GroupDto group = db.users().insertGroup();
loginAsAdmin();
String result = newRequest()
.setParam(PARAM_GROUP_CURRENT_NAME, group.getName())
.setParam(PARAM_GROUP_NAME, "new-name")
.execute().getInput();
assertJson(result).isSimilarTo(String.format("""
{
"group": {
"name": "new-name",
"description": "%s",
"membersCount": 0
}
}""", group.getDescription()));
}
@Test
public void update_only_description() {
insertDefaultGroup();
GroupDto group = db.users().insertGroup();
loginAsAdmin();
String result = newRequest()
.setParam(PARAM_GROUP_CURRENT_NAME, group.getName())
.setParam(PARAM_GROUP_DESCRIPTION, "New Description")
.execute().getInput();
assertJson(result).isSimilarTo(String.format("""
{
"group": {
"name": "%s",
"description": "New Description",
"membersCount": 0
}
}""", group.getName()));
}
@Test
public void return_default_field() {
insertDefaultGroup();
GroupDto group = db.users().insertGroup();
loginAsAdmin();
String result = newRequest()
.setParam(PARAM_GROUP_CURRENT_NAME, group.getName())
.setParam(PARAM_GROUP_NAME, "new-name")
.execute().getInput();
assertJson(result).isSimilarTo("{" +
" \"group\": {" +
" \"name\": \"new-name\"," +
" \"description\": \"" + group.getDescription() + "\"," +
" \"membersCount\": 0," +
" \"default\": false" +
" }" +
"}");
}
@Test
public void require_admin_permission() {
insertDefaultGroup();
GroupDto group = db.users().insertGroup();
userSession.logIn("not-admin");
assertThatThrownBy(() -> {
newRequest()
.setParam(PARAM_GROUP_CURRENT_NAME, group.getName())
.setParam(PARAM_GROUP_NAME, "some-product-bu")
.setParam(PARAM_GROUP_DESCRIPTION, "Business Unit for Some Awesome Product")
.execute();
})
.isInstanceOf(ForbiddenException.class);
}
@Test
public void fail_if_name_is_too_short() {
insertDefaultGroup();
GroupDto group = db.users().insertGroup();
loginAsAdmin();
TestRequest request = newRequest()
.setParam(PARAM_GROUP_CURRENT_NAME, group.getName())
.setParam(PARAM_GROUP_NAME, "");
assertThatThrownBy(request::execute)
.isInstanceOf(BadRequestException.class)
.hasMessage("Group name cannot be empty");
}
@Test
public void fail_if_no_currentname_are_provided() {
insertDefaultGroup();
TestRequest request = newRequest()
.setParam(PARAM_GROUP_NAME, "newname");
loginAsAdmin();
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The 'currentName' parameter is missing");
}
@Test
public void fail_if_new_name_is_anyone() {
insertDefaultGroup();
GroupDto group = db.users().insertGroup();
loginAsAdmin();
TestRequest request = newRequest()
.setParam(PARAM_GROUP_CURRENT_NAME, group.getName())
.setParam(PARAM_GROUP_NAME, "AnYoNe");
assertThatThrownBy(request::execute)
.isInstanceOf(BadRequestException.class)
.hasMessage("Anyone group cannot be used");
}
@Test
public void fail_to_update_if_name_already_exists() {
insertDefaultGroup();
GroupDto groupToBeRenamed = db.users().insertGroup("a name");
String newName = "new-name";
db.users().insertGroup(newName);
loginAsAdmin();
TestRequest request = newRequest()
.setParam(PARAM_GROUP_CURRENT_NAME, groupToBeRenamed.getName())
.setParam(PARAM_GROUP_NAME, newName);
assertThatThrownBy(request::execute)
.isInstanceOf(ServerException.class)
.hasMessage("Group 'new-name' already exists");
}
@Test
public void fail_if_unknown_group_name() {
loginAsAdmin();
TestRequest request = newRequest()
.setParam(PARAM_GROUP_CURRENT_NAME, "42");
assertThatThrownBy(request::execute)
.isInstanceOf(NotFoundException.class)
.hasMessage("Could not find a user group with name '42'.");
}
@Test
public void fail_to_update_default_group_name() {
GroupDto group = db.users().insertDefaultGroup();
loginAsAdmin();
TestRequest request = newRequest()
.setParam(PARAM_GROUP_CURRENT_NAME, group.getName())
.setParam(PARAM_GROUP_NAME, "new name");
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Default group 'sonar-users' cannot be used to perform this action");
}
@Test
public void fail_to_update_default_group_description() {
GroupDto group = db.users().insertDefaultGroup();
loginAsAdmin();
TestRequest request = newRequest()
.setParam(PARAM_GROUP_CURRENT_NAME, group.getName())
.setParam(PARAM_GROUP_DESCRIPTION, "new description");
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Default group 'sonar-users' cannot be used to perform this action");
}
@Test
public void fail_if_instance_is_externally_managed() {
loginAsAdmin();
BadRequestException exception = BadRequestException.create("Not allowed");
doThrow(exception).when(managedInstanceChecker).throwIfInstanceIsManaged();
TestRequest testRequest = newRequest();
assertThatThrownBy(testRequest::execute)
.isEqualTo(exception);
}
private TestRequest newRequest() {
return ws.newRequest();
}
private void loginAsAdmin() {
userSession.logIn().addPermission(ADMINISTER);
}
private void insertDefaultGroup() {
db.users().insertDefaultGroup();
}
}
| 9,410 | 31.340206 | 139 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/usergroups/ws/UsersActionIT.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.usergroups.ws;
import java.util.Set;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.WebService.Action;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.server.ws.WebService.SelectionMode;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.management.ManagedInstanceService;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.usergroups.DefaultGroupFinder;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
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.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.db.permission.GlobalPermission.ADMINISTER;
import static org.sonar.db.user.UserTesting.newUserDto;
import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_GROUP_NAME;
import static org.sonar.test.JsonAssert.assertJson;
public class UsersActionIT {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final ManagedInstanceService managedInstanceService = mock(ManagedInstanceService.class);
private final WsActionTester ws = new WsActionTester(
new UsersAction(db.getDbClient(), userSession, managedInstanceService, new GroupWsSupport(db.getDbClient(), new DefaultGroupFinder(db.getDbClient()))));
@Test
public void verify_definition() {
Action wsDef = ws.getDef();
assertThat(wsDef.isInternal()).isFalse();
assertThat(wsDef.since()).isEqualTo("5.2");
assertThat(wsDef.isPost()).isFalse();
assertThat(wsDef.changelog()).extracting(Change::getVersion, Change::getDescription).containsOnly(
tuple("10.0", "Field 'managed' added to the payload."),
tuple("10.0", "Parameter 'id' is removed. Use 'name' instead."),
tuple("9.8", "response fields 'total', 's', 'ps' have been deprecated, please use 'paging' object instead."),
tuple("9.8", "The field 'paging' has been added to the response."),
tuple("8.4", "Parameter 'id' is deprecated. Format changes from integer to string. Use 'name' instead."));
}
@Test
public void fail_if_unknown_group_uuid() {
loginAsAdmin();
TestRequest request = newUsersRequest()
.setParam(PARAM_GROUP_NAME, "unknown")
.setParam("login", "john");
assertThatThrownBy(request::execute)
.isInstanceOf(NotFoundException.class)
.hasMessage("No group with name 'unknown'");
}
@Test
public void fail_if_not_admin() {
GroupDto group = db.users().insertGroup();
userSession.logIn("not-admin");
TestRequest request = newUsersRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam("login", "john");
assertThatThrownBy(request::execute)
.isInstanceOf(ForbiddenException.class);
}
@Test
public void group_has_no_users() {
GroupDto group = db.users().insertGroup();
loginAsAdmin();
String result = newUsersRequest()
.setParam("login", "john")
.setParam(PARAM_GROUP_NAME, group.getName())
.execute()
.getInput();
assertJson(result).isSimilarTo("""
{
"p": 1,
"total": 0,
"paging": {
"pageIndex": 1,
"pageSize": 25,
"total": 0
}, "users": []
}""");
}
@Test
public void references_group_by_its_name() {
GroupDto group = db.users().insertGroup();
UserDto lovelace = db.users().insertUser(newUserDto().setLogin("ada.login").setName("Ada Lovelace"));
UserDto hopper = db.users().insertUser(newUserDto().setLogin("grace").setName("Grace Hopper"));
db.users().insertMember(group, lovelace);
loginAsAdmin();
String result = newUsersRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam(Param.SELECTED, SelectionMode.ALL.value())
.execute()
.getInput();
assertJson(result).isSimilarTo("""
{
"users": [
{"login": "ada.login", "name": "Ada Lovelace", "selected": true},
{"login": "grace", "name": "Grace Hopper", "selected": false}
]
}
""");
}
@Test
public void test_isManagedFlag() {
GroupDto group = db.users().insertGroup();
UserDto lovelace = db.users().insertUser(newUserDto().setLogin("ada.login").setName("Ada Lovelace"));
UserDto hopper = db.users().insertUser(newUserDto().setLogin("grace").setName("Grace Hopper"));
mockUsersAsManaged(hopper.getUuid());
db.users().insertMember(group, hopper);
db.users().insertMember(group, lovelace);
loginAsAdmin();
String result = newUsersRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.execute()
.getInput();
assertJson(result).isSimilarTo("""
{
"users": [
{"login": "ada.login", "name": "Ada Lovelace", "managed": false},
{"login": "grace", "name": "Grace Hopper", "managed": true}
]
}
""");
}
@Test
public void filter_members_by_name() {
GroupDto group = db.users().insertGroup("a group");
UserDto adaLovelace = db.users().insertUser(newUserDto().setLogin("ada").setName("Ada Lovelace"));
UserDto graceHopper = db.users().insertUser(newUserDto().setLogin("grace").setName("Grace Hopper"));
db.users().insertMember(group, adaLovelace);
db.users().insertMember(group, graceHopper);
loginAsAdmin();
String response = newUsersRequest().setParam(PARAM_GROUP_NAME, group.getName()).execute().getInput();
assertThat(response).contains("Ada Lovelace", "Grace Hopper");
}
@Test
public void selected_users() {
GroupDto group = db.users().insertGroup("a group");
UserDto lovelace = db.users().insertUser(newUserDto().setLogin("ada").setName("Ada Lovelace"));
UserDto hopper = db.users().insertUser(newUserDto().setLogin("grace").setName("Grace Hopper"));
db.users().insertMember(group, lovelace);
loginAsAdmin();
assertJson(newUsersRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.execute()
.getInput()).isSimilarTo("""
{
"users": [
{"login": "ada", "name": "Ada Lovelace", "selected": true}
]
}""");
assertJson(newUsersRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam(Param.SELECTED, SelectionMode.SELECTED.value())
.execute()
.getInput()).isSimilarTo("""
{
"users": [
{"login": "ada", "name": "Ada Lovelace", "selected": true}
]
}""");
}
@Test
public void deselected_users() {
GroupDto group = db.users().insertGroup();
UserDto lovelace = db.users().insertUser(newUserDto().setLogin("ada").setName("Ada Lovelace"));
UserDto hopper = db.users().insertUser(newUserDto().setLogin("grace").setName("Grace Hopper"));
db.users().insertMember(group, lovelace);
loginAsAdmin();
String result = newUsersRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam(Param.SELECTED, SelectionMode.DESELECTED.value())
.execute()
.getInput();
assertJson(result).isSimilarTo("""
{
"users": [
{"login": "grace", "name": "Grace Hopper", "selected": false}
]
}""");
}
@Test
public void paging() {
GroupDto group = db.users().insertGroup();
UserDto lovelace = db.users().insertUser(newUserDto().setLogin("ada").setName("Ada Lovelace"));
UserDto hopper = db.users().insertUser(newUserDto().setLogin("grace").setName("Grace Hopper"));
db.users().insertMember(group, lovelace);
loginAsAdmin();
assertJson(newUsersRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam("ps", "1")
.setParam(Param.SELECTED, SelectionMode.ALL.value())
.execute()
.getInput()).isSimilarTo("""
{
"p": 1,
"ps": 1,
"total": 2,
"paging": {
"pageIndex": 1,
"pageSize": 1,
"total": 2
}, "users": [
{"login": "ada", "name": "Ada Lovelace", "selected": true}
]
}""");
assertJson(newUsersRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam("ps", "1")
.setParam("p", "2")
.setParam(Param.SELECTED, SelectionMode.ALL.value())
.execute()
.getInput()).isSimilarTo("""
{
"p": 2,
"ps": 1,
"total": 2,
"paging": {
"pageIndex": 2,
"pageSize": 1,
"total": 2
}, "users": [
{"login": "grace", "name": "Grace Hopper", "selected": false}
]
}""");
}
@Test
public void filtering_by_name_email_and_login() {
GroupDto group = db.users().insertGroup();
UserDto lovelace = db.users().insertUser(newUserDto().setLogin("ada.login").setName("Ada Lovelace").setEmail("ada@email.com"));
UserDto hopper = db.users().insertUser(newUserDto().setLogin("grace").setName("Grace Hopper").setEmail("grace@hopper.com"));
db.users().insertMember(group, lovelace);
loginAsAdmin();
assertJson(newUsersRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam("q", "ace")
.setParam(Param.SELECTED, SelectionMode.ALL.value())
.execute()
.getInput()).isSimilarTo("""
{
"users": [
{"login": "ada.login", "name": "Ada Lovelace", "selected": true},
{"login": "grace", "name": "Grace Hopper", "selected": false}
]
}
""");
assertJson(newUsersRequest().setParam(PARAM_GROUP_NAME, group.getName())
.setParam("q", ".logi")
.execute()
.getInput()).isSimilarTo("""
{
"users": [
{
"login": "ada.login",
"name": "Ada Lovelace",
"selected": true
}
]
}
""");
assertJson(newUsersRequest().setParam(PARAM_GROUP_NAME, group.getName())
.setParam("q", "OvE")
.execute()
.getInput()).isSimilarTo("""
{
"users": [
{
"login": "ada.login",
"name": "Ada Lovelace",
"selected": true
}
]
}
""");
assertJson(newUsersRequest().setParam(PARAM_GROUP_NAME, group.getName())
.setParam("q", "mail")
.execute()
.getInput()).isSimilarTo("""
{
"users": [
{
"login": "ada.login",
"name": "Ada Lovelace",
"selected": true
}
]
}
""");
}
@Test
public void test_example() {
GroupDto group = db.users().insertGroup();
UserDto admin = db.users().insertUser(newUserDto().setLogin("admin").setName("Administrator"));
db.users().insertMember(group, admin);
UserDto george = db.users().insertUser(newUserDto().setLogin("george.orwell").setName("George Orwell"));
db.users().insertMember(group, george);
mockUsersAsManaged(george.getUuid());
loginAsAdmin();
String result = newUsersRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam(Param.SELECTED, SelectionMode.ALL.value())
.execute()
.getInput();
assertJson(result).isSimilarTo(ws.getDef().responseExampleAsString());
}
private TestRequest newUsersRequest() {
return ws.newRequest();
}
private void loginAsAdmin() {
userSession.logIn().addPermission(ADMINISTER);
}
private void mockUsersAsManaged(String... userUuids) {
when(managedInstanceService.getUserUuidToManaged(any(), any())).thenAnswer(invocation ->
{
Set<?> allUsersUuids = invocation.getArgument(1, Set.class);
return allUsersUuids.stream()
.map(userUuid -> (String) userUuid)
.collect(toMap(identity(), userUuid -> Set.of(userUuids).contains(userUuid)));
}
);
}
}
| 13,167 | 32.085427 | 156 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/usertoken/ws/GenerateActionIT.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.usertoken.ws;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.SonarRuntime;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.db.component.ResourceTypesRule;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.user.TokenType;
import org.sonar.db.user.UserDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.ServerException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.usertoken.TokenGenerator;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.MediaTypes;
import org.sonarqube.ws.UserTokens.GenerateWsResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyString;
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.api.utils.DateUtils.DATETIME_FORMAT;
import static org.sonar.api.utils.DateUtils.DATE_FORMAT;
import static org.sonar.core.config.MaxTokenLifetimeOption.NO_EXPIRATION;
import static org.sonar.core.config.MaxTokenLifetimeOption.THIRTY_DAYS;
import static org.sonar.core.config.TokenExpirationConstants.MAX_ALLOWED_TOKEN_LIFETIME;
import static org.sonar.db.permission.GlobalPermission.SCAN;
import static org.sonar.db.user.TokenType.GLOBAL_ANALYSIS_TOKEN;
import static org.sonar.db.user.TokenType.PROJECT_ANALYSIS_TOKEN;
import static org.sonar.db.user.TokenType.USER_TOKEN;
import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_EXPIRATION_DATE;
import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_LOGIN;
import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_NAME;
import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_PROJECT_KEY;
import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_TYPE;
import static org.sonar.test.JsonAssert.assertJson;
public class GenerateActionIT {
private static final String TOKEN_NAME = "Third Party Application";
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final SonarRuntime runtime = mock(SonarRuntime.class);
private final TokenGenerator tokenGenerator = mock(TokenGenerator.class);
private final MapSettings mapSettings = new MapSettings();
private final Configuration configuration = mapSettings.asConfig();
private final GenerateActionValidation validation = new GenerateActionValidation(configuration, runtime);
private final ComponentFinder componentFinder = new ComponentFinder(db.getDbClient(), new ResourceTypesRule());
private final WsActionTester ws = new WsActionTester(
new GenerateAction(db.getDbClient(), System2.INSTANCE, componentFinder, tokenGenerator, new UserTokenSupport(db.getDbClient(), userSession), validation));
@Before
public void setUp() {
when(tokenGenerator.generate(USER_TOKEN)).thenReturn("123456789");
when(tokenGenerator.generate(GLOBAL_ANALYSIS_TOKEN)).thenReturn("sqa_123456789");
when(tokenGenerator.generate(PROJECT_ANALYSIS_TOKEN)).thenReturn("sqp_123456789");
when(tokenGenerator.hash(anyString())).thenReturn("987654321");
when(runtime.getEdition()).thenReturn(ENTERPRISE); // by default, a Sonar version that supports the max allowed lifetime token property
}
@Test
public void generate_action() {
WebService.Action action = ws.getDef();
assertThat(action.key()).isEqualTo("generate");
assertThat(action.since()).isEqualTo("5.3");
assertThat(action.responseExampleAsString()).isNotEmpty();
assertThat(action.isPost()).isTrue();
assertThat(action.param(PARAM_LOGIN).isRequired()).isFalse();
assertThat(action.param(PARAM_NAME).isRequired()).isTrue();
assertThat(action.param(PARAM_TYPE).isRequired()).isFalse();
assertThat(action.param(PARAM_TYPE).since()).isEqualTo("9.5");
assertThat(action.param(PARAM_PROJECT_KEY).isRequired()).isFalse();
assertThat(action.param(PARAM_PROJECT_KEY).since()).isEqualTo("9.5");
assertThat(action.param(PARAM_EXPIRATION_DATE).isRequired()).isFalse();
assertThat(action.param(PARAM_EXPIRATION_DATE).since()).isEqualTo("9.6");
}
@Test
public void json_example() {
UserDto user1 = db.users().insertUser(u -> u.setLogin("grace.hopper"));
logInAsSystemAdministrator();
String response = ws.newRequest()
.setMediaType(MediaTypes.JSON)
.setParam(PARAM_LOGIN, user1.getLogin())
.setParam(PARAM_NAME, TOKEN_NAME)
.execute().getInput();
assertJson(response).ignoreFields("createdAt").ignoreFields("expirationDate").isSimilarTo(getClass().getResource("generate-example.json"));
}
@Test
public void a_user_can_generate_token_for_himself() {
UserDto user = userLogin();
GenerateWsResponse response = newRequest(null, TOKEN_NAME);
assertThat(response.getLogin()).isEqualTo(user.getLogin());
assertThat(response.getCreatedAt()).isNotEmpty();
}
@Test
public void a_user_can_generate_globalAnalysisToken_with_the_global_scan_permission() {
UserDto user = userLogin();
userSession.addPermission(SCAN);
GenerateWsResponse response = newRequest(null, TOKEN_NAME, GLOBAL_ANALYSIS_TOKEN, null);
assertThat(response.getLogin()).isEqualTo(user.getLogin());
assertThat(response.getToken()).startsWith("sqa_");
assertThat(response.getCreatedAt()).isNotEmpty();
}
@Test
public void a_user_can_generate_projectAnalysisToken_with_the_project_global_scan_permission() {
UserDto user = userLogin();
ProjectDto project = db.components().insertPublicProject().getProjectDto();
userSession.addPermission(SCAN);
GenerateWsResponse response = newRequest(null, TOKEN_NAME, PROJECT_ANALYSIS_TOKEN, project.getKey());
assertThat(response.getLogin()).isEqualTo(user.getLogin());
assertThat(response.getToken()).startsWith("sqp_");
assertThat(response.getProjectKey()).isEqualTo(project.getKey());
assertThat(response.getCreatedAt()).isNotEmpty();
}
@Test
public void a_user_can_generate_projectAnalysisToken_with_the_project_scan_permission() {
UserDto user = userLogin();
ProjectDto project = db.components().insertPublicProject().getProjectDto();
userSession.addProjectPermission(SCAN.toString(), project);
GenerateWsResponse response = newRequest(null, TOKEN_NAME, PROJECT_ANALYSIS_TOKEN, project.getKey());
assertThat(response.getLogin()).isEqualTo(user.getLogin());
assertThat(response.getToken()).startsWith("sqp_");
assertThat(response.getProjectKey()).isEqualTo(project.getKey());
assertThat(response.getCreatedAt()).isNotEmpty();
}
@Test
public void a_user_can_generate_projectAnalysisToken_with_the_project_scan_permission_passing_login() {
UserDto user = userLogin();
ProjectDto project = db.components().insertPublicProject().getProjectDto();
userSession.addProjectPermission(SCAN.toString(), project);
GenerateWsResponse responseWithLogin = newRequest(user.getLogin(), TOKEN_NAME, PROJECT_ANALYSIS_TOKEN, project.getKey());
assertThat(responseWithLogin.getLogin()).isEqualTo(user.getLogin());
assertThat(responseWithLogin.getToken()).startsWith("sqp_");
assertThat(responseWithLogin.getProjectKey()).isEqualTo(project.getKey());
assertThat(responseWithLogin.getCreatedAt()).isNotEmpty();
}
@Test
public void a_user_can_generate_token_for_himself_with_expiration_date() {
UserDto user = userLogin();
// A date 10 days in the future with format yyyy-MM-dd
String expirationDateValue = LocalDate.now().plusDays(10).format(DateTimeFormatter.ofPattern(DATE_FORMAT));
GenerateWsResponse response = newRequest(null, TOKEN_NAME, expirationDateValue);
assertThat(response.getLogin()).isEqualTo(user.getLogin());
assertThat(response.getCreatedAt()).isNotEmpty();
assertThat(response.getExpirationDate()).isEqualTo(getFormattedDate(expirationDateValue));
}
@Test
public void an_administrator_can_generate_token_for_users_with_expiration_date() {
UserDto user = userLogin();
logInAsSystemAdministrator();
// A date 10 days in the future with format yyyy-MM-dd
String expirationDateValue = LocalDate.now().plusDays(10).format(DateTimeFormatter.ofPattern(DATE_FORMAT));
GenerateWsResponse response = newRequest(user.getLogin(), TOKEN_NAME, expirationDateValue);
assertThat(response.getLogin()).isEqualTo(user.getLogin());
assertThat(response.getCreatedAt()).isNotEmpty();
assertThat(response.getExpirationDate()).isEqualTo(getFormattedDate(expirationDateValue));
}
@Test
public void fail_if_login_does_not_exist() {
logInAsSystemAdministrator();
assertThatThrownBy(() -> newRequest("unknown-login", "any-name"))
.isInstanceOf(NotFoundException.class)
.hasMessage("User with login 'unknown-login' doesn't exist");
}
@Test
public void fail_if_name_is_blank() {
UserDto user = userLogin();
logInAsSystemAdministrator();
String login = user.getLogin();
assertThatThrownBy(() -> newRequest(login, " "))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The 'name' parameter is missing");
}
@Test
public void fail_if_globalAnalysisToken_created_for_other_user() {
String login = userLogin().getLogin();
logInAsSystemAdministrator();
assertThatThrownBy(() -> newRequest(login, "token 1", GLOBAL_ANALYSIS_TOKEN, null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("A Global Analysis Token cannot be generated for another user.");
}
@Test
public void fail_if_projectAnalysisToken_created_for_other_user() {
String login = userLogin().getLogin();
logInAsSystemAdministrator();
assertThatThrownBy(() -> newRequest(login, "token 1", PROJECT_ANALYSIS_TOKEN, "project 1"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("A Project Analysis Token cannot be generated for another user.");
}
@Test
public void fail_if_globalAnalysisToken_created_without_global_permission() {
userLogin();
assertThatThrownBy(() -> {
newRequest(null, "token 1", GLOBAL_ANALYSIS_TOKEN, null);
})
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void fail_if_projectAnalysisToken_created_without_project_permission() {
userLogin();
String projectKey = db.components().insertPublicProject().getProjectDto().getKey();
assertThatThrownBy(() -> newRequest(null, "token 1", PROJECT_ANALYSIS_TOKEN, projectKey))
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void fail_if_projectAnalysisToken_created_for_blank_projectKey() {
userLogin();
assertThatThrownBy(() -> {
newRequest(null, "token 1", PROJECT_ANALYSIS_TOKEN, null);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("A projectKey is needed when creating Project Analysis Token");
}
@Test
public void fail_if_projectAnalysisToken_created_for_non_existing_project() {
userLogin();
userSession.addPermission(SCAN);
assertThatThrownBy(() -> {
newRequest(null, "token 1", PROJECT_ANALYSIS_TOKEN, "nonExistingProjectKey");
})
.isInstanceOf(NotFoundException.class)
.hasMessage("Project key 'nonExistingProjectKey' not found");
}
@Test
public void fail_if_token_with_same_login_and_name_exists() {
UserDto user = db.users().insertUser();
String login = user.getLogin();
logInAsSystemAdministrator();
db.users().insertToken(user, t -> t.setName(TOKEN_NAME));
assertThatThrownBy(() -> {
newRequest(login, TOKEN_NAME);
})
.isInstanceOf(BadRequestException.class)
.hasMessage(String.format("A user token for login '%s' and name 'Third Party Application' already exists", user.getLogin()));
}
@Test
public void fail_if_expirationDate_format_is_wrong() {
UserDto user = db.users().insertUser();
String login = user.getLogin();
logInAsSystemAdministrator();
assertThatThrownBy(() -> {
newRequest(login, TOKEN_NAME, "21/06/2022");
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Supplied date format for parameter expirationDate is wrong. Please supply date in the ISO 8601 date format (YYYY-MM-DD)");
}
@Test
public void fail_if_expirationDate_is_not_in_future() {
UserDto user = db.users().insertUser();
String login = user.getLogin();
logInAsSystemAdministrator();
assertThatThrownBy(() -> {
newRequest(login, TOKEN_NAME, "2022-06-29");
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(String.format("The minimum value for parameter %s is %s.", PARAM_EXPIRATION_DATE, LocalDate.now().plusDays(1).format(DateTimeFormatter.ISO_DATE)));
}
@Test
public void success_if_expirationDate_is_equal_to_the_max_allowed_token_lifetime() {
String login = userLogin().getLogin();
mapSettings.setProperty(MAX_ALLOWED_TOKEN_LIFETIME, THIRTY_DAYS.getName());
String expirationDateString = LocalDate.now().plusDays(30).format(DateTimeFormatter.ofPattern(DATE_FORMAT));
GenerateWsResponse response = newRequest(login, TOKEN_NAME, expirationDateString);
assertThat(response.getLogin()).isEqualTo(login);
assertThat(response.getCreatedAt()).isNotEmpty();
assertThat(response.getExpirationDate()).isEqualTo(getFormattedDate(expirationDateString));
}
@Test
public void success_if_expirationDate_is_before_the_max_allowed_token_lifetime() {
String login = userLogin().getLogin();
mapSettings.setProperty(MAX_ALLOWED_TOKEN_LIFETIME, THIRTY_DAYS.getName());
String expirationDateString = LocalDate.now().plusDays(29).format(DateTimeFormatter.ofPattern(DATE_FORMAT));
GenerateWsResponse response = newRequest(login, TOKEN_NAME, expirationDateString);
assertThat(response.getLogin()).isEqualTo(login);
assertThat(response.getCreatedAt()).isNotEmpty();
assertThat(response.getExpirationDate()).isEqualTo(getFormattedDate(expirationDateString));
}
@Test
public void success_if_no_expiration_date_is_allowed_with_expiration_date() {
String login = userLogin().getLogin();
mapSettings.setProperty(MAX_ALLOWED_TOKEN_LIFETIME, NO_EXPIRATION.getName());
String expirationDateString = LocalDate.now().plusDays(30).format(DateTimeFormatter.ofPattern(DATE_FORMAT));
GenerateWsResponse response = newRequest(login, TOKEN_NAME, expirationDateString);
assertThat(response.getLogin()).isEqualTo(login);
assertThat(response.getCreatedAt()).isNotEmpty();
assertThat(response.getExpirationDate()).isEqualTo(getFormattedDate(expirationDateString));
}
@Test
public void success_if_no_expiration_date_is_allowed_without_expiration_date() {
String login = userLogin().getLogin();
mapSettings.setProperty(MAX_ALLOWED_TOKEN_LIFETIME, NO_EXPIRATION.getName());
GenerateWsResponse response = newRequest(login, TOKEN_NAME);
assertThat(response.getLogin()).isEqualTo(login);
assertThat(response.getCreatedAt()).isNotEmpty();
}
@Test
public void fail_if_expirationDate_is_after_the_max_allowed_token_lifetime() {
String login = userLogin().getLogin();
mapSettings.setProperty(MAX_ALLOWED_TOKEN_LIFETIME, THIRTY_DAYS.getName());
String expirationDateString = LocalDate.now().plusDays(31).format(DateTimeFormatter.ofPattern(DATE_FORMAT));
// with expiration date
assertThatThrownBy(() -> {
newRequest(login, TOKEN_NAME, expirationDateString);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Tokens expiring after %s are not allowed. Please use a valid expiration date.",
LocalDate.now().plusDays(THIRTY_DAYS.getDays().get()).format(DateTimeFormatter.ISO_DATE));
// without expiration date
when(tokenGenerator.hash(anyString())).thenReturn("random");
assertThatThrownBy(() -> {
newRequest(login, TOKEN_NAME);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Tokens expiring after %s are not allowed. Please use an expiration date.",
LocalDate.now().plusDays(THIRTY_DAYS.getDays().get()).format(DateTimeFormatter.ISO_DATE));
}
@Test
public void max_allowed_token_lifetime_not_enforced_for_unsupported_versions() {
String login = userLogin().getLogin();
mapSettings.setProperty(MAX_ALLOWED_TOKEN_LIFETIME, THIRTY_DAYS.getName());
List.of(DEVELOPER, COMMUNITY).forEach(edition -> {
when(runtime.getEdition()).thenReturn(edition);
when(tokenGenerator.hash(anyString())).thenReturn("987654321" + edition);
GenerateWsResponse response = newRequest(login, TOKEN_NAME + edition);
assertThat(response.getLogin()).isEqualTo(login);
assertThat(response.getCreatedAt()).isNotEmpty();
});
}
@Test
public void max_allowed_token_lifetime_enforced_for_supported_versions() {
String login = userLogin().getLogin();
mapSettings.setProperty(MAX_ALLOWED_TOKEN_LIFETIME, THIRTY_DAYS.getName());
List.of(ENTERPRISE, DATACENTER).forEach(edition -> {
when(runtime.getEdition()).thenReturn(edition);
when(tokenGenerator.hash(anyString())).thenReturn("987654321" + edition);
assertThatThrownBy(() -> {
newRequest(login, TOKEN_NAME);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Tokens expiring after %s are not allowed. Please use an expiration date.",
LocalDate.now().plusDays(THIRTY_DAYS.getDays().get()).format(DateTimeFormatter.ISO_DATE));
});
}
@Test
public void fail_if_token_hash_already_exists_in_db() {
UserDto user = db.users().insertUser();
String login = user.getLogin();
logInAsSystemAdministrator();
when(tokenGenerator.hash(anyString())).thenReturn("987654321");
db.users().insertToken(user, t -> t.setTokenHash("987654321"));
assertThatThrownBy(() -> {
newRequest(login, TOKEN_NAME);
})
.isInstanceOf(ServerException.class)
.hasMessage("Error while generating token. Please try again.");
}
@Test
public void throw_ForbiddenException_if_non_administrator_creates_token_for_someone_else() {
String login = db.users().insertUser().getLogin();
userSession.logIn().setNonSystemAdministrator();
assertThatThrownBy(() -> {
newRequest(login, TOKEN_NAME);
})
.isInstanceOf(ForbiddenException.class);
}
@Test
public void throw_UnauthorizedException_if_not_logged_in() {
String login = db.users().insertUser().getLogin();
userSession.anonymous();
assertThatThrownBy(() -> {
newRequest(login, TOKEN_NAME);
})
.isInstanceOf(UnauthorizedException.class);
}
private GenerateWsResponse newRequest(@Nullable String login, String name) {
TestRequest testRequest = ws.newRequest()
.setParam(PARAM_NAME, name);
if (login != null) {
testRequest.setParam(PARAM_LOGIN, login);
}
return testRequest.executeProtobuf(GenerateWsResponse.class);
}
private GenerateWsResponse newRequest(@Nullable String login, String name, String expirationDate) {
TestRequest testRequest = ws.newRequest()
.setParam(PARAM_NAME, name)
.setParam(PARAM_EXPIRATION_DATE, expirationDate);
if (login != null) {
testRequest.setParam(PARAM_LOGIN, login);
}
return testRequest.executeProtobuf(GenerateWsResponse.class);
}
private GenerateWsResponse newRequest(@Nullable String login, String name, TokenType tokenType, @Nullable String projectKey) {
TestRequest testRequest = ws.newRequest()
.setParam(PARAM_NAME, name)
.setParam(PARAM_TYPE, tokenType.toString());
if (login != null) {
testRequest.setParam(PARAM_LOGIN, login);
}
if (projectKey != null) {
testRequest.setParam(PARAM_PROJECT_KEY, projectKey);
}
return testRequest.executeProtobuf(GenerateWsResponse.class);
}
private UserDto userLogin() {
UserDto user = db.users().insertUser();
userSession.logIn(user);
return user;
}
private void logInAsSystemAdministrator() {
userSession.logIn().setSystemAdministrator();
}
private String getFormattedDate(String expirationDateValue) {
return DateTimeFormatter
.ofPattern(DATETIME_FORMAT)
.format(LocalDate.parse(expirationDateValue, DateTimeFormatter.ofPattern(DATE_FORMAT)).atStartOfDay(ZoneOffset.UTC).withZoneSameInstant(ZoneId.systemDefault()));
}
}
| 22,240 | 39.001799 | 167 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/usertoken/ws/RevokeActionIT.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.usertoken.ws;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserTokenDto;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_LOGIN;
import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_NAME;
public class RevokeActionIT {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private DbClient dbClient = db.getDbClient();
private DbSession dbSession = db.getSession();
private WsActionTester ws = new WsActionTester(new RevokeAction(dbClient, new UserTokenSupport(db.getDbClient(), userSession)));
@Test
public void revoke_action() {
WebService.Action action = ws.getDef();
assertThat(action).isNotNull();
assertThat(action.key()).isEqualTo("revoke");
assertThat(action.since()).isEqualTo("5.3");
assertThat(action.isPost()).isTrue();
assertThat(action.param("login").isRequired()).isFalse();
assertThat(action.param("name").isRequired()).isTrue();
}
@Test
public void delete_token_in_db() {
logInAsSystemAdministrator();
UserDto user1 = db.users().insertUser();
UserDto user2 = db.users().insertUser();
UserTokenDto tokenToDelete = db.users().insertToken(user1);
UserTokenDto tokenToKeep1 = db.users().insertToken(user1);
UserTokenDto tokenToKeep2 = db.users().insertToken(user1);
UserTokenDto tokenFromAnotherUser = db.users().insertToken(user2);
String response = newRequest(user1.getLogin(), tokenToDelete.getName());
assertThat(response).isEmpty();
assertThat(dbClient.userTokenDao().selectByUser(dbSession, user1))
.extracting(UserTokenDto::getName)
.containsExactlyInAnyOrder(tokenToKeep1.getName(), tokenToKeep2.getName());
assertThat(dbClient.userTokenDao().selectByUser(dbSession, user2))
.extracting(UserTokenDto::getName)
.containsExactlyInAnyOrder(tokenFromAnotherUser.getName());
}
@Test
public void user_can_delete_its_own_tokens() {
UserDto user = db.users().insertUser();
UserTokenDto token = db.users().insertToken(user);
userSession.logIn(user);
String response = newRequest(null, token.getName());
assertThat(response).isEmpty();
assertThat(dbClient.userTokenDao().selectByUser(dbSession, user)).isEmpty();
}
@Test
public void does_not_fail_when_incorrect_login_or_name() {
UserDto user = db.users().insertUser();
db.users().insertToken(user);
logInAsSystemAdministrator();
newRequest(user.getLogin(), "another-token-name");
}
@Test
public void throw_ForbiddenException_if_non_administrator_revokes_token_of_someone_else() {
UserDto user = db.users().insertUser();
UserTokenDto token = db.users().insertToken(user);
userSession.logIn();
assertThatThrownBy(() -> {
newRequest(user.getLogin(), token.getName());
})
.isInstanceOf(ForbiddenException.class);
}
@Test
public void throw_UnauthorizedException_if_not_logged_in() {
UserDto user = db.users().insertUser();
UserTokenDto token = db.users().insertToken(user);
userSession.anonymous();
assertThatThrownBy(() -> {
newRequest(user.getLogin(), token.getName());
})
.isInstanceOf(UnauthorizedException.class);
}
@Test
public void fail_if_login_does_not_exist() {
logInAsSystemAdministrator();
assertThatThrownBy(() -> {
newRequest("unknown-login", "any-name");
})
.isInstanceOf(NotFoundException.class)
.hasMessage("User with login 'unknown-login' doesn't exist");
}
private String newRequest(@Nullable String login, String name) {
TestRequest testRequest = ws.newRequest()
.setParam(PARAM_NAME, name);
if (login != null) {
testRequest.setParam(PARAM_LOGIN, login);
}
return testRequest.execute().getInput();
}
private void logInAsSystemAdministrator() {
userSession.logIn().setSystemAdministrator();
}
}
| 5,488 | 33.522013 | 130 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/usertoken/ws/SearchActionIT.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.usertoken.ws;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserTokenDto;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.UserTokens.SearchWsResponse;
import org.sonarqube.ws.UserTokens.SearchWsResponse.UserToken;
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.sonar.api.utils.DateUtils.formatDateTime;
import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_LOGIN;
import static org.sonar.test.JsonAssert.assertJson;
public class SearchActionIT {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private DbClient dbClient = db.getDbClient();
private WsActionTester ws = new WsActionTester(new SearchAction(dbClient, new UserTokenSupport(db.getDbClient(), userSession)));
@Test
public void search_action() {
WebService.Action action = ws.getDef();
assertThat(action).isNotNull();
assertThat(action.key()).isEqualTo("search");
assertThat(action.since()).isEqualTo("5.3");
assertThat(action.isPost()).isFalse();
assertThat(action.param("login").isRequired()).isFalse();
}
@Test
public void search_json_example() {
ProjectDto project1 = db.components().insertPublicProject(p -> p.setKey("project-1").setName("Project 1")).getProjectDto();
UserDto user1 = db.users().insertUser(u -> u.setLogin("grace.hopper"));
UserDto user2 = db.users().insertUser(u -> u.setLogin("ada.lovelace"));
db.users().insertToken(user1, t -> t.setName("Project scan on Travis").setCreatedAt(1448523067221L));
db.users().insertToken(user1, t -> t.setName("Project scan on AppVeyor").setCreatedAt(1438523067221L));
db.users().insertProjectAnalysisToken(user1, t -> t.setName("Project scan on Jenkins")
.setCreatedAt(1428523067221L)
.setExpirationDate(1563055200000L)
.setProjectUuid(project1.getUuid()));
db.users().insertProjectAnalysisToken(user2, t -> t.setName("Project scan on Travis")
.setCreatedAt(141456787123L)
.setProjectUuid(project1.getUuid()));
logInAsSystemAdministrator();
String response = ws.newRequest()
.setParam(PARAM_LOGIN, user1.getLogin())
.execute().getInput();
assertJson(response).isSimilarTo(getClass().getResource("search-example.json"));
}
@Test
public void a_user_can_search_its_own_token() {
UserDto user = db.users().insertUser();
db.users().insertToken(user, t -> t.setName("Project scan on Travis").setCreatedAt(1448523067221L));
userSession.logIn(user);
SearchWsResponse response = newRequest(null);
assertThat(response.getUserTokensCount()).isOne();
}
@Test
public void return_last_connection_date() {
UserDto user = db.users().insertUser();
UserTokenDto token1 = db.users().insertToken(user);
UserTokenDto token2 = db.users().insertToken(user);
db.getDbClient().userTokenDao().updateWithoutAudit(db.getSession(), token1.setLastConnectionDate(10_000_000_000L));
db.commit();
logInAsSystemAdministrator();
SearchWsResponse response = newRequest(user.getLogin());
assertThat(response.getUserTokensList())
.extracting(UserToken::getName, UserToken::hasLastConnectionDate, UserToken::getLastConnectionDate)
.containsExactlyInAnyOrder(
tuple(token1.getName(), true, formatDateTime(10_000_000_000L)),
tuple(token2.getName(), false, ""));
}
@Test
public void expiration_date_is_returned_only_when_set() {
UserDto user = db.users().insertUser();
UserTokenDto token1 = db.users().insertToken(user, t -> t.setExpirationDate(10_000_000_000L));
UserTokenDto token2 = db.users().insertToken(user);
logInAsSystemAdministrator();
SearchWsResponse response = newRequest(user.getLogin());
assertThat(response.getUserTokensList())
.extracting(UserToken::getName, UserToken::getExpirationDate)
.containsExactlyInAnyOrder(
tuple(token1.getName(), formatDateTime(10_000_000_000L)),
tuple(token2.getName(), ""));
}
@Test
public void isExpired_is_returned_only_when_expiration_date_is_set() {
UserDto user = db.users().insertUser();
UserTokenDto token1 = db.users().insertToken(user, t -> t.setExpirationDate(10_000_000_000_000L));
UserTokenDto token2 = db.users().insertToken(user, t -> t.setExpirationDate(1_000_000_000_000L));
UserTokenDto token3 = db.users().insertToken(user);
logInAsSystemAdministrator();
SearchWsResponse response = newRequest(user.getLogin());
assertThat(response.getUserTokensList())
.extracting(UserToken::getName, UserToken::hasIsExpired, UserToken::getIsExpired)
.containsExactlyInAnyOrder(
tuple(token1.getName(), true, false),
tuple(token2.getName(), true, true),
tuple(token3.getName(), false, false));
}
@Test
public void fail_when_login_does_not_exist() {
logInAsSystemAdministrator();
assertThatThrownBy(() -> {
newRequest("unknown-login");
})
.isInstanceOf(NotFoundException.class)
.hasMessage("User with login 'unknown-login' doesn't exist");
}
@Test
public void throw_ForbiddenException_if_a_non_root_administrator_searches_for_tokens_of_someone_else() {
UserDto user = db.users().insertUser();
userSession.logIn();
assertThatThrownBy(() -> {
newRequest(user.getLogin());
})
.isInstanceOf(ForbiddenException.class);
}
@Test
public void throw_UnauthorizedException_if_not_logged_in() {
UserDto user = db.users().insertUser();
userSession.anonymous();
assertThatThrownBy(() -> {
newRequest(user.getLogin());
})
.isInstanceOf(UnauthorizedException.class);
}
private SearchWsResponse newRequest(@Nullable String login) {
TestRequest testRequest = ws.newRequest();
if (login != null) {
testRequest.setParam(PARAM_LOGIN, login);
}
return testRequest.executeProtobuf(SearchWsResponse.class);
}
private void logInAsSystemAdministrator() {
userSession.logIn().setSystemAdministrator();
}
}
| 7,582 | 36.539604 | 130 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/webhook/ws/CreateActionIT.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.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.Configuration;
import org.sonar.api.resources.ResourceTypes;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.UserRole;
import org.sonar.core.util.UuidFactory;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.webhook.WebhookDbTester;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Webhooks.CreateWsResponse;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.AssertionsForClassTypes.tuple;
import static org.mockito.Mockito.mock;
import static org.sonar.db.DbTester.create;
import static org.sonar.server.tester.UserSessionRule.standalone;
import static org.sonar.server.webhook.ws.WebhooksWsParameters.NAME_PARAM;
import static org.sonar.server.webhook.ws.WebhooksWsParameters.PROJECT_KEY_PARAM;
import static org.sonar.server.webhook.ws.WebhooksWsParameters.URL_PARAM;
import static org.sonar.server.ws.KeyExamples.NAME_WEBHOOK_EXAMPLE_001;
import static org.sonar.server.ws.KeyExamples.URL_WEBHOOK_EXAMPLE_001;
public class CreateActionIT {
@Rule
public UserSessionRule userSession = standalone();
@Rule
public DbTester db = create();
private final DbClient dbClient = db.getDbClient();
private final WebhookDbTester webhookDbTester = db.webhooks();
private final ComponentDbTester componentDbTester = db.components();
private final UuidFactory uuidFactory = UuidFactoryFast.getInstance();
private final Configuration configuration = mock(Configuration.class);
private final NetworkInterfaceProvider networkInterfaceProvider = mock(NetworkInterfaceProvider.class);
private final WebhookSupport webhookSupport = new WebhookSupport(userSession, configuration, networkInterfaceProvider);
private final ResourceTypes resourceTypes = mock(ResourceTypes.class);
private final ComponentFinder componentFinder = new ComponentFinder(dbClient, resourceTypes);
private final CreateAction underTest = new CreateAction(dbClient, userSession, uuidFactory, webhookSupport, componentFinder);
private final WsActionTester wsActionTester = new WsActionTester(underTest);
@Test
public void test_ws_definition() {
WebService.Action action = wsActionTester.getDef();
assertThat(action).isNotNull();
assertThat(action.isInternal()).isFalse();
assertThat(action.isPost()).isTrue();
assertThat(action.responseExampleAsString()).isNotEmpty();
assertThat(action.params())
.extracting(WebService.Param::key, WebService.Param::isRequired)
.containsExactlyInAnyOrder(
tuple("project", false),
tuple("name", true),
tuple("url", true),
tuple("secret", false));
}
@Test
public void create_a_webhook_with_400_length_project_key() {
String longProjectKey = generateStringWithLength(400);
ProjectDto project = componentDbTester.insertPrivateProject(componentDto -> componentDto.setKey(longProjectKey)).getProjectDto();
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
CreateWsResponse response = wsActionTester.newRequest()
.setParam("project", longProjectKey)
.setParam("name", NAME_WEBHOOK_EXAMPLE_001)
.setParam("url", URL_WEBHOOK_EXAMPLE_001)
.setParam("secret", "a_secret")
.executeProtobuf(CreateWsResponse.class);
assertThat(response.getWebhook()).isNotNull();
assertThat(response.getWebhook().getKey()).isNotNull();
assertThat(response.getWebhook().getName()).isEqualTo(NAME_WEBHOOK_EXAMPLE_001);
assertThat(response.getWebhook().getUrl()).isEqualTo(URL_WEBHOOK_EXAMPLE_001);
assertThat(response.getWebhook().getHasSecret()).isTrue();
}
@Test
public void create_a_webhook_with_secret() {
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
CreateWsResponse response = wsActionTester.newRequest()
.setParam("name", NAME_WEBHOOK_EXAMPLE_001)
.setParam("url", URL_WEBHOOK_EXAMPLE_001)
.setParam("secret", "a_secret")
.executeProtobuf(CreateWsResponse.class);
assertThat(response.getWebhook()).isNotNull();
assertThat(response.getWebhook().getKey()).isNotNull();
assertThat(response.getWebhook().getName()).isEqualTo(NAME_WEBHOOK_EXAMPLE_001);
assertThat(response.getWebhook().getUrl()).isEqualTo(URL_WEBHOOK_EXAMPLE_001);
assertThat(response.getWebhook().getHasSecret()).isTrue();
assertThat(webhookDbTester.selectWebhook(response.getWebhook().getKey()))
.isPresent()
.hasValueSatisfying(reloaded -> {
assertThat(reloaded.getName()).isEqualTo(NAME_WEBHOOK_EXAMPLE_001);
assertThat(reloaded.getUrl()).isEqualTo(URL_WEBHOOK_EXAMPLE_001);
assertThat(reloaded.getProjectUuid()).isNull();
assertThat(reloaded.getSecret()).isEqualTo("a_secret");
});
}
@Test
public void create_a_global_webhook() {
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
CreateWsResponse response = wsActionTester.newRequest()
.setParam("name", NAME_WEBHOOK_EXAMPLE_001)
.setParam("url", URL_WEBHOOK_EXAMPLE_001)
.executeProtobuf(CreateWsResponse.class);
assertThat(response.getWebhook()).isNotNull();
assertThat(response.getWebhook().getKey()).isNotNull();
assertThat(response.getWebhook().getName()).isEqualTo(NAME_WEBHOOK_EXAMPLE_001);
assertThat(response.getWebhook().getUrl()).isEqualTo(URL_WEBHOOK_EXAMPLE_001);
assertThat(response.getWebhook().getHasSecret()).isFalse();
}
@Test
public void create_a_webhook_on_project() {
ProjectDto project = componentDbTester.insertPrivateProject().getProjectDto();
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
CreateWsResponse response = wsActionTester.newRequest()
.setParam("project", project.getKey())
.setParam("name", NAME_WEBHOOK_EXAMPLE_001)
.setParam("url", URL_WEBHOOK_EXAMPLE_001)
.executeProtobuf(CreateWsResponse.class);
assertThat(response.getWebhook()).isNotNull();
assertThat(response.getWebhook().getKey()).isNotNull();
assertThat(response.getWebhook().getName()).isEqualTo(NAME_WEBHOOK_EXAMPLE_001);
assertThat(response.getWebhook().getUrl()).isEqualTo(URL_WEBHOOK_EXAMPLE_001);
assertThat(response.getWebhook().getHasSecret()).isFalse();
}
@Test
public void fail_if_project_does_not_exist() {
userSession.logIn();
TestRequest request = wsActionTester.newRequest()
.setParam(PROJECT_KEY_PARAM, "nonexistent-project-uuid")
.setParam(NAME_PARAM, NAME_WEBHOOK_EXAMPLE_001)
.setParam(URL_PARAM, URL_WEBHOOK_EXAMPLE_001);
assertThatThrownBy(request::execute)
.isInstanceOf(NotFoundException.class)
.hasMessage("Project 'nonexistent-project-uuid' not found");
}
@Test
public void fail_if_crossing_maximum_quantity_of_webhooks_on_this_project() {
ProjectDto project = componentDbTester.insertPrivateProject().getProjectDto();
for (int i = 0; i < 10; i++) {
webhookDbTester.insertWebhook(project);
}
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
TestRequest request = wsActionTester.newRequest()
.setParam(PROJECT_KEY_PARAM, project.getKey())
.setParam(NAME_PARAM, NAME_WEBHOOK_EXAMPLE_001)
.setParam(URL_PARAM, URL_WEBHOOK_EXAMPLE_001);
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(format("Maximum number of webhook reached for project '%s'", project.getKey()));
}
@Test
public void fail_if_crossing_maximum_quantity_of_global_webhooks() {
for (int i = 0; i < 10; i++) {
webhookDbTester.insertGlobalWebhook();
}
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
TestRequest request = wsActionTester.newRequest()
.setParam(NAME_PARAM, NAME_WEBHOOK_EXAMPLE_001)
.setParam(URL_PARAM, URL_WEBHOOK_EXAMPLE_001);
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Maximum number of global webhooks reached");
}
@Test
public void fail_if_url_is_not_valid() {
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
TestRequest request = wsActionTester.newRequest()
.setParam(NAME_PARAM, NAME_WEBHOOK_EXAMPLE_001)
.setParam(URL_PARAM, "htp://www.wrong-protocol.com/");
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void fail_if_credential_in_url_is_have_a_wrong_format() {
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
TestRequest request = wsActionTester.newRequest()
.setParam(NAME_PARAM, NAME_WEBHOOK_EXAMPLE_001)
.setParam(URL_PARAM, "http://:www.wrong-protocol.com/");
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void return_UnauthorizedException_if_not_logged_in() {
userSession.anonymous();
TestRequest request = wsActionTester.newRequest()
.setParam(NAME_PARAM, NAME_WEBHOOK_EXAMPLE_001)
.setParam(URL_PARAM, URL_WEBHOOK_EXAMPLE_001);
assertThatThrownBy(request::execute)
.isInstanceOf(UnauthorizedException.class);
}
@Test
public void throw_ForbiddenException_if_project_not_provided_but_user_is_not_administrator() {
userSession.logIn();
TestRequest request = wsActionTester.newRequest()
.setParam(NAME_PARAM, NAME_WEBHOOK_EXAMPLE_001)
.setParam(URL_PARAM, URL_WEBHOOK_EXAMPLE_001);
assertThatThrownBy(request::execute)
.isInstanceOf(ForbiddenException.class).hasMessage("Insufficient privileges");
}
@Test
public void throw_ForbiddenException_if_not_project_administrator() {
ComponentDto project = componentDbTester.insertPrivateProject().getMainBranchComponent();
userSession.logIn();
TestRequest request = wsActionTester.newRequest()
.setParam(NAME_PARAM, NAME_WEBHOOK_EXAMPLE_001)
.setParam(URL_PARAM, URL_WEBHOOK_EXAMPLE_001)
.setParam(PROJECT_KEY_PARAM, project.getKey());
assertThatThrownBy(request::execute)
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void throw_IllegalArgumentException_if_project_key_greater_than_400() {
String longProjectKey = generateStringWithLength(401);
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
TestRequest request = wsActionTester.newRequest()
.setParam("project", longProjectKey)
.setParam("name", NAME_WEBHOOK_EXAMPLE_001)
.setParam("url", URL_WEBHOOK_EXAMPLE_001)
.setParam("secret", "a_secret");
assertThatThrownBy(() -> request.executeProtobuf(CreateWsResponse.class))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("'project' length (401) is longer than the maximum authorized (400)");
}
private static String generateStringWithLength(int length) {
return "x".repeat(Math.max(0, length));
}
}
| 12,529 | 40.627907 | 133 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/webhook/ws/DeleteActionIT.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.ws;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.Configuration;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDbTester;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.webhook.WebhookDbTester;
import org.sonar.db.webhook.WebhookDeliveryDao;
import org.sonar.db.webhook.WebhookDeliveryDbTester;
import org.sonar.db.webhook.WebhookDto;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.AssertionsForClassTypes.tuple;
import static org.mockito.Mockito.mock;
import static org.sonar.db.DbTester.create;
import static org.sonar.db.webhook.WebhookDeliveryTesting.newDto;
import static org.sonar.server.tester.UserSessionRule.standalone;
import static org.sonar.server.webhook.ws.WebhooksWsParameters.KEY_PARAM;
public class DeleteActionIT {
@Rule
public UserSessionRule userSession = standalone();
@Rule
public DbTester db = create();
private final DbClient dbClient = db.getDbClient();
private final DbSession dbSession = db.getSession();
private final WebhookDbTester webhookDbTester = db.webhooks();
private final WebhookDeliveryDbTester webhookDeliveryDbTester = db.webhookDelivery();
private final WebhookDeliveryDao deliveryDao = dbClient.webhookDeliveryDao();
private final ComponentDbTester componentDbTester = db.components();
private final Configuration configuration = mock(Configuration.class);
private final NetworkInterfaceProvider networkInterfaceProvider = mock(NetworkInterfaceProvider.class);
private final WebhookSupport webhookSupport = new WebhookSupport(userSession, configuration, networkInterfaceProvider);
private final DeleteAction underTest = new DeleteAction(dbClient, userSession, webhookSupport);
private final WsActionTester wsActionTester = new WsActionTester(underTest);
@Test
public void test_ws_definition() {
WebService.Action action = wsActionTester.getDef();
assertThat(action).isNotNull();
assertThat(action.isInternal()).isFalse();
assertThat(action.isPost()).isTrue();
assertThat(action.params())
.extracting(WebService.Param::key, WebService.Param::isRequired)
.containsExactlyInAnyOrder(tuple("webhook", true));
}
@Test
public void delete_a_project_webhook() {
ProjectDto project = componentDbTester.insertPrivateProject().getProjectDto();
WebhookDto dto = webhookDbTester.insertWebhook(project);
webhookDeliveryDbTester.insert(newDto().setWebhookUuid(dto.getUuid()));
webhookDeliveryDbTester.insert(newDto().setWebhookUuid(dto.getUuid()));
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
TestResponse response = wsActionTester.newRequest()
.setParam(KEY_PARAM, dto.getUuid())
.execute();
assertThat(response.getStatus()).isEqualTo(HTTP_NO_CONTENT);
Optional<WebhookDto> reloaded = webhookDbTester.selectWebhook(dto.getUuid());
assertThat(reloaded).isEmpty();
int deliveriesCount = deliveryDao.countDeliveriesByWebhookUuid(dbSession, dto.getUuid());
assertThat(deliveriesCount).isZero();
}
@Test
public void delete_a_global_webhook() {
WebhookDto dto = webhookDbTester.insertGlobalWebhook();
webhookDeliveryDbTester.insert(newDto().setWebhookUuid(dto.getUuid()));
webhookDeliveryDbTester.insert(newDto().setWebhookUuid(dto.getUuid()));
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
TestResponse response = wsActionTester.newRequest()
.setParam(KEY_PARAM, dto.getUuid())
.execute();
assertThat(response.getStatus()).isEqualTo(HTTP_NO_CONTENT);
Optional<WebhookDto> reloaded = webhookDbTester.selectWebhook(dto.getUuid());
assertThat(reloaded).isEmpty();
int deliveriesCount = deliveryDao.countDeliveriesByWebhookUuid(dbSession, dto.getUuid());
assertThat(deliveriesCount).isZero();
}
@Test
public void fail_if_webhook_does_not_exist() {
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
TestRequest request = wsActionTester.newRequest()
.setParam(KEY_PARAM, "inexistent-webhook-uuid");
assertThatThrownBy(request::execute)
.isInstanceOf(NotFoundException.class)
.hasMessage("No webhook with key 'inexistent-webhook-uuid'");
}
@Test
public void fail_if_not_logged_in() {
WebhookDto dto = webhookDbTester.insertGlobalWebhook();
userSession.anonymous();
TestRequest request = wsActionTester.newRequest()
.setParam(KEY_PARAM, dto.getUuid());
assertThatThrownBy(request::execute)
.isInstanceOf(UnauthorizedException.class);
}
@Test
public void fail_if_no_permission_on_webhook_scope_project() {
ProjectDto project = componentDbTester.insertPrivateProject().getProjectDto();
WebhookDto dto = webhookDbTester.insertWebhook(project);
userSession.logIn();
TestRequest request = wsActionTester.newRequest()
.setParam(KEY_PARAM, dto.getUuid());
assertThatThrownBy(request::execute)
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void fail_if_no_permission_on_webhook_scope_global() {
WebhookDto dto = webhookDbTester.insertGlobalWebhook();
userSession.logIn();
TestRequest request = wsActionTester.newRequest()
.setParam(KEY_PARAM, dto.getUuid());
assertThatThrownBy(request::execute)
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
}
| 7,024 | 38.466292 | 121 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/webhook/ws/ListActionIT.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.ws;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.Configuration;
import org.sonar.api.resources.ResourceTypes;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.webhook.WebhookDbTester;
import org.sonar.db.webhook.WebhookDeliveryDbTester;
import org.sonar.db.webhook.WebhookDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Webhooks.ListResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.AssertionsForClassTypes.tuple;
import static org.mockito.Mockito.mock;
import static org.sonar.db.DbTester.create;
import static org.sonar.db.webhook.WebhookDeliveryTesting.newDto;
import static org.sonar.db.webhook.WebhookTesting.newGlobalWebhook;
import static org.sonar.server.tester.UserSessionRule.standalone;
import static org.sonar.server.webhook.ws.WebhooksWsParameters.PROJECT_KEY_PARAM;
import static org.sonarqube.ws.Webhooks.LatestDelivery;
import static org.sonarqube.ws.Webhooks.ListResponseElement;
public class ListActionIT {
private static final long NOW = 1_500_000_000L;
private static final long BEFORE = NOW - 1_000L;
@Rule
public UserSessionRule userSession = standalone();
@Rule
public DbTester db = create();
private final DbClient dbClient = db.getDbClient();
private final Configuration configuration = mock(Configuration.class);
private final NetworkInterfaceProvider networkInterfaceProvider = mock(NetworkInterfaceProvider.class);
private final WebhookSupport webhookSupport = new WebhookSupport(userSession, configuration, networkInterfaceProvider);
private final ResourceTypes resourceTypes = mock(ResourceTypes.class);
private final ComponentFinder componentFinder = new ComponentFinder(dbClient, resourceTypes);
private final ListAction underTest = new ListAction(dbClient, userSession, webhookSupport, componentFinder);
private final ComponentDbTester componentDbTester = db.components();
private final WebhookDbTester webhookDbTester = db.webhooks();
private final WebhookDeliveryDbTester webhookDeliveryDbTester = db.webhookDelivery();
private final WsActionTester wsActionTester = new WsActionTester(underTest);
@Test
public void definition() {
WebService.Action action = wsActionTester.getDef();
assertThat(action).isNotNull();
assertThat(action.isInternal()).isFalse();
assertThat(action.isPost()).isFalse();
assertThat(action.responseExampleAsString()).isNotEmpty();
assertThat(action.params())
.extracting(Param::key, Param::isRequired)
.containsExactlyInAnyOrder(
tuple("project", false));
assertThat(action.changelog()).hasSize(2);
}
@Test
public void list_webhooks_and_their_latest_delivery() {
WebhookDto webhook1 = webhookDbTester.insert(newGlobalWebhook("aaa"), null, null);
webhookDeliveryDbTester.insert(newDto("WH1-DELIVERY-1-UUID", webhook1.getUuid(), "COMPONENT_1", "TASK_1").setCreatedAt(BEFORE));
webhookDeliveryDbTester.insert(newDto("WH1-DELIVERY-2-UUID", webhook1.getUuid(), "COMPONENT_1", "TASK_2").setCreatedAt(NOW));
WebhookDto webhook2 = webhookDbTester.insert(newGlobalWebhook("bbb"), null, null);
webhookDeliveryDbTester.insert(newDto("WH2-DELIVERY-1-UUID", webhook2.getUuid(), "COMPONENT_1", "TASK_1").setCreatedAt(BEFORE));
webhookDeliveryDbTester.insert(newDto("WH2-DELIVERY-2-UUID", webhook2.getUuid(), "COMPONENT_1", "TASK_2").setCreatedAt(NOW));
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
ListResponse response = wsActionTester.newRequest().executeProtobuf(ListResponse.class);
List<ListResponseElement> elements = response.getWebhooksList();
assertThat(elements).hasSize(2);
assertThat(elements.get(0)).extracting(ListResponseElement::getKey).isEqualTo(webhook1.getUuid());
assertThat(elements.get(0)).extracting(ListResponseElement::getName).isEqualTo("aaa");
assertThat(elements.get(0).getLatestDelivery()).isNotNull();
assertThat(elements.get(0).getLatestDelivery()).extracting(LatestDelivery::getId).isEqualTo("WH1-DELIVERY-2-UUID");
assertThat(elements.get(1)).extracting(ListResponseElement::getKey).isEqualTo(webhook2.getUuid());
assertThat(elements.get(1)).extracting(ListResponseElement::getName).isEqualTo("bbb");
assertThat(elements.get(1).getLatestDelivery()).isNotNull();
assertThat(elements.get(1).getLatestDelivery()).extracting(LatestDelivery::getId).isEqualTo("WH2-DELIVERY-2-UUID");
}
@Test
public void list_webhooks_when_no_delivery() {
WebhookDto webhook1 = webhookDbTester.insert(newGlobalWebhook("aaa"), null, null);
WebhookDto webhook2 = webhookDbTester.insert(newGlobalWebhook("bbb"), null, null);
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
ListResponse response = wsActionTester.newRequest().executeProtobuf(ListResponse.class);
List<ListResponseElement> elements = response.getWebhooksList();
assertThat(elements).hasSize(2);
assertThat(elements.get(0)).extracting(ListResponseElement::getKey).isEqualTo(webhook1.getUuid());
assertThat(elements.get(0)).extracting(ListResponseElement::getName).isEqualTo("aaa");
assertThat(elements.get(0).hasLatestDelivery()).isFalse();
assertThat(elements.get(1)).extracting(ListResponseElement::getKey).isEqualTo(webhook2.getUuid());
assertThat(elements.get(1)).extracting(ListResponseElement::getName).isEqualTo("bbb");
assertThat(elements.get(1).hasLatestDelivery()).isFalse();
}
@Test
public void obfuscate_credentials_in_webhook_URLs() {
String url = "http://foo:barouf@toto/bop";
String expectedUrl = "http://***:******@toto/bop";
WebhookDto webhook1 = webhookDbTester.insert(newGlobalWebhook("aaa", t -> t.setUrl(url)), null, null);
webhookDeliveryDbTester.insert(newDto("WH1-DELIVERY-1-UUID", webhook1.getUuid(), "COMPONENT_1", "TASK_1").setCreatedAt(BEFORE));
webhookDeliveryDbTester.insert(newDto("WH1-DELIVERY-2-UUID", webhook1.getUuid(), "COMPONENT_1", "TASK_2").setCreatedAt(NOW));
webhookDbTester.insert(newGlobalWebhook("bbb", t -> t.setUrl(url)), null, null);
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
ListResponse response = wsActionTester.newRequest().executeProtobuf(ListResponse.class);
List<ListResponseElement> elements = response.getWebhooksList();
assertThat(elements)
.hasSize(2)
.extracting(ListResponseElement::getUrl)
.containsOnly(expectedUrl);
}
@Test
public void list_global_webhooks() {
WebhookDto dto1 = webhookDbTester.insertGlobalWebhook();
WebhookDto dto2 = webhookDbTester.insertGlobalWebhook().setSecret(null);
// insert a project-specific webhook, that should not be returned when listing global webhooks
webhookDbTester.insertWebhook(componentDbTester.insertPrivateProject().getProjectDto());
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
ListResponse response = wsActionTester.newRequest()
.executeProtobuf(ListResponse.class);
assertThat(response.getWebhooksList())
.extracting(ListResponseElement::getName, ListResponseElement::getUrl)
.containsExactlyInAnyOrder(tuple(dto1.getName(), dto1.getUrl()),
tuple(dto2.getName(), dto2.getUrl()));
}
@Test
public void list_webhooks_with_secret() {
WebhookDto withSecret = webhookDbTester.insertGlobalWebhook();
WebhookDto withoutSecret = newGlobalWebhook().setSecret(null);
webhookDbTester.insert(withoutSecret, null, null);
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
ListResponse response = wsActionTester.newRequest()
.executeProtobuf(ListResponse.class);
assertThat(response.getWebhooksList())
.extracting(ListResponseElement::getName, ListResponseElement::getUrl, ListResponseElement::getHasSecret)
.containsExactlyInAnyOrder(tuple(withSecret.getName(), withSecret.getUrl(), true),
tuple(withoutSecret.getName(), withoutSecret.getUrl(), false));
}
@Test
public void list_project_webhooks_when_project_key_param_is_provided() {
ProjectDto project1 = componentDbTester.insertPrivateProject().getProjectDto();
userSession.logIn().addProjectPermission(UserRole.ADMIN, project1);
WebhookDto dto1 = webhookDbTester.insertWebhook(project1);
WebhookDto dto2 = webhookDbTester.insertWebhook(project1);
ListResponse response = wsActionTester.newRequest()
.setParam(PROJECT_KEY_PARAM, project1.getKey())
.executeProtobuf(ListResponse.class);
assertThat(response.getWebhooksList())
.extracting(ListResponseElement::getName, ListResponseElement::getUrl)
.contains(tuple(dto1.getName(), dto1.getUrl()),
tuple(dto2.getName(), dto2.getUrl()));
}
@Test
public void list_global_webhooks_if_project_key_param_missing() {
WebhookDto dto1 = webhookDbTester.insertGlobalWebhook();
WebhookDto dto2 = webhookDbTester.insertGlobalWebhook();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
ListResponse response = wsActionTester.newRequest()
.executeProtobuf(ListResponse.class);
assertThat(response.getWebhooksList())
.extracting(ListResponseElement::getName, ListResponseElement::getUrl)
.contains(tuple(dto1.getName(), dto1.getUrl()),
tuple(dto2.getName(), dto2.getUrl()));
}
@Test
public void return_NotFoundException_if_requested_project_is_not_found() {
userSession.logIn().setSystemAdministrator();
TestRequest request = wsActionTester.newRequest()
.setParam(PROJECT_KEY_PARAM, "pipo");
assertThatThrownBy(() -> request.executeProtobuf(ListResponse.class))
.isInstanceOf(NotFoundException.class);
}
@Test
public void return_UnauthorizedException_if_not_logged_in() {
userSession.anonymous();
TestRequest request = wsActionTester.newRequest();
assertThatThrownBy(() -> request.executeProtobuf(ListResponse.class))
.isInstanceOf(UnauthorizedException.class);
}
@Test
public void throw_ForbiddenException_if_not_administrator() {
userSession.logIn();
TestRequest request = wsActionTester.newRequest();
assertThatThrownBy(() -> request.executeProtobuf(ListResponse.class))
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void throw_ForbiddenException_if_not_project_administrator() {
ComponentDto project = componentDbTester.insertPrivateProject().getMainBranchComponent();
TestRequest request = wsActionTester.newRequest()
.setParam(PROJECT_KEY_PARAM, project.getKey());
userSession.logIn();
assertThatThrownBy(() -> request.executeProtobuf(ListResponse.class))
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
}
| 12,401 | 43.292857 | 132 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/webhook/ws/UpdateActionIT.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.ws;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.Configuration;
import org.sonar.api.resources.ResourceTypes;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDbTester;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.webhook.WebhookDbTester;
import org.sonar.db.webhook.WebhookDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.AssertionsForClassTypes.tuple;
import static org.mockito.Mockito.mock;
import static org.sonar.db.DbTester.create;
import static org.sonar.server.tester.UserSessionRule.standalone;
import static org.sonar.server.ws.KeyExamples.NAME_WEBHOOK_EXAMPLE_001;
import static org.sonar.server.ws.KeyExamples.URL_WEBHOOK_EXAMPLE_001;
public class UpdateActionIT {
@Rule
public UserSessionRule userSession = standalone();
@Rule
public DbTester db = create();
private final DbClient dbClient = db.getDbClient();
private final WebhookDbTester webhookDbTester = db.webhooks();
private final ComponentDbTester componentDbTester = db.components();
private final Configuration configuration = mock(Configuration.class);
private final NetworkInterfaceProvider networkInterfaceProvider = mock(NetworkInterfaceProvider.class);
private final WebhookSupport webhookSupport = new WebhookSupport(userSession, configuration, networkInterfaceProvider);
private final ResourceTypes resourceTypes = mock(ResourceTypes.class);
private final ComponentFinder componentFinder = new ComponentFinder(dbClient, resourceTypes);
private final UpdateAction underTest = new UpdateAction(dbClient, userSession, webhookSupport, componentFinder);
private final WsActionTester wsActionTester = new WsActionTester(underTest);
@Test
public void test_ws_definition() {
WebService.Action action = wsActionTester.getDef();
assertThat(action).isNotNull();
assertThat(action.isInternal()).isFalse();
assertThat(action.isPost()).isTrue();
assertThat(action.params())
.extracting(WebService.Param::key, WebService.Param::isRequired)
.containsExactlyInAnyOrder(
tuple("webhook", true),
tuple("name", true),
tuple("url", true),
tuple("secret", false));
}
@Test
public void update_a_project_webhook_with_required_fields() {
ProjectDto project = componentDbTester.insertPrivateProject().getProjectDto();
WebhookDto dto = webhookDbTester.insertWebhook(project);
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
TestResponse response = wsActionTester.newRequest()
.setParam("webhook", dto.getUuid())
.setParam("name", NAME_WEBHOOK_EXAMPLE_001)
.setParam("url", URL_WEBHOOK_EXAMPLE_001)
.execute();
assertThat(response.getStatus()).isEqualTo(HTTP_NO_CONTENT);
Optional<WebhookDto> reloaded = webhookDbTester.selectWebhook(dto.getUuid());
assertThat(reloaded).isPresent();
assertThat(reloaded.get().getName()).isEqualTo(NAME_WEBHOOK_EXAMPLE_001);
assertThat(reloaded.get().getUrl()).isEqualTo(URL_WEBHOOK_EXAMPLE_001);
assertThat(reloaded.get().getProjectUuid()).isEqualTo(dto.getProjectUuid());
assertThat(reloaded.get().getSecret()).isEqualTo(dto.getSecret());
}
@Test
public void update_with_empty_secrets_removes_the_secret() {
ProjectDto project = componentDbTester.insertPrivateProject().getProjectDto();
WebhookDto dto = webhookDbTester.insertWebhook(project);
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
TestResponse response = wsActionTester.newRequest()
.setParam("webhook", dto.getUuid())
.setParam("name", NAME_WEBHOOK_EXAMPLE_001)
.setParam("url", URL_WEBHOOK_EXAMPLE_001)
.setParam("secret", "")
.execute();
assertThat(response.getStatus()).isEqualTo(HTTP_NO_CONTENT);
Optional<WebhookDto> reloaded = webhookDbTester.selectWebhook(dto.getUuid());
assertThat(reloaded).isPresent();
assertThat(reloaded.get().getName()).isEqualTo(NAME_WEBHOOK_EXAMPLE_001);
assertThat(reloaded.get().getUrl()).isEqualTo(URL_WEBHOOK_EXAMPLE_001);
assertThat(reloaded.get().getProjectUuid()).isEqualTo(dto.getProjectUuid());
assertThat(reloaded.get().getSecret()).isEqualTo(null);
}
@Test
public void update_a_project_webhook_with_all_fields() {
ProjectDto project = componentDbTester.insertPrivateProject().getProjectDto();
WebhookDto dto = webhookDbTester.insertWebhook(project);
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
TestResponse response = wsActionTester.newRequest()
.setParam("webhook", dto.getUuid())
.setParam("name", NAME_WEBHOOK_EXAMPLE_001)
.setParam("url", URL_WEBHOOK_EXAMPLE_001)
.setParam("secret", "a_new_secret")
.execute();
assertThat(response.getStatus()).isEqualTo(HTTP_NO_CONTENT);
Optional<WebhookDto> reloaded = webhookDbTester.selectWebhook(dto.getUuid());
assertThat(reloaded).isPresent();
assertThat(reloaded.get().getName()).isEqualTo(NAME_WEBHOOK_EXAMPLE_001);
assertThat(reloaded.get().getUrl()).isEqualTo(URL_WEBHOOK_EXAMPLE_001);
assertThat(reloaded.get().getProjectUuid()).isEqualTo(dto.getProjectUuid());
assertThat(reloaded.get().getSecret()).isEqualTo("a_new_secret");
}
@Test
public void update_a_global_webhook() {
WebhookDto dto = webhookDbTester.insertGlobalWebhook();
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
TestResponse response = wsActionTester.newRequest()
.setParam("webhook", dto.getUuid())
.setParam("name", NAME_WEBHOOK_EXAMPLE_001)
.setParam("url", URL_WEBHOOK_EXAMPLE_001)
.setParam("secret", "a_new_secret")
.execute();
assertThat(response.getStatus()).isEqualTo(HTTP_NO_CONTENT);
Optional<WebhookDto> reloaded = webhookDbTester.selectWebhook(dto.getUuid());
assertThat(reloaded).isPresent();
assertThat(reloaded.get().getName()).isEqualTo(NAME_WEBHOOK_EXAMPLE_001);
assertThat(reloaded.get().getUrl()).isEqualTo(URL_WEBHOOK_EXAMPLE_001);
assertThat(reloaded.get().getProjectUuid()).isNull();
assertThat(reloaded.get().getSecret()).isEqualTo("a_new_secret");
}
@Test
public void fail_if_webhook_does_not_exist() {
userSession.logIn().addPermission(GlobalPermission.ADMINISTER);
TestRequest request = wsActionTester.newRequest()
.setParam("webhook", "inexistent-webhook-uuid")
.setParam("name", NAME_WEBHOOK_EXAMPLE_001)
.setParam("url", URL_WEBHOOK_EXAMPLE_001);
assertThatThrownBy(request::execute)
.isInstanceOf(NotFoundException.class)
.hasMessage("No webhook with key 'inexistent-webhook-uuid'");
}
@Test
public void fail_if_not_logged_in() {
WebhookDto dto = webhookDbTester.insertGlobalWebhook();
userSession.anonymous();
TestRequest request = wsActionTester.newRequest()
.setParam("webhook", dto.getUuid())
.setParam("name", NAME_WEBHOOK_EXAMPLE_001)
.setParam("url", URL_WEBHOOK_EXAMPLE_001);
assertThatThrownBy(request::execute)
.isInstanceOf(UnauthorizedException.class);
}
@Test
public void fail_if_no_permission_on_webhook_scope_project() {
ProjectDto project = componentDbTester.insertPrivateProject().getProjectDto();
WebhookDto dto = webhookDbTester.insertWebhook(project);
userSession.logIn();
TestRequest request = wsActionTester.newRequest()
.setParam("webhook", dto.getUuid())
.setParam("name", NAME_WEBHOOK_EXAMPLE_001)
.setParam("url", URL_WEBHOOK_EXAMPLE_001);
assertThatThrownBy(request::execute)
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void fail_if_no_permission_on_webhook_scope_global() {
WebhookDto dto = webhookDbTester.insertGlobalWebhook();
userSession.logIn();
TestRequest request = wsActionTester.newRequest()
.setParam("webhook", dto.getUuid())
.setParam("name", NAME_WEBHOOK_EXAMPLE_001)
.setParam("url", URL_WEBHOOK_EXAMPLE_001);
assertThatThrownBy(request::execute)
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void fail_if_url_is_not_valid() {
ProjectDto project = componentDbTester.insertPrivateProject().getProjectDto();
WebhookDto dto = webhookDbTester.insertWebhook(project);
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
TestRequest request = wsActionTester.newRequest()
.setParam("webhook", dto.getUuid())
.setParam("name", NAME_WEBHOOK_EXAMPLE_001)
.setParam("url", "htp://www.wrong-protocol.com/");
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void fail_if_credential_in_url_is_have_a_wrong_format() {
ProjectDto project = componentDbTester.insertPrivateProject().getProjectDto();
WebhookDto dto = webhookDbTester.insertWebhook(project);
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
TestRequest request = wsActionTester.newRequest()
.setParam("webhook", dto.getUuid())
.setParam("name", NAME_WEBHOOK_EXAMPLE_001)
.setParam("url", "http://:www.wrong-protocol.com/");
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class);
}
}
| 10,930 | 41.204633 | 121 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/webhook/ws/WebhookDeliveriesActionIT.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.ws;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.webhook.WebhookDeliveryDbTester;
import org.sonar.db.webhook.WebhookDeliveryDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.component.TestComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Webhooks;
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.sonar.db.webhook.WebhookDeliveryTesting.newDto;
import static org.sonar.test.JsonAssert.assertJson;
public class WebhookDeliveriesActionIT {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private DbClient dbClient = db.getDbClient();
private WebhookDeliveryDbTester webhookDeliveryDbTester = db.webhookDelivery();
private WsActionTester ws;
private ProjectDto project;
private ProjectDto otherProject;
@Before
public void setUp() {
ComponentFinder componentFinder = TestComponentFinder.from(db);
WebhookDeliveriesAction underTest = new WebhookDeliveriesAction(dbClient, userSession, componentFinder);
ws = new WsActionTester(underTest);
project = db.components().insertPrivateProject(c -> c.setKey("my-project")).getProjectDto();
otherProject = db.components().insertPrivateProject(c -> c.setKey("other-project")).getProjectDto();
}
@Test
public void test_definition() {
assertThat(ws.getDef().params()).extracting(WebService.Param::key).containsExactlyInAnyOrder("componentKey", "ceTaskId", "webhook", "p", "ps");
assertThat(ws.getDef().isPost()).isFalse();
assertThat(ws.getDef().isInternal()).isFalse();
assertThat(ws.getDef().responseExampleAsString()).isNotEmpty();
}
@Test
public void throw_UnauthorizedException_if_anonymous() {
TestRequest request = ws.newRequest();
assertThatThrownBy(request::execute)
.isInstanceOf(UnauthorizedException.class);
}
@Test
public void search_by_component_and_return_no_records() {
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
Webhooks.DeliveriesWsResponse response = ws.newRequest()
.setParam("componentKey", project.getKey())
.executeProtobuf(Webhooks.DeliveriesWsResponse.class);
assertThat(response.getDeliveriesCount()).isZero();
}
@Test
public void search_by_task_and_return_no_records() {
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
Webhooks.DeliveriesWsResponse response = ws.newRequest()
.setParam("ceTaskId", "t1")
.executeProtobuf(Webhooks.DeliveriesWsResponse.class);
assertThat(response.getDeliveriesCount()).isZero();
}
@Test
public void search_by_webhook_and_return_no_records() {
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
Webhooks.DeliveriesWsResponse response = ws.newRequest()
.setParam("webhook", "t1")
.executeProtobuf(Webhooks.DeliveriesWsResponse.class);
assertThat(response.getDeliveriesCount()).isZero();
}
@Test
public void search_by_component_and_return_records_of_example() {
WebhookDeliveryDto dto = newDto()
.setUuid("d1")
.setProjectUuid(project.getUuid())
.setCeTaskUuid("task-1")
.setName("Jenkins")
.setUrl("http://jenkins")
.setCreatedAt(1_500_000_000_000L)
.setSuccess(true)
.setDurationMs(10)
.setHttpStatus(200);
dbClient.webhookDeliveryDao().insert(db.getSession(), dto);
db.commit();
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
String json = ws.newRequest()
.setParam("componentKey", project.getKey())
.execute()
.getInput();
assertJson(json).isSimilarTo(ws.getDef().responseExampleAsString());
}
@Test
public void search_by_task_and_return_records() {
WebhookDeliveryDto dto1 = newDto().setProjectUuid(project.getUuid()).setCeTaskUuid("t1");
WebhookDeliveryDto dto2 = newDto().setProjectUuid(project.getUuid()).setCeTaskUuid("t1");
WebhookDeliveryDto dto3 = newDto().setProjectUuid(project.getUuid()).setCeTaskUuid("t2");
dbClient.webhookDeliveryDao().insert(db.getSession(), dto1);
dbClient.webhookDeliveryDao().insert(db.getSession(), dto2);
dbClient.webhookDeliveryDao().insert(db.getSession(), dto3);
db.commit();
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
Webhooks.DeliveriesWsResponse response = ws.newRequest()
.setParam("ceTaskId", "t1")
.executeProtobuf(Webhooks.DeliveriesWsResponse.class);
assertThat(response.getDeliveriesCount()).isEqualTo(2);
assertThat(response.getDeliveriesList()).extracting(Webhooks.Delivery::getId).containsOnly(dto1.getUuid(), dto2.getUuid());
}
@Test
public void search_by_webhook_and_return_records() {
WebhookDeliveryDto dto1 = newDto().setProjectUuid(project.getUuid()).setCeTaskUuid("t1").setWebhookUuid("wh-1-uuid");
WebhookDeliveryDto dto2 = newDto().setProjectUuid(project.getUuid()).setCeTaskUuid("t1").setWebhookUuid("wh-1-uuid");
WebhookDeliveryDto dto3 = newDto().setProjectUuid(project.getUuid()).setCeTaskUuid("t2").setWebhookUuid("wh-2-uuid");
WebhookDeliveryDto dto4 = newDto().setProjectUuid(otherProject.getUuid()).setCeTaskUuid("t4").setWebhookUuid("wh-1-uuid");
WebhookDeliveryDto dto5 = newDto().setProjectUuid(otherProject.getUuid()).setCeTaskUuid("t5").setWebhookUuid("wh-1-uuid");
dbClient.webhookDeliveryDao().insert(db.getSession(), dto1);
dbClient.webhookDeliveryDao().insert(db.getSession(), dto2);
dbClient.webhookDeliveryDao().insert(db.getSession(), dto3);
dbClient.webhookDeliveryDao().insert(db.getSession(), dto4);
dbClient.webhookDeliveryDao().insert(db.getSession(), dto5);
db.commit();
userSession.logIn().addProjectPermission(UserRole.ADMIN, project, otherProject);
Webhooks.DeliveriesWsResponse response = ws.newRequest()
.setParam("webhook", "wh-1-uuid")
.executeProtobuf(Webhooks.DeliveriesWsResponse.class);
assertThat(response.getDeliveriesCount()).isEqualTo(4);
assertThat(response.getDeliveriesList()).extracting(Webhooks.Delivery::getId)
.containsOnly(dto1.getUuid(), dto2.getUuid(), dto4.getUuid(), dto5.getUuid());
assertThat(response.getDeliveriesList()).extracting(Webhooks.Delivery::getId, Webhooks.Delivery::getComponentKey)
.containsOnly(
tuple(dto1.getUuid(), project.getKey()),
tuple(dto2.getUuid(), project.getKey()),
tuple(dto4.getUuid(), otherProject.getKey()),
tuple(dto5.getUuid(), otherProject.getKey()));
}
@Test
public void validate_default_pagination() {
for (int i = 0; i < 15; i++) {
webhookDeliveryDbTester.insert(newDto().setProjectUuid(project.getUuid()).setCeTaskUuid("t1").setWebhookUuid("wh-1-uuid"));
}
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
Webhooks.DeliveriesWsResponse response = ws.newRequest()
.setParam("webhook", "wh-1-uuid")
.executeProtobuf(Webhooks.DeliveriesWsResponse.class);
assertThat(response.getDeliveriesCount()).isEqualTo(10);
}
@Test
public void validate_pagination_first_page() {
for (int i = 0; i < 12; i++) {
webhookDeliveryDbTester.insert(newDto().setProjectUuid(project.getUuid()).setCeTaskUuid("t1").setWebhookUuid("wh-1-uuid"));
}
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
Webhooks.DeliveriesWsResponse response = ws.newRequest()
.setParam("webhook", "wh-1-uuid")
.setParam("p", "1")
.setParam("ps", "10")
.executeProtobuf(Webhooks.DeliveriesWsResponse.class);
assertThat(response.getDeliveriesCount()).isEqualTo(10);
assertThat(response.getPaging().getTotal()).isEqualTo(12);
assertThat(response.getPaging().getPageIndex()).isOne();
}
@Test
public void validate_pagination_last_page() {
for (int i = 0; i < 12; i++) {
webhookDeliveryDbTester.insert(newDto().setProjectUuid(project.getUuid()).setCeTaskUuid("t1").setWebhookUuid("wh-1-uuid"));
}
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
Webhooks.DeliveriesWsResponse response = ws.newRequest()
.setParam("webhook", "wh-1-uuid")
.setParam("p", "2")
.setParam("ps", "10")
.executeProtobuf(Webhooks.DeliveriesWsResponse.class);
assertThat(response.getDeliveriesCount()).isEqualTo(2);
assertThat(response.getPaging().getTotal()).isEqualTo(12);
assertThat(response.getPaging().getPageIndex()).isEqualTo(2);
}
@Test
public void search_by_component_and_throw_ForbiddenException_if_not_admin_of_project() {
WebhookDeliveryDto dto = newDto()
.setProjectUuid(project.getUuid());
dbClient.webhookDeliveryDao().insert(db.getSession(), dto);
db.commit();
userSession.logIn().addProjectPermission(UserRole.USER, project);
TestRequest request = ws.newRequest()
.setParam("componentKey", project.getKey());
assertThatThrownBy(request::execute)
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void search_by_task_and_throw_ForbiddenException_if_not_admin_of_project() {
WebhookDeliveryDto dto = newDto()
.setProjectUuid(project.getUuid());
dbClient.webhookDeliveryDao().insert(db.getSession(), dto);
db.commit();
userSession.logIn().addProjectPermission(UserRole.USER, project);
TestRequest request = ws.newRequest()
.setParam("ceTaskId", dto.getCeTaskUuid());
assertThatThrownBy(request::execute)
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void throw_IAE_if_both_component_and_task_parameters_are_set() {
userSession.logIn();
TestRequest request = ws.newRequest()
.setParam("componentKey", project.getKey())
.setParam("ceTaskId", "t1");
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Either 'ceTaskId' or 'componentKey' or 'webhook' must be provided");
}
@Test
public void throw_IAE_if_both_component_and_webhook_are_set() {
userSession.logIn();
TestRequest request = ws.newRequest()
.setParam("componentKey", project.getKey())
.setParam("webhook", "wh-uuid");
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Either 'ceTaskId' or 'componentKey' or 'webhook' must be provided");
}
}
| 11,938 | 38.273026 | 147 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/webhook/ws/WebhookDeliveryActionIT.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.ws;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.webhook.WebhookDeliveryDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.component.TestComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.MediaTypes;
import org.sonarqube.ws.Webhooks;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.webhook.WebhookDeliveryTesting.newDto;
import static org.sonar.test.JsonAssert.assertJson;
public class WebhookDeliveryActionIT {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create();
private DbClient dbClient = db.getDbClient();
private WsActionTester ws;
private ProjectDto project;
@Before
public void setUp() {
ComponentFinder componentFinder = TestComponentFinder.from(db);
WebhookDeliveryAction underTest = new WebhookDeliveryAction(dbClient, userSession, componentFinder);
ws = new WsActionTester(underTest);
project = db.components().insertPrivateProject(c -> c.setKey("my-project")).getProjectDto();
}
@Test
public void test_definition() {
WebService.Action definition = ws.getDef();
assertThat(definition.isPost()).isFalse();
assertThat(definition.isInternal()).isFalse();
assertThat(definition.responseExampleAsString()).isNotEmpty();
assertThat(definition.params()).hasSize(1);
assertThat(definition.param("deliveryId").isRequired()).isTrue();
}
@Test
public void throw_UnauthorizedException_if_anonymous() {
assertThatThrownBy(() -> ws.newRequest().execute())
.isInstanceOf(UnauthorizedException.class);
}
@Test
public void return_404_if_delivery_does_not_exist() {
userSession.logIn();
assertThatThrownBy(() -> ws.newRequest()
.setMediaType(MediaTypes.PROTOBUF)
.setParam("deliveryId", "does_not_exist")
.execute())
.isInstanceOf(NotFoundException.class);
}
@Test
public void load_the_delivery_of_example() {
WebhookDeliveryDto dto = newDto()
.setUuid("d1")
.setProjectUuid(project.getUuid())
.setCeTaskUuid("task-1")
.setName("Jenkins")
.setUrl("http://jenkins")
.setCreatedAt(1_500_000_000_000L)
.setSuccess(true)
.setDurationMs(10)
.setHttpStatus(200)
.setPayload("{\"status\"=\"SUCCESS\"}");
dbClient.webhookDeliveryDao().insert(db.getSession(), dto);
db.commit();
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
String json = ws.newRequest()
.setParam("deliveryId", dto.getUuid())
.execute()
.getInput();
assertJson(json).isSimilarTo(ws.getDef().responseExampleAsString());
}
@Test
public void return_delivery_that_failed_to_be_sent() {
WebhookDeliveryDto dto = newDto()
.setProjectUuid(project.getUuid())
.setSuccess(false)
.setHttpStatus(null)
.setErrorStacktrace("IOException -> can not connect");
dbClient.webhookDeliveryDao().insert(db.getSession(), dto);
db.commit();
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
Webhooks.DeliveryWsResponse response = ws.newRequest()
.setParam("deliveryId", dto.getUuid())
.executeProtobuf(Webhooks.DeliveryWsResponse.class);
Webhooks.Delivery actual = response.getDelivery();
assertThat(actual.hasHttpStatus()).isFalse();
assertThat(actual.getErrorStacktrace()).isEqualTo(dto.getErrorStacktrace());
}
@Test
public void return_delivery_with_none_of_optional_fields() {
WebhookDeliveryDto dto = newDto()
.setProjectUuid(project.getUuid())
.setCeTaskUuid(null)
.setHttpStatus(null)
.setErrorStacktrace(null)
.setAnalysisUuid(null);
dbClient.webhookDeliveryDao().insert(db.getSession(), dto);
db.commit();
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
Webhooks.DeliveryWsResponse response = ws.newRequest()
.setParam("deliveryId", dto.getUuid())
.executeProtobuf(Webhooks.DeliveryWsResponse.class);
Webhooks.Delivery actual = response.getDelivery();
assertThat(actual.hasHttpStatus()).isFalse();
assertThat(actual.hasErrorStacktrace()).isFalse();
assertThat(actual.hasCeTaskId()).isFalse();
}
@Test
public void throw_ForbiddenException_if_not_admin_of_project() {
WebhookDeliveryDto dto = newDto()
.setProjectUuid(project.getUuid());
dbClient.webhookDeliveryDao().insert(db.getSession(), dto);
db.commit();
userSession.logIn().addProjectPermission(UserRole.USER, project);
assertThatThrownBy(() -> ws.newRequest()
.setMediaType(MediaTypes.PROTOBUF)
.setParam("deliveryId", dto.getUuid())
.execute())
.isInstanceOf(ForbiddenException.class)
.hasMessageContaining("Insufficient privileges");
}
}
| 6,210 | 34.090395 | 104 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.